Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
K-th Largest Sum Contiguous Subarray
Next article icon

Longest Subarray With Sum K

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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[].

Table of Content

  • [Naive Approach] Using Nested Loop – O(n^2) Time and O(1) Space
  • [Expected Approach] Using Hash Map and Prefix Sum – O(n) Time and O(n) Space

[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)); 

Output
6 

[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.

  1. 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.
  2. 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)); 

Output
6 

Related Problem

Largest subarray with equal number of 0s and 1s



Next Article
K-th Largest Sum Contiguous Subarray

A

ayushjauhari14
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Amazon
  • prefix-sum
Practice Tags :
  • Amazon
  • Arrays
  • Hash
  • prefix-sum

Similar Reads

  • Longest Subarray with 0 Sum
    Given an array arr[] of size n, the task is to find the length of the longest subarray with sum equal to 0. Examples: Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23}Output: 5Explanation: The longest subarray with sum equals to 0 is {-2, 2, -8, 1, 7} Input: arr[] = {1, 2, 3}Output: 0Explanation: There i
    10 min read
  • Longest Subarray with sum differences ≤ K
    Given a sorted array arr[] of size N, the task is to find the length of the longest subarray and print the subarray such that the sum of the differences of the maximum element of the chosen subarray with all other elements of that same subarray is ≤ K.i.e. ∑(amax-ai) ≤ K, for that given subarray. Ex
    7 min read
  • Longest Subarray With Sum Divisible By K
    Given an arr[] containing n integers and a positive integer k, he problem is to find the longest subarray's length with the sum of the elements divisible by k. Examples: Input: arr[] = [2, 7, 6, 1, 4, 5], k = 3Output: 4Explanation: The subarray [7, 6, 1, 4] has sum = 18, which is divisible by 3. Inp
    10 min read
  • Count of subarrays with sum at least K
    Given an array arr[] of size N and an integer K > 0. The task is to find the number of subarrays with sum at least K.Examples: Input: arr[] = {6, 1, 2, 7}, K = 10 Output: 2 {6, 1, 2, 7} and {1, 2, 7} are the only valid subarrays.Input: arr[] = {3, 3, 3}, K = 5 Output: 3 Approach: For a fixed left
    6 min read
  • K-th Largest Sum Contiguous Subarray
    Given an array arr[] of size n, the task is to find the kth largest sum of contiguous subarray within the array of numbers that has both negative and positive numbers. Examples: Input: arr[] = [20, -5, -1], k = 3Output: 14Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1), so
    15+ min read
  • Longest subarray with sum not divisible by X
    Given an array arr[] and an integer X, the task is to print the longest subarray such that the sum of its elements isn't divisible by X. If no such subarray exists, print "-1". Note: If more than one subarray exists with the given property, print any one of them.Examples: Input: arr[] = {1, 2, 3} X
    15+ min read
  • Subarray with exactly K positive sum
    Given two integer values N and K, the task is to create an array A of N integers such that number of the total positive sum subarrays is exactly K and the remaining subarrays have a negative sum (-1000 ≤ A[i] ≤ 1000). Examples: Input: N = 4, K=5Output: 2 2 -1 -1000Explanation:Positive Sum Subarrays:
    8 min read
  • Print subarray with maximum sum
    Given an array arr[], the task is to print the subarray having maximum sum. Examples: Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11. Input: arr[] = {-2, -5, 6, -2, -3, 1, 5, -6}Output: {6, -2, -3, 1, 5}Explanation: The subarray {6, -2,
    13 min read
  • Longest subarray having sum K | Set 2
    Given an array arr[] of size N containing integers. The task is to find the length of the longest sub-array having sum equal to the given value K. Examples: Input: arr[] = {2, 3, 4, 2, 1, 1}, K = 10 Output: 4 Explanation: The subarray {3, 4, 2, 1} gives summation as 10. Input: arr[] = {6, 8, 14, 9,
    14 min read
  • Smallest Subarray with Sum K from an Array
    Given an array arr[] consisting of N integers, the task is to find the length of the Smallest subarray with a sum equal to K. Examples: Input: arr[] = {2, 4, 6, 10, 2, 1}, K = 12 Output: 2 Explanation: All possible subarrays with sum 12 are {2, 4, 6} and {10, 2}. Input: arr[] = {-8, -8, -3, 8}, K =
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences