Katkat

Implement longest subarray summing to k

GoogleData Scientist · Onsite

Last updated

This question evaluates proficiency in array algorithms, prefix-sum reasoning, hash-based lookup patterns, and careful handling of edge cases and deterministic tie-breaking.

Given an integer array nums (length ≤ 200,000; values may be negative) and integer k, return the maximum length and the [l, r] indices of a contiguous subarray whose sum is exactly k. If multiple answers tie for length, choose the smallest l; if still tied, choose the smallest r.

  • First outline a correct O(n^2) brute‑force solution.
  • Then design an O(n) algorithm using prefix sums and a hash map. Prove correctness and explain how you ensure earliest indices under ties.
  • State time/space complexity and handle edge cases: k=0, all negatives, all zeros, duplicates, and empty or no‑solution cases.