Implement longest subarray summing to k
GoogleData Scientist · OnsiteLast 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.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.