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 k INPUT nums array: 1 idx: 0 0 idx: 1 1 idx: 2 Target sum k: k = 1 Input Values: nums = [1, 0, 1] k = 1 length = 3 ALGORITHM STEPS 1 Initialize Hash Map map = {0: -1}, sum = 0 2 Compute Prefix Sum Track running sum at i 3 Check (sum - k) If exists, update maxLen 4 Store in Hash Map Store sum:index if new Hash Map State: i=0: sum=1, map={0:-1, 1:0} i=1: sum=1, map={0:-1, 1:0} i=2: sum=2, map={0:-1, 1:0, 2:2} sum-k=0 found at i=1 len = 1-(-1) = 2 FINAL RESULT Maximum subarray found: 1 idx: 0 0 idx: 1 1 idx: 2 subarray [1, 0] Sum: 1 + 0 = 1 = k Output: 2 [OK] Max length = 2 Indices: 0 to 1 Key Insight: Use prefix sum with hash map: if prefixSum[j] - prefixSum[i] = k, then subarray (i+1, j) sums to k. Store first occurrence of each prefix sum to maximize length. Time: O(n), Space: O(n). Initialize map with {0: -1} to handle subarrays starting from index 0. TutorialsPoint - Maximum Size Subarray Sum Equals k | Hash Map Approach
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