Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Count non-empty subsequences whose minimum + maximum ≤ target (sort, then two pointers with powers of 2).

Problem: Count non-empty subsequences whose minimum + maximum ≤ target (sort, then two pointers with powers of 2).
def count(a, t):
    a.sort(); l, r, res = 0, len(a) - 1, 0
    while l <= r:
        if a[l] + a[r] <= t:
            res += 2 ** (r - l); l += 1
        else: r -= 1
    return res
print(count([3, 5, 6, 7, 2, 4], 9))
What is printed?
  1. A. 21
  2. B. 64
  3. C. 33
  4. D. 42

Correct answer: D. 42

After sorting, if a[l] + a[r] ≤ t then a[l] can be the minimum together with any subset of a[l+1..r], giving 2^(r−l) subsequences. Summing over l with the shrinking r gives 42, matching enumeration of all 63 subsequences.

More Coding Interview Problems questions

Exams that ask this topic