Introduction
The Longest Subarray with Sum K problem involves finding the longest contiguous subarray whose sum is equal to a given value k.
Given an array arr[] of size n and an integer k, the task is to find the length of the longest subarray having sum equal to k.
This is one of the most important array problems and helps in understanding Prefix Sum, Hashing, and Sliding Window optimization techniques.
Example
Input: arr[] = [1, 2, 3, 1, 1, 1, 1]k = 6 Output: 4 Explanation: Subarray [1, 2, 3] → Sum = 6 Length = 3 Subarray [3, 1, 1, 1] → Sum = 6 Length = 4 Longest Length = 4 Input: arr[] = [2, 1, 1, 1, 3, 2] k = 5 Output: 4
Explanation:
Subarray [1, 1, 1, 2] → Sum = 5
Length = 4
Constraints
1 <= n <= 10^5-10^9 <= arr[i] <= 10^9
-10^9 <= k <= 10^9
Approach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Generate all possible subarrays
- Calculate sum of every subarray
- Check whether the sum equals k
- Track the maximum length
This approach is easy to understand but recalculating sums repeatedly increases time complexity.
Steps
- Traverse all starting indices.
- For every starting index:
- generate all subarrays
- Calculate current subarray sum.
- If sum equals k:
- update maximum length
- Return the longest length.
Dry Run
Input Array: [1, 2, 3, 1, 1, 1, 1]k = 6
Subarray [1]:
Sum = 1
Subarray [1, 2]:
Sum = 3
Subarray [1, 2, 3]:
Sum = 6
Length = 3
Update Maximum Length = 3
Subarray [3, 1, 1, 1]:
Sum = 6
Length = 4
Update Maximum Length = 4
Final Result: 4
Brute Force Code
Complexity Analysis
Time Complexity: O(n²)Explanation:
All possible subarrays are generated.
Space Complexity: O(1)
Explanation:
No extra data structures are used.
Approach 2 : Optimized Solution (Prefix Sum + HashMap)
Explanation
Instead of recalculating sums for every subarray, we can use:
- Prefix Sum
- HashMap
The idea is:
- Store prefix sums and their indices
- If (currentSum-k) exists in the map:
- a valid subarray exists
- Update maximum length accordingly
This avoids repeated traversals and improves efficiency.
Steps
- Initialize:
- prefix sum = 0
- hashmap
- maximum length = 0
- Traverse the array.
- Add current element to prefix sum.
- If prefix sum equals k:
- update maximum length
- If (prefixSum-k) exists:
- calculate valid subarray length
- Store prefix sum if not already present.
Dry Run
Input Array: [1, 2, 3, 1, 1, 1, 1]k = 6
Traverse 1:
Prefix Sum = 1
Store:
1 → index 0
Traverse 2:
Prefix Sum = 3
Store:
3 → index 1
Traverse 3:
Prefix Sum = 6
Prefix Sum == k
Length = 3
Update Maximum Length = 3
Traverse 1:
Prefix Sum = 7
7 - 6 = 1 exists in map
Length = 4 - 0 = 4
Update Maximum Length = 4
Final Result: 4
Optimized Code
Complexity Analysis
Time Complexity: O(n)Explanation:
Each element is processed once using HashMap lookups.
Space Complexity: O(n)
Explanation:
HashMap stores prefix sums and indices.