Number of Subsequences That Satisfy the Given Sum Condition — LeetCode 1498 Python Solution

MediumArrayTwo PointersBinary SearchSorting
Problem
#1498
Reading time
3 min

The problem

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.

Example

Input
nums = [3,5,6,7], target = 9
Output
4
Explanation
There are 4 subsequences that satisfy the condition.

Python solution

Python
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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n), where n is the length of the array \textit{nums} auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition?
LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition is rated Medium on LeetCode.
What is the time complexity of LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition?
The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
What topics does LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition cover?
LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview