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 pairs whose sum is below a target

Easy · Target 12 minutes · Two pointers· Type asked at

You're given an integer array nums and an integer target, and you have to return how many pairs of indices i < j have nums[i] + nums[j] < target.

Examples

InputOutputWhy
nums = [-1, 1, 2, 3, 1], target = 23You get (−1, 1) twice because there are two 1's, and then (−1, 2), and everything else comes to 2 or more.
nums = [1, 2, 3], target = 00
nums = [3, 1, 2], target = 411 + 2 is the only pair that's under 4, since the other two come to 4 and 5.

Constraints

  • 0 ≤ n ≤ 10⁵
  • −10⁴ ≤ nums[i], target ≤ 10⁴

Hints

Hint 1

You're counting pairs of positions so it doesn't really matter what order the array's in. What does that let you do to it before you start?

Hint 2

I'd sort it and put lo at the start and hi at the end. If nums[lo] + nums[hi] < target then what can you say about nums[lo] with each of the values in between?

Hint 3

None of them is bigger than nums[hi], so all hi − lo of those pairs work and you can add them in one go and move lo up. When the sum's too big it's nums[hi] that can't go with anything that's left, and hi comes down.

Where people lose marks

  • Adding 1 on a hit when you've really found hi − lo pairs, which will probably get the tiny examples right and the bigger ones wrong.
  • Using ≤ where the problem says <, when a sum that's equal to the target doesn't count and on a tie it's hi that you'd move.
  • Worrying that sorting changes the answer. I wouldn't, because it only moves the values about and every pair of positions you had before is still there with the same sum.
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.