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?
  1. A. 3 5 0
  2. B. 5 3 0
  3. C. 3 3 0
  4. 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

Exams that ask this topic