Maximum Size Subarray Sum Equals k - Problem
Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is not one, return 0 instead.
A subarray is a contiguous sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1, 0, 1], k = 1
›
Output:
2
💡 Note:
The subarray [0, 1] starting at index 1 has sum 1 and length 2. Single element subarrays [1] also have sum 1 but length 1, so maximum is 2.
Example 2 — No Valid Subarray
$
Input:
nums = [1, 2, 3], k = 10
›
Output:
0
💡 Note:
No subarray sums to 10, so return 0.
Example 3 — Negative Numbers
$
Input:
nums = [-2, -1, 2, 1], k = 1
›
Output:
2
💡 Note:
The subarray [2, 1] at indices 2-3 has sum 1 and length 2. Also [-1, 2] has sum 1 and length 2.
Constraints
- 1 ≤ nums.length ≤ 2 × 104
- -104 ≤ nums[i] ≤ 104
- -107 ≤ k ≤ 107
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of integers and target sum k
2
Process
Find all subarrays that sum to k
3
Output
Return maximum length found
Key Takeaway
🎯 Key Insight: Prefix sums with hash map allow finding target sum subarrays in O(n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code