Leetcode #1498: Number of Subsequences That Satisfy the Given Sum Condition
In this guide, we solve Leetcode #1498 Number of Subsequences That Satisfy the Given Sum Condition in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Two Pointers, Binary Search, Sorting
Intuition
The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.
Moving one pointer at a time keeps the invariant intact and avoids nested loops.
Approach
Place pointers at the left and right ends and move them based on the comparison or target condition.
This yields a clean linear pass after any required sorting.
Steps:
- Set left and right pointers.
- Move a pointer based on the condition.
- Update the best answer while scanning.
Example
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)
Python Solution
class Solution:
def numSubseq(self, nums: List[int], target: int) -> int:
mod = 10**9 + 7
nums.sort()
n = len(nums)
f = [1] + [0] * n
for i in range(1, n + 1):
f[i] = f[i - 1] * 2 % mod
ans = 0
for i, x in enumerate(nums):
if x * 2 > target:
break
j = bisect_right(nums, target - x, i + 1) - 1
ans = (ans + f[j - i]) % mod
return ans
Complexity
The time complexity is , and the space complexity is , where is the length of the array . The space complexity is , where is the length of the array .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.