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
Maximum Size Subarray Sum Equals kInput:1010k = 1Process:01Subarray [0,1] has sum = 1, length = 2Output:2(Maximum length found)🎯 Key Insight: Use prefix sums to efficiently find target subarrays
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
Asked in
Facebook 15 Google 12 Amazon 8
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen