← Home

1498. Number of Subsequences That Satisfy the Given Sum Condition

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
149

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1498. Number of Subsequences That Satisfy the Given Sum Condition, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window, greedy.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are power, numSubseq.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 380 ms, faster than 55.92% of C++ online submissions for Number of Subsequences That Satisfy the Given Sum Condition.
02//Memory Usage: 47.7 MB, less than 100.00% of C++ online submissions for Number of Subsequences That Satisfy the Given Sum Condition.
03class Solution {
04public:
05    int MOD = 1e9+7;
06    
07    long long int power(long long int x, long long int y){
08        long long int res = 1;
09
10        // Update x if it is more than or equal to p
11        x = x % MOD;
12
13        while(y > 0){
14            // If y is odd, multiply x with result
15            if(y & 1){
16                //don't need mod multiply for now?
17                // res = multiply(res,x) % MOD;
18                res = (res*x) % MOD;
19            }
20
21            // y must be even now
22            y >>= 1;
23            // x = multiply(x, x) % MOD;
24            x = (x*x) % MOD;
25        }
26
27        return res;
28    };
29    
30    int numSubseq(vector<int>& nums, int target) {
31        int n = nums.size();
32        int count = 0;
33        
34        sort(nums.begin(), nums.end());
35        
36        // for(int& num : nums){
37        //     cout << num << " ";
38        // }
39        // cout << endl;
40        
41        /*
42        target is large enough,
43        so even the subarray: [nums.back()] is acceptable.
44        */
45        if(target >= 2*nums.back()){
46            return power(2, n)-1;
47        }
48        
49        for(int left = 0, right = n-1; left <= right; ++left){
50            // cout << "left: " << left << endl;
51            // discard too large elements
52            while(right >= 0 && nums[left] + nums[right] > target){
53                --right;
54            }
55            
56            if(left <= right && nums[left] + nums[right] <= target){
57                // cout << "[" << left << ", " << right << "]: " << power(2, right-left) << endl;
58                /*
59                for the subarray nums[left...right],
60                keep nums[left] in the subarray,
61                and for nums[left+1...right], 
62                we can choose keep it or not
63                so we can have totally 2^(right-left)
64                combinations, 
65                in which right-left is subarray's size-1
66                */
67                count = (count+ power(2, right-left))%MOD;
68            }
69        }
70        
71        return count;
72    }
73};
74
75//Two Sum
76//https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/discuss/709227/JavaC%2B%2BPython-Two-Sum
77//Runtime: 340 ms, faster than 86.87% of C++ online submissions for Number of Subsequences That Satisfy the Given Sum Condition.
78//Memory Usage: 50.1 MB, less than 100.00% of C++ online submissions for Number of Subsequences That Satisfy the Given Sum Condition.
79//time: O(NlogN), space: O(N) or O(1)
80class Solution {
81public:
82    int numSubseq(vector<int>& nums, int target) {
83        int n = nums.size();
84        int MOD = 1e9+7;
85        int ans = 0;
86        vector<int> power(n, 1);
87        
88        //precalculate the powers
89        for(int i = 1; i < n; ++i){
90            power[i] = (power[i-1] << 1) % MOD;
91        }
92        
93        sort(nums.begin(), nums.end());
94        
95        for(int l = 0, r = n-1; l <= r; ){
96            if(nums[l] + nums[r] > target){
97                //either decrease r or increase l
98                --r;
99            }else{
100                ans = (ans + power[r-l]) % MOD;
101                //either decrease r or increase l
102                ++l;
103            }
104        }
105        
106        return ans;
107    }
108};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.