3Sum Smaller

Medium Two Pointers

Problem

Given an integer array nums and an integer target, return the number of index triplets i, j, k with 0 <= i < j < k < nums.length such that nums[i] + nums[j] + nums[k] < target.

  • 0 ≤ nums.length ≤ 3500
  • −10⁵ ≤ nums[i] ≤ 10⁵
  • −10⁵ ≤ target ≤ 10⁵

Example

Input: nums = [-2,0,1,3], target = 2
Output: 2

The triplets that satisfy the condition are (-2,0,1) with sum -1 < 2 and (-2,0,3) with sum 1 < 2. The brute-force approach would check all triplets, which is O(n^3). The key insight is to sort the array and use two pointers to efficiently count valid pairs for each fixed first element.

Approach

Straightforward Solution

A brute-force triple nested loop checks all triplets, resulting in O(n^3) time complexity, which is too slow for large inputs.

Core Observation

The problem requires counting triplets with sums less than a target, which suggests exploring combinations efficiently. Sorting the array allows leveraging the order to prune search space.

Path to Optimal

Sorting the array enables a two-pointer approach for the inner two elements. Fixing one element, the two pointers scan from both ends inward to count all pairs that satisfy the sum condition in O(n) time per fixed element, reducing total complexity to O(n^2).

Optimal Approach

Sort nums. For each index i, use two pointers left and right to find pairs where nums[i] + nums[left] + nums[right] < target. When the sum is less than target, all elements between left and right form valid pairs with i, so increment count by right - left and move left pointer forward. Otherwise, move right pointer backward. Return total count after processing all i.

Time

O(n^2)

Sorting takes O(n log n). The outer loop runs O(n) times, and the inner two-pointer scan runs O(n) per iteration, resulting in O(n^2) total time.

Space

O(1)

Sorting is done in-place, and only a few variables are used for pointers and counters, resulting in O(1) auxiliary space.

Pattern Spotlight

Two Pointers (Sorted Array Pair Counting)

When counting pairs or triplets with sum constraints in a sorted array, fix one element and use two pointers to efficiently count all valid pairs by exploiting the sorted order to skip unnecessary checks.

Solution

1class Solution:
2 def threeSumSmaller(self, nums: list[int], target: int) -> int:
3 nums.sort()
4 count = 0
5
6 for i in range(len(nums) - 2):
7 left = i + 1
8 right = len(nums) - 1
9
10 while left < right:
11 total = nums[i] + nums[left] + nums[right]
12
13 if total < target:
14 count += right - left
15 left += 1
16 else:
17 right -= 1
18
19 return count

Step-by-Step Solution

1

Sort the Array and Initialize the Count

3nums.sort()
4count = 0

Objective

To prepare the input for efficient two-pointer traversal and set up the accumulator for valid triplets.

Key Insight

Sorting the array is essential because it allows the two-pointer technique to work by leveraging the order of elements. Initializing the count variable sets up the accumulator for the total number of valid triplets found.

Interview Quick-Check

Core Logic

Sorting enables the two-pointer approach by ensuring that increasing the left pointer increases the sum and decreasing the right pointer decreases the sum.

Common Pitfalls & Bugs

Forgetting to sort the array breaks the logic of the two-pointer approach, leading to incorrect counts.

2

Iterate Over the Array Fixing the First Element of Triplets

6for i in range(len(nums) - 2):

Objective

To select each element as the fixed first element and find pairs that complete triplets with sums less than the target.

Key Insight

Fixing one element reduces the problem to finding pairs with sums less than a reduced target. This transforms the triple sum problem into a two-sum variant solvable with two pointers, enabling efficient counting.

Interview Quick-Check

Core Logic

Fixing the first element and searching for pairs with two pointers reduces the problem from O(n^3) to O(n^2).

State & Boundaries

The loop runs until len(nums) - 2 because we need at least two more elements to form a triplet.

3

Use Two Pointers to Count Valid Pairs for Each Fixed Element

7left = i + 1
8right = len(nums) - 1
10while left < right:
11 total = nums[i] + nums[left] + nums[right]
13 if total < target:
14 count += right - left
15 left += 1
16 else:
17 right -= 1

Objective

To efficiently count all pairs between left and right pointers that, combined with the fixed element, have sums less than the target.

Key Insight

When the sum of nums[i] + nums[left] + nums[right] is less than target, all elements between left and right pointers form valid pairs with nums[i]. This allows counting multiple triplets in O(1) time per valid sum, avoiding checking each pair individually.

Interview Quick-Check

Core Logic

If the sum is less than target, increment count by right - left because all pairs between left and right pointers satisfy the condition.

Common Pitfalls & Bugs

Failing to move the left pointer forward after counting valid pairs leads to infinite loops or missed triplets.

State & Boundaries

The while loop continues as long as left < right to ensure valid pairs.

4

Return the Total Count of Valid Triplets

19return count

Objective

To output the final count of all triplets with sums less than the target after processing the entire array.

Key Insight

Returning the accumulated count completes the algorithm, providing the total number of valid triplets found by the two-pointer scanning process.

Interview Quick-Check

Core Logic

Returning count after all iterations ensures the final answer reflects all valid triplets.

Line Analysis

This solution has 3 Critical lines interviewers watch for.

Line 14 Critical
count += right - left

Increment count by the number of valid pairs between left and right pointers.

Because the array is sorted, if the sum with nums[right] is less than target, all elements between left and right pointers paired with the fixed element satisfy the condition, allowing O(1) counting of multiple triplets.

Line 3 Critical
nums.sort()

Sort the input array in ascending order.

Sorting is crucial because it enables the two-pointer technique by ensuring that moving pointers predictably increases or decreases the sum, allowing efficient pruning of the search space.

Line 13 Critical
if total < target:

Check if the current sum is less than the target.

This condition identifies when all pairs between left and right pointers form valid triplets, enabling bulk counting.

Line 6 Core
for i in range(len(nums) - 2):

Iterate over the array, fixing one element at a time for the triplet.

Fixing the first element transforms the problem into finding pairs with sums less than a reduced target, reducing complexity from cubic to quadratic.

Line 11 Core
total = nums[i] + nums[left] + nums[right]

Calculate the sum of the fixed element and the elements at left and right pointers.

Computing the current triplet sum is necessary to determine if it satisfies the less-than-target condition, guiding pointer movements.

Line 15 Core
left += 1

Move the left pointer forward to explore new pairs.

Advancing the left pointer after counting valid pairs ensures exploration of new pairs and prevents infinite loops.

Line 16 Core
else:

Handle the case where the sum is not less than the target.

When the sum is too large, moving the right pointer inward reduces the sum, enabling the search for smaller sums that might satisfy the condition.

Line 17 Core
right -= 1

Move the right pointer backward to reduce the sum.

Decreasing the right pointer moves to smaller elements, which may produce sums less than the target, maintaining the correctness of the two-pointer search.

Line 7 Core
left = i + 1

Set the left pointer to the element immediately after the fixed element.

Starting the left pointer just after the fixed element ensures unique triplets with increasing indices and leverages the sorted order for efficient scanning.

Line 8 Core
right = len(nums) - 1

Set the right pointer to the last element in the array.

The right pointer starts at the end to scan pairs from both ends inward, enabling the two-pointer approach to count valid pairs efficiently.

Line 10 Core
while left < right:

Continue scanning while left pointer is less than right pointer.

The condition ensures valid pairs are considered without overlap or repetition, maintaining the correctness of the two-pointer traversal.

Line 19 Core
return count

Return the total count of valid triplets found.

Returning the accumulated count completes the algorithm, providing the final answer to the problem.

Line 4 Standard
count = 0

Initialize the counter for valid triplets to zero.

This accumulator tracks the total number of triplets found that satisfy the sum condition, enabling incremental updates during the two-pointer traversal.

Test Your Understanding

Why can we add right - left to the count when the sum of nums[i] + nums[left] + nums[right] is less than the target?

Because the array is sorted, if the sum with nums[right] is less than target, then all elements between left and right pointers paired with nums[i] will also have sums less than target, allowing us to count all these pairs at once without checking each individually.

Related Problems

Two Pointers pattern

Don't just read it. Drill it.

Reconstruct 3Sum Smaller from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the 3Sum Smaller drill

or drill a free problem