> For the complete documentation index, see [llms.txt](https://joshualbarb.gitbook.io/leetcode-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://joshualbarb.gitbook.io/leetcode-problems/two-pointers/3sum-smaller.md).

# 3Sum Smaller

## Problem

Given an array `arr` of unsorted numbers and a target sum, **count all triplets** in it such that **`arr[i] + arr[j] + arr[k] < target`** where `i`, `j`, and `k` are three different indices. Write a function to return the count of such triplets.

{% hint style="info" %}
For example:

```
Input: [-1, 0, 2, 3], target=3 
Output: 2
Explanation: There are two triplets whose sum
is less than the target: [-1, 0, 3], 
[-1, 0, 2]
```

```
Input: [-1, 4, 2, 1, 3], target=5 
Output: 4
Explanation: There are four triplets whose 
sum is less than the target: [-1, 1, 4], 
[-1, 1, 3], [-1, 1, 2], [-1, 2, 3]
```

{% endhint %}

## Solution

```
def triplet_with_smaller_sum(arr, target):
  count = 0
  arr.sort()

  for i in range(len(arr)-2):
    j = i+1
    k = len(arr)-1

    while j < k:
      sums = arr[i]+arr[j]+arr[k]
      if sums < target:
      
      # since arr[k] >= arr[j], therefore, we can 
      #replace arr[k] by any number between
      #left and right to get a sum less than the target sum
        count+=k-j
        j+=1
      else: #sum is too large
        k-=1

      
      

  return count

```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/two-pointers/3sum-smaller.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
