#1498

Number of Subsequences That Satisfy the Given Sum Condition

Medium
ArrayTwo PointersBinary SearchSortingTwo PointersSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By sorting the array and using a two-pointer technique, we can efficiently find valid subsequences without generating all of them. This method leverages the properties of sorted arrays to quickly find pairs that meet the criteria.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array nums.
  2. 2Step 2: Initialize two pointers: left at the start and right at the end of the array.
  3. 3Step 3: While left <= right, check if nums[left] + nums[right] <= target. If true, count all subsequences formed by nums[left] and nums[right] and move left pointer up. If false, move right pointer down.
solution.py17 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def numSubseq(nums, target):
5    nums.sort()
6    left, right = 0, len(nums) - 1
7    count = 0
8    power = [1] * (len(nums) + 1)
9    for i in range(1, len(nums) + 1):
10        power[i] = (power[i - 1] * 2) % MOD
11    while left <= right:
12        if nums[left] + nums[right] <= target:
13            count = (count + power[right - left]) % MOD
14            left += 1
15        else:
16            right -= 1
17    return count

Complexity note: Sorting the array takes O(n log n), and the two-pointer traversal takes O(n), making this approach much more efficient than brute force.

  • 1Sorting the array allows efficient pairing of minimum and maximum values.
  • 2Using powers of 2 helps count the number of valid subsequences without generating them.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.