Mid/Senior

3Sum Smaller

Given an integer array nums and an integer target, return the number of index triplets (i, j, k) such that:

  • 0 <= i < j < k < nums.length
  • nums[i] + nums[j] + nums[k] < target

Your solution should be efficient enough for the given input size.

Example 1
Inputnums = [-2,0,1,3], target = 2
Output2
The valid triplets are [-2, 0, 1] and [-2, 0, 3], both of which have sums less than 2.
Example 2
Inputnums = [0], target = 0
Output0
There are fewer than three numbers, so no triplet can be formed.

Constraints

  • 0 <= nums.length <= 3500
  • -100 <= nums[i] <= 100
  • -100 <= target <= 100

Asked at 7 companies

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate