Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Count subarrays whose sum lies in [lo, hi] using prefix sums and a sorted list (bisect).
Problem: Count subarrays whose sum lies in [lo, hi] using prefix sums and a sorted list (bisect).
from bisect import bisect_left, bisect_right, insort
def count(a, lo, hi):
pre, s, res = [0], 0, 0
for x in a:
s += x
res += bisect_right(pre, s - lo) - bisect_left(pre, s - hi)
insort(pre, s)
return res
print(count([-2, 5, -1, 3, -4, 2], -2, 2))What is printed?- A. 11
- B. 6
- C. 13
- D. 8
Correct answer: A. 11
A subarray ending here has sum s − p for an earlier prefix p, so we need s − hi ≤ p ≤ s − lo, counted by two binary searches. The total 11 matches checking all 21 subarrays (an O(n log n) merge-sort or BIT version scales to 10⁵).
More Coding Interview Problems questions
- Problem: Starting at index s, you may jump from i to i + a[i] or i − a[i]. Can you reach any index holding 0? python def canreach(a, s)…
- Problem: Count non-empty subsequences whose minimum + maximum ≤ target (sort, then two pointers with powers of 2). python def count(a, t)…
- 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]…