You're given an integer array nums and a target integer k. Your mission is to find the maximum length of a contiguous subarray whose elements sum exactly to k.
A subarray is a contiguous sequence of elements within an array. For example, in array [1, 2, 3, 4], some subarrays include [1, 2], [2, 3, 4], and [1, 2, 3, 4].
Goal: Return the length of the longest subarray that sums to k. If no such subarray exists, return 0.
Example: In array [1, -1, 5, -2, 3] with k = 3, the subarray [5, -2] has sum 3 with length 2, but [1, -1, 5, -2, 3] also sums to 6... wait, that's not 3! The longest subarray summing to 3 is actually [3] with length 1, or we could have [1, -1, 5, -2] which sums to 3 with length 4!
Input & Output
Visualization
Time & Space Complexity
Single pass through array, with O(1) hash table operations
Hash table can store up to n different prefix sums in worst case
Constraints
- 1 โค nums.length โค 2 ร 104
- -104 โค nums[i] โค 104
- -107 โค k โค 107
- The array can contain negative numbers, zero, and positive numbers