Given an array arr[] containing integers and an integer k, your task is to find the length of the longest subarray where the sum of its elements is equal to k.
If no such subarray exists, return 0.
Input:
arr = [10, 5, 2, 7, 1, -10], k = 15
Output:
6
Explanation:
The subarray [10, 5, 2, 7, 1, -10] has a sum of 15. Its length is 6, which is the longest.
Input:
arr = [-5, 8, -14, 2, 4, 12], k = -5
Output:
5
Explanation:
The subarray [-5, 8, -14, 2, 4] has a sum of -5 and is the longest such subarray.
Input:
arr = [10, -10, 20, 30], k = 5
Output:
0
Explanation:
There is no subarray with a sum of 5.
- Initialize a
prefixsum variable as 0. - Use a
HashMapto store the first occurrence of each prefix sum. - Traverse the array:
- Add the current element to
prefix. - If
prefix == k, update the answer toi + 1. - If
prefix - kis found in the map, a subarray with sumkexists β update max length. - Use
putIfAbsent()to ensure we store the earliest index for each prefix sum.
- Add the current element to
- Return the maximum length found.
| Complexity | Value | Description |
|---|---|---|
| Time | O(N) | Single pass through the array |
| Space | O(N) | Storing prefix sums in a map |
- 1 β€ arr.length β€ 10β΅
- -10β΄ β€ arr[i] β€ 10β΄
- -10βΉ β€ k β€ 10βΉ
class Solution {
public int longestSubarray(int[] arr, int k) {
Map<Integer, Integer> map = new HashMap<>();
int n = arr.length, prefix = 0, ans = 0;
for(int i = 0; i < n; i++){
if((prefix += arr[i]) == k){
ans = i + 1;
}
if(map.containsKey(prefix - k)){
ans = Math.max(ans, i - map.get(prefix - k));
}
map.putIfAbsent(prefix, i);
}
return ans;
}
}Made with β€οΈ by Milan Haria