Number of Subsequences That Satisfy the Given Sum Condition

Count the subsequences of an array whose smallest plus largest number is at most a target.

You are given an array of integers nums, with at least one number, and a number target. A subsequence is a choice of some of the numbers, at least one, kept in their original order. Count the subsequences whose smallest number plus largest number is at most target. The count can be very large, so return it modulo 109 + 7: the remainder after dividing it by 1,000,000,007.

Example 1
Input: nums = [3, 5, 6, 7], target = 9
Output: 4
Explanation: [3], [3, 5], [3, 6] and [3, 5, 6].
Example 2
Input: nums = [3, 3, 6, 8], target = 10
Output: 6
Explanation: [3], [3], [3, 3], [3, 6], [3, 6] and [3, 3, 6]. Equal numbers at different positions count as different subsequences.
Example 3
Input: nums = [2, 3, 3, 4, 6, 7], target = 12
Output: 61
Explanation: of the 63 subsequences, only [6, 7] and [7] fail.
Solution

The Idea

Look at Example 1. Each of the four numbers in [3, 5, 6, 7] is either kept or left out. That gives 2 × 2 × 2 × 2 = 16 ways to choose, and 15 of them keep at least one number. For each choice, only two numbers matter: the smallest and the largest. [3, 5, 6] has 3 and 6, and 3 + 6 = 9 is not more than 9, so it counts. [5, 6] gives 5 + 6 = 11, so it does not.

Checking all 15 is easy here, but 30 numbers already give more than a billion choices. Can we count the good subsequences without listing them?

Start with what the condition ignores: the order. The smallest and largest of the chosen numbers are the same whichever order they come in. So we may sort the array first. Sorting moves the numbers, but every choice of positions before sorting matches one choice after it, with the same numbers. The array in Example 1 happens to be sorted already.

In a sorted array, the smallest number of a choice is simply the leftmost one picked. So take the possible smallest numbers one at a time. Which subsequences have 3 as their smallest number? 3 must be in. Then the largest number can be at most 9 - 3 = 6, so 7 is out, because 3 + 7 = 10. The 5 and the 6 are free to be in or out. Look at the picture below.

The sorted array 3, 5, 6, 7 with target 9. left is on 3, which is always in. right is on 6, because 3 + 7 = 10 is too big. 5 and 6 can each be in or out, which gives 4 subsequences: [3], [3, 5], [3, 6] and [3, 5, 6].

Two markers mark the range. left is on 3, the number that is always in. right is on 6, the largest number that 3 can go with. The two numbers after left, up to and including right, are each in or out, which gives 2 × 2 = 4 choices. They are the four subsequences in the bottom row, and they are the whole answer: with 5 as the smallest number, 5 + 5 = 10 is already too big.

So we never need to list the subsequences. For each smallest number, every number after left, up to and including right, doubles the count. There are right - left such numbers, so the count is 2right - left.

Solution Approach

Turning that idea into code means settling three things: how to find right for each left, how to count each subsequence only once, and how to keep the large powers of two in check.

Finding the largest partner

How do we find right for each left? We could search from the end of the array every time. But if the array has n numbers, that takes up to n steps for each of them, about n² steps in all.

There is a faster way. As left moves right, its number grows or stays the same, so the largest number it can go with can only get smaller. That means right never has to move back to the right. Start right at the last position and compare nums[left] + nums[right] with target:

  • If the sum is at most target, add 2right - left to the count and move left one place right.
  • Otherwise nums[right] is too big even for nums[left]. The numbers after left are only larger, so it is too big for them too. Move right one place left.

Each step moves one marker, so the whole walk takes at most n steps. Walking two markers through a sorted array like this is called the two-pointer technique.

The walk goes on while left <= right. When the two markers meet, the subsequence is the single number alone, and 20 = 1 counts it, provided twice that number is at most target.

Counting each subsequence once

What happens with equal numbers, as in Example 2? Sorted, it reads 3, 3, 6, 8. With left on the first 3, right ends on 6 and the count is 22 = 4: the first 3 alone, or with the second 3, the 6, or both. With left on the second 3, the first 3 is behind it and cannot be picked, so the count is 21 = 2. That makes 6, the expected answer.

So every subsequence is counted exactly once, under the leftmost position it uses, even when the array holds equal numbers.

Powers of two and the remainder

How big can 2right - left get? With 100 numbers it can reach 299, far past the largest long, which is about 9.2 × 1018. That is why the problem asks for the remainder, and remainders can be kept small all the way. The remainder of a number times 2 can be worked out from the remainder of the number.

So the powers go into an array pow2, built once: each entry is the one before it times 2, then the remainder. Every entry is below 1,000,000,007, so doubling one gives less than 2,000,000,014. That still fits in an int, whose largest value is 2,147,483,647, and so does the running count plus one entry.

Java Solution

The method numSubseq works in these steps:

  1. First, sort the input array with Arrays.sort(nums), so the smallest number of any choice is its leftmost one.
  2. Keep 1,000,000,007 in mod. Build the array pow2 with one entry per number: pow2[0] is 1, and each later entry is the one before it times 2, modulo mod.
  3. Set count to 0, put left on the first position and right on the last, and start a while loop that runs as long as left <= right.
  4. Inside the loop, if nums[left] + nums[right] is at most target, add pow2[right - left] to count, modulo mod, and move left one place right. Otherwise, move right one place left.
  5. When the loop ends, return count.

The main method runs the three examples, Example 1 in reverse order, a single number that fits and one that does not, and 100 ones with target 2, where every subsequence counts.

Java
import java.util.Arrays;

public class NumberOfSubsequencesThatSatisfyTargetSumCondition {

    public static int numSubseq(int[] nums, int target) {
        final int mod = 1000000007;
        int n = nums.length;
        Arrays.sort(nums);
        int[] pow2 = new int[n];
        pow2[0] = 1;
        for (int i = 1; i < n; i++) {
            pow2[i] = pow2[i - 1] * 2 % mod;
        }
        int count = 0;
        int left = 0;
        int right = n - 1;
        while (left <= right) {
            if (nums[left] + nums[right] <= target) {
                // nums[left] is the smallest; any values from left + 1 to right may join it
                count = (count + pow2[right - left]) % mod;
                left++;
            } else {
                right--;    // nums[right] is too big even with nums[left]
            }
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(numSubseq(new int[] {3, 5, 6, 7}, 9));
        System.out.println(numSubseq(new int[] {3, 3, 6, 8}, 10));
        System.out.println(numSubseq(new int[] {2, 3, 3, 4, 6, 7}, 12));
        System.out.println(numSubseq(new int[] {7, 6, 5, 3}, 9));
        System.out.println(numSubseq(new int[] {5}, 10));
        System.out.println(numSubseq(new int[] {6}, 10));
        int[] ones = new int[100];
        Arrays.fill(ones, 1);
        System.out.println(numSubseq(ones, 2));
    }
}

Running it prints:

Output
4
6
61
4
1
0
976371284

The first three lines, 4, 6 and 61, answer the three examples. The fourth line gives 4 again for [7, 6, 5, 3]: once sorted, it is the same array as Example 1. The next two lines are single numbers with target 10. 5 + 5 = 10 fits, so [5] gives 1, while 6 + 6 = 12 does not, so [6] gives 0.

The last line is the 100 ones. Any choice of them has 1 + 1 = 2, so all 2100 - 1 subsequences count. That number has 31 digits, and 976371284 is its remainder after dividing by 1,000,000,007, which a check with BigInteger confirms.

Why build pow2 at all, instead of writing (long) Math.pow(2, k) % mod? Math.pow returns a double, and casting a double that is too big for long gives Long.MAX_VALUE. For 299 that expression gives 291172003, while the true remainder is 988185646.

The original implementation, NumberOfSubsequencesThatSatisfyTargetSumCondition.java, is on GitHub.

Complexity

The work is the sort, one loop to fill pow2, and one walk of the two markers.

  • Time: O(n log n), where n is the length of the array. Arrays.sort takes O(n log n). Filling pow2 takes n steps, and every pass of the while loop moves left or right, so it ends after at most n passes.
  • Space: O(n). The pow2 array holds n powers of two. The input is sorted in place, and the markers and the count are single numbers.

Moving two markers through a sorted array by comparing a sum with a target is also the core of Two Sum II.