Longest Subarray Sum K HashMap | Java Fresher Interview
Fast recall
Quick revision
Core answer
i with running sum S, if S - k was seen at index j, then the subarray (j+1..i) sums to k; the longest is i - j. One pass, O(n) time and O(n) space - far better than the O(n^2) double loop.Whether you connect 'subarray sum' to prefix sums and a HashMap of sum->earliest index
Trying all subarrays (O(n^2)) or storing the latest index instead of the earliest (breaks 'longest')
Seed the map with sum 0 at index -1 and store only the FIRST occurrence of each prefix sum
Interview-ready guide
Interview answer
The key realization is that a subarray sums to k exactly when two prefix sums differ by k.
The prefix sum up to index i, minus the prefix sum up to some earlier index j, equals the sum of the elements between them. So if I want a subarray that sums to k ending at i, I need an earlier prefix sum equal to the current running sum minus k.
To find the longest such subarray, I want the earliest index where each prefix sum first appeared, because the earlier the start, the longer the subarray. So I keep a HashMap from prefix sum to the earliest index where I saw it. I walk the array once, maintaining a running sum.
At each index, I check whether the map contains the running sum minus k. If it does, that gives me a valid subarray, and I update my best length to the current index minus that stored earlier index. Two details are essential.
First, I seed the map with sum zero mapped to index minus one, so that a subarray which starts at index zero is correctly counted. Second, I only store the first occurrence of each prefix sum, using putIfAbsent, because for the longest subarray I want the earliest start. If I overwrote with the latest index, I'd shorten my answer.
This runs in O of n time and O of n space, and importantly it works even with negative numbers, where a sliding window wouldn't, because the running sum isn't monotonic. The brute force of checking every subarray would be O of n squared, so the prefix-sum map is the real win.
For example, for [1, 2, 3] and k = 3, start with prefix 0 at index -1. The prefix becomes 3 at index 1, so 3 - k = 0 points to index -1 and gives the subarray [1, 2] of length 2.
Longest Subarray Sum K HashMap | Java Fresher Interview
Direct Answer
Use a prefix sum + HashMap. Track a running sum and store, for each prefix sum, the earliest index it occurred. At index i with running sum S, if S - k was seen at index j, then the subarray (j+1..i) sums to k; the longest is i - j. One pass, O(n) time and O(n) space - far better than the O(n^2) double loop.
Deep Dive & Architecture
Let prefix be the sum from index 0 through the current index. A subarray ending here has sum k when an earlier prefix equals prefix - k, because subtracting the earlier total leaves exactly the range in between.
Store the earliest index for every prefix sum. Earlier is better because it produces the longest range. Seed the map with 0 -> -1, which lets a valid subarray begin at index 0.
Worked example: [1, -1, 5, -2, 3], k = 3
The prefix sums are 1, 0, 5, 3, and 6. When zero appears again at index 1, keep its earlier seed index -1. At index 3, prefix - k is 3 - 3 = 0; the earliest zero gives the range from index 0 through 3, [1, -1, 5, -2], with length 4. At index 4, prefix 6 finds prefix 3 at index 3 and gives only length 1, so the best remains 4. Never overwrite an existing prefix index.
Unlike a standard sliding window, this method works with negative values because prefix-sum subtraction stays valid even when sums rise and fall. The scan is O(n) average time and uses O(n) extra space. Use long for prefixes when integer totals may overflow.
Code Example
int longestSubarray(int[] nums, int k) {
Map<Integer,Integer> first = new HashMap<>();
first.put(0, -1); // empty prefix before index 0
int sum = 0, best = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (first.containsKey(sum - k)) // earlier prefix gives sum k
best = Math.max(best, i - first.get(sum - k));
first.putIfAbsent(sum, i); // keep EARLIEST index only
}
return best;
}
// nums = {1, -1, 5, -2, 3}, k = 3
// prefix: 1,0,5,3,6 ; sum-k seen -> best length 4 (subarray 1,-1,5,-2)
Common Mistakes & Pitfalls
- O(n^2) all-subarrays: trying every start/end; the prefix-sum map makes it O(n).
- Storing latest index: use
putIfAbsentto keep the earliest - storing the latest shortens the answer. - Forgetting the {0:-1} seed: without it, subarrays starting at index 0 are missed.
- Confusing with count: 'count of subarrays' stores frequencies, not earliest index.
Check your understanding
Answer these without looking back at the article.
- How do you use a HashMap to solve the frequency counting pattern?
- What happens when two keys produce the same hash code? How does a HashMap handle it?
- How would you use a HashMap to find the first non-repeating character in a string?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.