Problem Description
Given an integer array and an integer k, determine the maximum length of a contiguous subarray that sums to k. If no such subarray exists, return 0.
Key Insights
- Utilize the prefix sum concept to convert subarray sum queries into differences between two prefix sums.
- Use a hash table (dictionary/map) to store the earliest occurrence of each prefix sum.
- For each index, check if (current_prefix_sum - k) exists in the hash table to identify a valid subarray.
- Handling negative numbers correctly is crucial since prefix sums can decrease.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
Traverse the array while maintaining a cumulative (prefix) sum. For every index, calculate the current prefix sum and check if (current_prefix_sum - k) has been seen before in a hash map. If found, update the maximum subarray length with the difference between the current index and the stored index for (current_prefix_sum - k).
Store the prefix sums in a hash table only if they are seen for the first time to preserve the earliest index, which helps maximize the subarray length. This approach efficiently finds the longest subarray summing to k in a single pass.