Longest Subarray With Sum K
Last Updated :
11 Jan, 2025
Given an array arr[] of size n containing integers, the task is to find the length of the longest subarray having sum equal to the given value k.
Note: If there is no subarray with sum equal to k, return 0.
Examples:
Input: arr[] = [10, 5, 2, 7, 1, -10], k = 15
Output: 6
Explanation: Subarrays with sum = 15 are [5, 2, 7, 1], [10, 5] and [10, 5, 2, 7, 1, -10]. The length of the longest subarray with a sum of 15 is 6.
Input: arr[] = [-5, 8, -14, 2, 4, 12], k = -5
Output: 5
Explanation: Only subarray with sum = 15 is [-5, 8, -14, 2, 4] of length 5.
Input: arr[] = [10, -10, 20, 30], k = 5
Output: 0
Explanation: No subarray with sum = 5 is present in arr[].
[Naive Approach] Using Nested Loop - O(n^2) Time and O(1) Space
The idea is to check the sum of all the subarrays and return the length of the longest subarray having the sum k.
C++
// C++ program to find the length of the longest
// subarray having sum k using nested loop
#include <iostream>
#include <vector>
using namespace std;
// Function to find longest sub-array having sum k
int longestSubarray(vector<int>& arr, int k) {
int res = 0;
for (int i = 0; i < arr.size(); i++) {
// Sum of subarray from i to j
int sum = 0;
for (int j = i; j < arr.size(); j++) {
sum += arr[j];
// If subarray sum is equal to k
if (sum == k) {
// find subarray length and update result
int subLen = j - i + 1;
res = max(res, subLen);
}
}
}
return res;
}
int main() {
vector<int> arr = {10, 5, 2, 7, 1, -10};
int k = 15;
cout << longestSubarray(arr, k) << endl;
return 0;
}
C
// C program to find the length of the longest
// subarray having sum k using nested loop
#include <stdio.h>
// Function to find longest sub-array having sum k
int longestSubarray(int arr[], int n, int k) {
int res = 0;
for (int i = 0; i < n; i++) {
// Sum of subarray from i to j
int sum = 0;
for (int j = i; j < n; j++) {
sum += arr[j];
// If subarray sum is equal to k
if (sum == k) {
// Find subarray length and update result
int subLen = j - i + 1;
res = (res > subLen) ? res : subLen;
}
}
}
return res;
}
int main() {
int arr[] = {10, 5, 2, 7, 1, -10};
int k = 15;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", longestSubarray(arr, n, k));
return 0;
}
Java
// Java program to find the length of the longest
// subarray having sum k using nested loop
class GfG {
// Function to find longest sub-array having sum k
static int longestSubarray(int[] arr, int k) {
int res = 0;
for (int i = 0; i < arr.length; i++) {
// Sum of subarray from i to j
int sum = 0;
for (int j = i; j < arr.length; j++) {
sum += arr[j];
// If subarray sum is equal to k
if (sum == k) {
// find subarray length and update result
int subLen = j - i + 1;
res = Math.max(res, subLen);
}
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {10, 5, 2, 7, 1, -10};
int k = 15;
System.out.println(longestSubarray(arr, k));
}
}
Python
# Python program to find the length of the longest
# subarray having sum k using nested loop
# Function to find longest sub-array having sum k
def longestSubarray(arr, k):
res = 0
for i in range(len(arr)):
# Sum of subarray from i to j
sum = 0
for j in range(i, len(arr)):
sum += arr[j]
# If subarray sum is equal to k
if sum == k:
# find subarray length and update result
subLen = j - i + 1
res = max(res, subLen)
return res
if __name__ == "__main__":
arr = [10, 5, 2, 7, 1, -10]
k = 15
print(longestSubarray(arr, k))
C#
// C# program to find the length of the longest
// subarray having sum k using nested loop
using System;
class GfG {
// Function to find longest sub-array having sum k
static int longestSubarray(int[] arr, int k) {
int res = 0;
for (int i = 0; i < arr.Length; i++) {
// Sum of subarray from i to j
int sum = 0;
for (int j = i; j < arr.Length; j++) {
sum += arr[j];
// If subarray sum is equal to k
if (sum == k) {
// find subarray length and update result
int subLen = j - i + 1;
res = Math.Max(res, subLen);
}
}
}
return res;
}
static void Main() {
int[] arr = {10, 5, 2, 7, 1, -10};
int k = 15;
Console.WriteLine(longestSubarray(arr, k));
}
}
JavaScript
// JavaScript program to find the length of the longest
// subarray having sum k using nested loop
// Function to find longest sub-array having sum k
function longestSubarray(arr, k) {
let res = 0;
for (let i = 0; i < arr.length; i++) {
// Sum of subarray from i to j
let sum = 0;
for (let j = i; j < arr.length; j++) {
sum += arr[j];
// If subarray sum is equal to k
if (sum === k) {
// find subarray length and update result
let subLen = j - i + 1;
res = Math.max(res, subLen);
}
}
}
return res;
}
// Driver Code
const arr = [10, 5, 2, 7, 1, -10];
const k = 15;
console.log(longestSubarray(arr, k));
[Expected Approach] Using Hash Map and Prefix Sum - O(n) Time and O(n) Space
If you take a closer look at this problem, this is mainly an extension of Longest Subarray with 0 sum.
The idea is based on the fact that if Sj - Si = k (where Si and Sj are prefix sums till index i and j respectively, and i < j), then the subarray between i+1 to j has sum equal to k.
For example, arr[] = [5, 2, -3, 4, 7] and k = 3. The value of S3 - S0= 3, it means the subarray from index 1 to 3 has sum equals to 3.
So we mainly compute prefix sums in the array and store these prefix sums in a hash table. And check if current prefix sum - k is already present. If current prefix sum - k is present in the hash table and is mapped to index j, then subarray from j to current index has sum equal to k.
Below are the main points to consider in your implementation.
- If we have the whole prefix having sum equal to k, we should prefer it as it would be the longest possible till that point.
- If there are multiple occurrences of a prefixSum, we must store index of the earliest occurrence of prefixSum because we need to find the longest subarray.
C++
// C++ program to find longest sub-array having sum k
// using Hash Map and Prefix Sum
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// Function to find longest sub-array having sum k
int longestSubarray(vector<int>& arr, int k) {
unordered_map<int, int> mp;
int res = 0;
int prefSum = 0;
for (int i = 0; i < arr.size(); ++i) {
prefSum += arr[i];
// Check if the entire prefix sums to k
if (prefSum == k)
res = i + 1;
// If prefixSum - k exists in the map then there exist such
// subarray from (index of previous prefix + 1) to i.
else if (mp.find(prefSum - k) != mp.end())
res = max(res, i - mp[prefSum - k]);
// Store only first occurrence index of prefSum
if (mp.find(prefSum) == mp.end())
mp[prefSum] = i;
}
return res;
}
int main() {
vector<int> arr = {10, 5, 2, 7, 1, -10};
int k = 15;
cout << longestSubarray(arr, k) << endl;
}
Java
// Java program to find longest sub-array having sum k
// using Hash Map and Prefix Sum
import java.util.HashMap;
import java.util.Map;
class GfG {
// Function to find longest sub-array having sum k
static int longestSubarray(int[] arr, int k) {
Map<Integer, Integer> mp = new HashMap<>();
int res = 0;
int prefSum = 0;
for (int i = 0; i < arr.length; ++i) {
prefSum += arr[i];
// Check if the entire prefix sums to k
if (prefSum == k)
res = i + 1;
// If prefixSum - k exists in the map then there exist such
// subarray from (index of previous prefix + 1) to i.
else if (mp.containsKey(prefSum - k))
res = Math.max(res, i - mp.get(prefSum - k));
// Store only first occurrence index of prefSum
if (!mp.containsKey(prefSum))
mp.put(prefSum, i);
}
return res;
}
public static void main(String[] args) {
int[] arr = {10, 5, 2, 7, 1, -10};
int k = 15;
System.out.println(longestSubarray(arr, k));
}
}
Python
# Python program to find longest sub-array having sum k
# using Hash Map and Prefix Sum
# Function to find longest sub-array having sum k
def longestSubarray(arr, k):
mp = {}
res = 0
prefSum = 0
for i in range(len(arr)):
prefSum += arr[i]
# Check if the entire prefix sums to k
if prefSum == k:
res = i + 1
# If prefixSum - k exists in the map then there exist such
# subarray from (index of previous prefix + 1) to i.
elif (prefSum - k) in mp:
res = max(res, i - mp[prefSum - k])
# Store only first occurrence index of prefSum
if prefSum not in mp:
mp[prefSum] = i
return res
if __name__ == "__main__":
arr = [10, 5, 2, 7, 1, -10]
k = 15
print(longestSubarray(arr, k))
C#
// C# program to find longest sub-array having sum k
// using Hash Map and Prefix Sum
using System;
using System.Collections.Generic;
class GfG {
// Function to find longest sub-array having sum k
static int longestSubarray(int[] arr, int k) {
Dictionary<int, int> mp = new Dictionary<int, int>();
int res = 0;
int prefSum = 0;
for (int i = 0; i < arr.Length; ++i) {
prefSum += arr[i];
// Check if the entire prefix sums to k
if (prefSum == k)
res = i + 1;
// If prefixSum - k exists in the map then there exist such
// subarray from (index of previous prefix + 1) to i.
else if (mp.ContainsKey(prefSum - k))
res = Math.Max(res, i - mp[prefSum - k]);
// Store only first occurrence index of prefSum
if (!mp.ContainsKey(prefSum))
mp[prefSum] = i;
}
return res;
}
static void Main() {
int[] arr = {10, 5, 2, 7, 1, -10};
int k = 15;
Console.WriteLine(longestSubarray(arr, k));
}
}
JavaScript
// JavaScript program to find longest sub-array having sum k
// using Hash Map and Prefix Sum
// Function to find longest sub-array having sum k
function longestSubarray(arr, k) {
let mp = new Map();
let res = 0;
let prefSum = 0;
for (let i = 0; i < arr.length; ++i) {
prefSum += arr[i];
// Check if the entire prefix sums to k
if (prefSum === k)
res = i + 1;
// If prefixSum - k exists in the map then there exist such
// subarray from (index of previous prefix + 1) to i.
else if (mp.has(prefSum - k))
res = Math.max(res, i - mp.get(prefSum - k));
// Store only first occurrence index of prefSum
if (!mp.has(prefSum))
mp.set(prefSum, i);
}
return res;
}
// Driver Code
const arr = [10, 5, 2, 7, 1, -10];
const k = 15;
console.log(longestSubarray(arr, k));
Related Problem
Largest subarray with equal number of 0s and 1s
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read