Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the length of the LONGEST contiguous subarray whose sum equals k; values can be negative, so a sliding window is not valid.
Problem: Find the length of the LONGEST contiguous subarray whose sum equals k; values can be negative, so a sliding window is not valid.
def longest_k(a, k):
first = {0: -1}; run = best = 0
for i, x in enumerate(a):
run += x
if run - k in first:
best = max(best, i - first[run - k])
if run not in first:
first[run] = i
return best
print(longest_k([2, -3, 4, -1, 2, 1], 3), longest_k([4, -4, 1, 2, -2], 1), longest_k([5, 6], 4))What is printed?- A. 3 5 0
- B. 5 3 0
- C. 3 3 0
- D. 5 5 0
Correct answer: D. 5 5 0
Keep the FIRST index of each prefix sum; a later prefix P pairs with the earliest prefix P − k to give the longest window. First array: prefixes 2, −1, 3, 2, 4, 5; at i = 5 (P = 5) the prefix 2 first occurred at i = 0 → length 5 ([−3, 4, −1, 2, 1]). Second: prefix 1 at i = 4 pairs with the empty prefix 0 → whole array, length 5. Overwriting the map with the latest index (the trap) finds shorter windows (3 and 3). O(n).
More Coding Interview Problems questions
- Problem: Count contiguous subarrays of positive integers whose product is strictly less than k, using a shrinking window. python def…
- Problem: An array is a permutation of 0..n−1. Split it into the maximum number of chunks so that sorting each chunk separately and…
- Problem: Seat numbers must become pairwise distinct; one move increments a seat number by 1. Find the minimum moves (sort, then push each…
- Problem: Two engineers list their free slots as sorted, internally disjoint closed intervals. Return every common free interval. python…
- Problem: A sensor array is 'steady' between positions i < j if a[j] − a[i] = j − i. Count steady pairs in O(n) by grouping a[i] − i…
- Problem: Four price lists A, B, C, D (each of length n ≤ 500). Count index tuples (i, j, k, l) with A[i] + B[j] + C[k] + D[l] = 0 by…