Number of Subsequences That Satisfy the Given Sum Condition

MediumTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums and an integer target, count the **non-empty** subsequences whose minimum element plus maximum element is at most target. Subsequences are chosen by index, so two subsequences with the same values taken from different positions count separately. A single-element subsequence uses that element as both its minimum and maximum. The count can be very large; return it modulo 10^9 + 7. Aim for O(n log n) time.

Examples

Input: nums = [3,5,6,7], target = 9
Output: 4
[3], [3,5], [3,6], and [3,5,6] qualify.
Input: nums = [3,3,6,8], target = 10
Output: 6
[3], [3], [3,3], [3,6], [3,6], and [3,3,6] qualify (the two 3s are different indices).
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
All 63 non-empty subsequences except [6,7] and [7] qualify.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^6
  • 1 <= target <= 10^6

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems