Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums).
Problem: Return the shortest subarray with sum at least k when values can be negative (monotonic deque over prefix sums).
from collections import deque
def shortest(a, k):
P = [0]
for x in a: P.append(P[-1] + x)
dq, best = deque(), float('inf')
for i, p in enumerate(P):
while dq and p - P[dq[0]] >= k:
best = min(best, i - dq.popleft())
while dq and P[dq[-1]] >= p:
dq.pop()
dq.append(i)
return best if best != float('inf') else -1
print(shortest([2, -1, 2], 3), shortest([1, 2], 4), shortest([84, -37, 32, 40, 95], 167))What is printed?- A. 3 -1 3
- B. 2 -1 3
- C. 3 -1 5
- D. 3 0 3
Correct answer: A. 3 -1 3
Keep prefix indices with increasing prefix sums; a front index that already satisfies P[i] − P[j] ≥ k can never give a shorter answer later, so pop it. [2, −1, 2] needs all three. [32, 40, 95] = 167 is length 3. The variable sliding window fails here because of negatives. O(n).
More Coding Interview Problems questions
- Problem: Given n meetings with values, choose non-overlapping ones (end < next start) to maximise total value – weighted interval…
- Problem: Find the minimum cost to climb stairs where cost[i] is paid on stepping on stair i, moving 1 or 2 stairs, starting at stair 0 or…
- Problem: Count the distinct BST shapes that store keys 1..n. python def shapes(n): dp = [1] + [0] n for k in range(1, n + 1): dp[k] =…
- Problem: Count the number of ways to tile a 2 × n board with 2 × 1 dominoes, modulo 10⁹ + 7. cpp const long long MOD = 1e9 + 7; long long…
- Problem: Find the minimum number of perfect squares that sum to n. python def squares(n): dp = [0] + [float('inf')] n for i in range(1, n…
- Problem: Count the number of distinct subsequences of s that equal t. python def distinct(s, t): dp = [1] + [0] len(t) for ch in s: for j…