Skip to main content
Back to problems
#1498
Medium Algorithms

Number of subsequences that satisfy the given sum condition

Array Two Pointers Binary Search Sorting
49.3% acceptance
Feb 25, 2026
4650
435
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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn num_subseq(mut nums: Vec<i32>, target: i32) -> i32 {
    const MOD: i64 = 1_000_000_007;
    nums.sort_unstable();
    let n = nums.len();
    let mut pow2 = vec![1i64; n + 1];
    for i in 1..=n { pow2[i] = pow2[i - 1] * 2 % MOD; }
    let mut ans = 0i64;
    let (mut l, mut r) = (0usize, n - 1);
    while l <= r {
      if nums[l] + nums[r] <= target {
        ans = (ans + pow2[r - l]) % MOD;
        l += 1;
      } else {
        if r == 0 { break; }
        r -= 1;
      }
    }
    ans as i32
  }
}