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

Subsequences whose smallest and largest fit a target

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

You're given an array of positive integers nums and an integer target, and you have to count the non-empty subsequences of nums where the smallest value plus the largest value is at most target. Two subsequences that pick the same values from different places both count, since it's the positions that tell them apart. The answer can get huge so you return it modulo 10⁹ + 7.

Examples

InputOutputWhy
nums = [3, 5, 6, 7], target = 94You get [3], [3, 5], [3, 6] and [3, 5, 6], and something like [5] on its own doesn't work because 5 + 5 is 10.
nums = [3, 3, 6, 8], target = 106Each 3 on its own and with the 6, so that's four, and then both 3's together, with or without the 6.
nums = [2, 3, 3, 4, 6, 7], target = 1261There are 63 non-empty subsequences in all, and only [6, 7] and [7] go over.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ nums[i] ≤ 10⁶
  • 1 ≤ target ≤ 10⁶

Hints

Hint 1

A subsequence only cares about which positions it picks, and the condition only cares about its min and max. So does the order of the array matter at all here?

Hint 2

It doesn't, so you can sort it. Now fix lo as the smallest element you'll use. If nums[lo] + nums[hi] ≤ target, how many subsequences have nums[lo] as their minimum and nothing past hi?

Hint 3

Every subset of the hi − lo elements after lo can come along, since they're all between nums[lo] and nums[hi]. That's 2^(hi − lo) of them. Add that and move lo up, or move hi down when the sum's too big.

Where people lose marks

  • Working out 2^(hi − lo) with a shift or a float, which I've seen quite a few times. It'll overflow long before n gets anywhere near 10⁵, so you'd build the table mod 10⁹ + 7 as you go.
  • Stopping the loop when lo = hi, because nums[lo] on its own is still a subsequence if 2 × nums[lo] ≤ target and you'd miss it. The loop has to run while lo ≤ hi.
  • Worrying that the sort breaks the subsequences. I wouldn't, since all it does is relabel the positions and the number of sets of positions with a given min and max stays the same.
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.