Number of Subsequences That Satisfy the Given Sum Condition Problem
Description
LeetCode Problem 1498.
You are given an array of integers nums and an integer target.
Return the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [3,5,6,7], target = 9
Output: 4
Explanation: There are 4 subsequences that satisfy the condition.
[3] -> Min value + max value <= target (3 + 3 <= 9)
[3,5] -> (3 + 5 <= 9)
[3,5,6] -> (3 + 6 <= 9)
[3,6] -> (3 + 6 <= 9)
Example 2:
Input: nums = [3,3,6,8], target = 10
Output: 6
Explanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]
Example 3:
Input: nums = [2,3,3,4,6,7], target = 12
Output: 61
Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^61 <= target <= 10^6
Solution
Approach: Sort and Two Pointers
A subsequence is judged only by its smallest and largest element, and those do not depend on the order of the array. So we can sort nums and count subsets instead.
In the sorted array, fix the minimum at index i and let j be the largest index with nums[i] + nums[j] <= target. Every subset that contains nums[i] plus any choice of elements from nums[i+1..j] is valid, because its maximum is at most nums[j]. That is 2^(j - i) subsets.
Two pointers find j for every i without searching from scratch. Start with i = 0 and j = n - 1:
- If
nums[i] + nums[j] <= target, add2^(j - i)and moveiright. - Otherwise
nums[j]is too big even for the smallest remaining minimum, so it is too big for every laterias well: movejleft.
Stop when i > j. The case i == j is the single-element subsequence [nums[i]], valid when 2 * nums[i] <= target, and the formula gives 2^0 = 1 for it.
The powers of two get huge, so precompute 2^d mod (10^9 + 7) for every d < n and keep the sum reduced modulo 10^9 + 7.
Complexity: O(n log n) time for sorting (the two-pointer pass is O(n)), and O(n) space for the powers of two.
class Solution:
def numSubseq(self, nums: List[int], target: int) -> int:
MOD = 10**9 + 7
nums.sort()
n = len(nums)
pow2 = [1] * n # pow2[d] = 2^d mod MOD
for d in range(1, n):
pow2[d] = pow2[d - 1] * 2 % MOD
ans = 0
i, j = 0, n - 1
while i <= j:
if nums[i] + nums[j] <= target:
# nums[i] is the minimum; any subset of nums[i+1..j] can join it
ans = (ans + pow2[j - i]) % MOD
i += 1
else:
j -= 1 # nums[j] is too big for this and every larger minimum
return ans