Given an integer array nums of size n and an integer k, return the length of the longest non-empty contiguous subarray whose sum equals k. Return 0 if no such subarray exists.
The array may contain positive numbers, negative numbers, and zeros.
Example 1
Input: nums = [10, 5, 2, 7, 1, 9], k = 15
Output: 4
Explanation: Both [10, 5] and [5, 2, 7, 1] sum to 15. The second subarray is longer. It runs from index 1 through index 4, so the answer is 4.
Example 2
Input: nums = [-3, 2, 1], k = 6
Output: 0
Explanation: The largest sum among the contiguous subarrays is 3, from [2, 1]. No subarray reaches 6.
Brute Force
Every subarray is defined by a starting index and an ending index. Try every possible pair of endpoints, calculate the sum of the elements between them, and check whether it equals k.
Use two loops to choose the starting index left and ending index right. For each pair, use a third loop to add all elements from left through right, including both endpoints.
Whenever the sum equals k, calculate the subarray’s length and compare it with the longest valid subarray found so far. For example, [10, 5] and [5, 2, 7, 1] both sum to 15, but their lengths are 2 and 4, so we keep 4.
Approach
Initialise
maxLengthto0.Choose each starting index
leftfrom0ton - 1.For each start, choose every ending index
rightfromleftton - 1.Reset the sum to
0and use a third loop to add the elements fromleftthroughright.If the sum equals
k, calculate the length asright - left + 1and updatemaxLengthif it is larger.Return
maxLengthafter checking all subarrays.
Dry Run
Longest subarray with sum K Brute force
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Find the length of the longest subarray whose sum equals k. int longestSubarray(vector<int>& nums, int k) { // Get the total number of elements in the array. int n = nums.size(); // Stores the maximum length of a subarray whose sum equals k. int maxLength = 0; // Select every possible starting index of a subarray. for (int left = 0; left < n; ++left) { // Reset the sum for the new starting index. int sum = 0; // Extend the subarray from the current starting index. for (int right = left; right < n; ++right) { // Include the current element in the subarray sum. sum += nums[right]; // Check whether the current subarray sum equals k. if (sum == k) { // Calculate the current subarray length. // Length = ending index - starting index + 1. maxLength = max(maxLength, right - left + 1); } } } // Return the maximum length found. return maxLength; }};int main() { // Example input array. vector<int> nums = {-1, 1, 1}; // Target sum. int k = 1; // Create an object of the Solution class. Solution solution; // Find the length of the longest subarray whose sum equals k. int answer = solution.longestSubarray(nums, k); // Print the result. cout << "The length of the longest subarray is: " << answer << "\n"; return 0;}Complexity Analysis
Time Complexity : O(N³). There are O(N²) endpoint pairs, and this version computes each segment’s sum from scratch.
Space Complexity : O(1) auxiliary space as we only use constant variables to track the sum and length.
Optimal (Positive and Negative Numbers)
A prefix sum is the sum of all elements from index 0 through the current index. To find a subarray with sum k, we can subtract an earlier prefix sum from the current prefix sum. If the difference is k, the elements between those two positions form a valid subarray.
For example, in [10, 5, 2, 7, 1, 9], the prefix sum at index 4 is 25. To get a subarray ending there with sum 15, we need to remove a prefix with sum 25 - 15 = 10. That prefix ends at index 0, leaving [5, 2, 7, 1] from index 1 through index 4, with length 4.
Use a hash map to store each prefix sum and the first index where it appears. At each index, look for prefixSum - k. Keeping the earliest occurrence gives the longest possible subarray ending at the current index. This works with both positive and negative numbers because it relies on the difference between prefix sums.
Start with {0: -1} to represent the empty prefix before the array. This also handles subarrays starting at index 0. If the current prefix sum equals k, the required earlier sum is 0, giving a length of i - (-1) = i + 1.
Approach
Initialise
prefixSumandmaxLengthto0. Create a hash map containing{0: -1}.Traverse the array. At each index
i, addnums[i]toprefixSum.Look for
prefixSum - kin the map.If it exists at index
j, the subarray fromj + 1throughisums tok. UpdatemaxLengthusing the lengthi - j.Store the current prefix sum and index only if that sum has never appeared before.
Return
maxLengthafter scanning the entire array.
Dry Run
Longest subarray with sum K optimal
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Find the length of the longest subarray whose sum equals k. int longestSubarray(vector<int>& nums, int k) { // Get the total number of elements in the array. int n = nums.size(); // Stores the first occurrence of each prefix sum. // Key = prefix sum. // Value = index where that prefix sum first appeared. map<int, int> preSumMap; // Stores the cumulative sum from index 0 to the current index. int sum = 0; // Stores the maximum length of a subarray whose sum equals k. int maxLen = 0; // Traverse the array and calculate prefix sums. for (int i = 0; i < n; ++i) { // Add the current element to the prefix sum. sum += nums[i]; // If the prefix sum itself equals k, // the subarray from index 0 to i has sum k. if (sum == k) { // Length of this subarray is i + 1. maxLen = max(maxLen, i + 1); } // Find the prefix sum required to form a subarray of sum k. // If previousPrefixSum = sum - k, // then currentPrefixSum - previousPrefixSum = k. int rem = sum - k; // Check whether the required prefix sum appeared earlier. auto it = preSumMap.find(rem); if (it != preSumMap.end()) { // A previous prefix sum equal to sum - k exists. // Therefore, the subarray between that index and i // has a sum equal to k. // // Length = current index - previous occurrence index. maxLen = max(maxLen, i - it->second); } // Store only the first occurrence of each prefix sum. // The earliest index gives the longest possible subarray. if (preSumMap.find(sum) == preSumMap.end()) { preSumMap[sum] = i; } } // Return the maximum length found. return maxLen; }};int main() { // Example input array. vector<int> nums = {-1, 1, 1}; // Target sum. int k = 1; // Create an object of the Solution class. Solution solution; // Find the length of the longest subarray whose sum equals k. int answer = solution.longestSubarray(nums, k); // Print the result. cout << "The length of the longest subarray is: " << answer << "\n"; return 0;}Complexity Analysis
Time Complexity : O(N) on average with unordered map, and O(N²) in the worst case if many keys collide. An ordered map gives O(N log N) worst-case time.
Space Complexity : O(N) auxiliary space used for the stored prefix sums.
Optimal (Positive Numbers)
Use a sliding window to keep track of a contiguous subarray and its sum. With positive numbers, adding an element increases the sum, while removing an element decreases it. This tells us how to move the window boundaries.
Expand the window by moving the right boundary forward. If the sum becomes greater than k, extending that window would only increase it further. Move the left boundary forward, removing elements until the sum is at most k. Whenever the sum equals k, compare the window’s length with the longest one found so far.
For example, in [10, 5, 2, 7, 1, 9] with k = 15, the first two elements give a sum of 15. Adding 2 increases it to 17, so remove 10 from the left. Continuing to expand eventually gives [5, 2, 7, 1], which sums to 15 and has length 4.
Each boundary moves only forward, so every element enters and leaves the window at most once. This method applies to positive arrays. When negative numbers are allowed, use the prefix-sum solution because adding or removing an element can change the sum in either direction.
Approach
Initialise
left,windowSum, andmaxLengthto0.Move
rightfrom0throughn - 1, addingnums[right]towindowSum.While
left <= rightandwindowSum > k, subtractnums[left]and incrementleft.If
left <= rightandwindowSum == k, calculate the length asright - left + 1and updatemaxLengthif it is larger.Return
maxLengthafter scanning the entire array.
Dry Run
Longest subarray with sum K optimal(Positive)
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Find the length of the longest subarray whose sum equals k. // This sliding window approach assumes all elements are non-negative. int longestSubarray(vector<int>& nums, int k) { // Get the total number of elements in the array. int n = nums.size(); // Stores the maximum length of a subarray whose sum equals k. int maxLen = 0; // Initialize the left and right pointers of the sliding window. int left = 0, right = 0; // Initialize the window sum with the first element. long long sum = nums[0]; // Continue expanding the window until the right pointer // reaches the end of the array. while (right < n) { // If the current window sum exceeds k, // shrink the window from the left. while (left <= right && sum > k) { // Remove the leftmost element from the window sum. sum -= nums[left]; // Move the left pointer one position forward. ++left; } // If the current window sum equals k, // calculate the current window length. if (left <= right && sum == k) { // Update the maximum length found so far. // Window length = right - left + 1. maxLen = max(maxLen, right - left + 1); } // Expand the window by moving the right pointer forward. ++right; // If the right pointer is still within the array, // include the new element in the window sum. if (right < n) { sum += nums[right]; } } // Return the maximum length of a subarray whose sum equals k. return maxLen; }};int main() { // Example input array containing non-negative elements. vector<int> nums = {10, 5, 2, 7, 1, 9}; // Target sum. int k = 15; // Create an object of the Solution class. Solution sol; // Find the length of the longest subarray whose sum equals k. int ans = sol.longestSubarray(nums, k); // Print the result. cout << "The length of longest subarray having sum k is: " << ans << "\n"; return 0;}Complexity Analysis
Time Complexity : O(N). Each element enters the window once and leaves it at most once.
Space Complexity : O(1) auxiliary space as we only use constant variables to store sum and slide the window.
Interview follow-up Questions
For a fixed ending index, the earliest matching prefix leaves the longest subarray. A later occurrence of the same prefix sum gives a shorter candidate.
Be the first to add a comment.