Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

Count the triplets with a sum below a target

Medium · Target 15 minutes · Two pointers· Type asked at

You're given an integer array nums and an integer target, and you have to count the triples of indices i < j < k with nums[i] + nums[j] + nums[k] < target. Equal values at different positions count as different triplets.

Examples

InputOutputWhy
nums = [-2, 0, 1, 3], target = 22−2 + 0 + 1 = −1 and −2 + 0 + 3 = 1 are both under 2, and anything else comes to 2 or more.
nums = [], target = 00There's nothing to pick from, so the count's zero.
nums = [1, 1, 1], target = 41There's only one way to pick three positions out of three.

Constraints

  • 0 ≤ n ≤ 3500
  • −100 ≤ nums[i], target ≤ 100

Hints

Hint 1

You're counting positions, not values, so the order of the array doesn't matter. What does sorting buy you once you've fixed the first value?

Hint 2

With nums[i] fixed it's the count-pairs-below-a-target question on everything to the right of i, with the target lowered by nums[i].

Hint 3

If nums[i] + nums[lo] + nums[hi] < target, every k from lo + 1 up to hi works with lo too, so you'd add hi − lo in one go and move lo up.

Where people lose marks

  • Skipping repeated values the way you do in 3-sum. Here every set of positions counts, so you'd be throwing away triplets you're meant to keep.
  • Adding 1 on a hit when you've really found hi − lo triplets with this i and lo, which gets the small examples right and the bigger ones wrong.
  • Using ≤ when the problem says <, so that a triplet that adds up to the target exactly gets counted when it shouldn't.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.