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?- A. 21
- B. 64
- C. 33
- 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
- Problem: Rotate an array right by k in O(1) extra space with three reversals. python def rotate(a, k): n = len(a); k %= n def rev(i, j)…
- Problem: Count primes in [L, R] with a segmented sieve (mark multiples of small primes up to √R inside the segment). python import math…
- Edge case: itertools.groupby on unsorted data. python from itertools import groupby data = "aabbbaacc" print([(k, len(list(g))) for k, g…
- Problem: Row n of Pascal's triangle built in place, plus two checks. python def row(n): r = [1] for in range(n): r = [1] + [r[i] + r[i+1]…
- Problem: Find the maximum sum of a sub-rectangle whose sum does not exceed k (fix two columns, then 'max subarray sum ≤ k' with a sorted…
- Problem: What does the following print? It is the multiplicative inverse of 7 modulo 26. python print(pow(7, -1, 26))