Arrays January 13 ,2026

Longest Subarray with Sum K

Problem Statement

Given an array of integers and an integer K, find the length of the longest contiguous subarray whose sum is exactly equal to K.

If no such subarray exists, return 0.

Why This Problem Is Important

  • Very common interview question
  • Tests understanding of:
    • Prefix Sum
    • Hashing
    • Sliding Window logic
  • Extension of:
    • Subarray with Given Sum
    • Two Sum
    • Kadane’s concepts

Example 1 (Positive + Negative Numbers)

Input

arr = [10, 5, 2, 7, 1, 9]
K = 15

Output

4

Explanation

Subarray: [5, 2, 7, 1]
Sum = 15
Length = 4 (longest)

Example 2

Input

arr = [1, -1, 5, -2, 3]
K = 3

Output

4

Explanation

Subarray: [1, -1, 5, -2]

Key Observation

The approach depends on array elements:

Array TypeBest Approach
Only positive numbersSliding Window
Contains negative numbersPrefix Sum + Hash Map

Approach 1: Prefix Sum + Hash Map (Works for All Cases)

Core Idea

If:

prefixSum[j] - prefixSum[i] = K

Then:

prefixSum[i] = prefixSum[j] - K

To get the longest length, we:

  • Store the first occurrence of each prefix sum
  • Do not overwrite existing sums

Algorithm

  1. Initialize:
    • sum = 0
    • maxLen = 0
    • Hash map prefixSum → index
  2. Traverse array:
    • Add element to sum
  3. If sum == K:
    • Update maxLen = i + 1
  4. If (sum - K) exists in map:
    • Length = i - map[sum - K]
    • Update maxLen
  5. Store sum in map only if not already present

Time and Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(n)

C Implementation

#include <stdio.h>

int main() {
    int arr[] = {10, 5, 2, 7, 1, 9};
    int n = 6, K = 15;

    int sum = 0, maxLen = 0;
    int prefixSum[1000];
    int index[1000];
    int size = 0;

    for(int i = 0; i < n; i++) {
        sum += arr[i];

        if(sum == K)
            maxLen = i + 1;

        for(int j = 0; j < size; j++) {
            if(prefixSum[j] == sum - K) {
                int len = i - index[j];
                if(len > maxLen)
                    maxLen = len;
            }
        }

        int found = 0;
        for(int j = 0; j < size; j++) {
            if(prefixSum[j] == sum)
                found = 1;
        }

        if(!found) {
            prefixSum[size] = sum;
            index[size] = i;
            size++;
        }
    }

    printf("Longest subarray length: %d", maxLen);
    return 0;
}

Output

Longest subarray length: 4

C++ Implementation

#include <iostream>
#include <unordered_map>
using namespace std;

int main() {
    int arr[] = {10, 5, 2, 7, 1, 9};
    int n = 6, K = 15;

    unordered_map<int, int> mp;
    int sum = 0, maxLen = 0;

    for(int i = 0; i < n; i++) {
        sum += arr[i];

        if(sum == K)
            maxLen = i + 1;

        if(mp.find(sum - K) != mp.end())
            maxLen = max(maxLen, i - mp[sum - K]);

        if(mp.find(sum) == mp.end())
            mp[sum] = i;
    }

    cout << "Longest subarray length: " << maxLen;
    return 0;
}

Java Implementation

import java.util.*;

public class LongestSubarraySumK {
    public static void main(String[] args) {
        int[] arr = {10, 5, 2, 7, 1, 9};
        int K = 15;

        Map map = new HashMap<>();
        int sum = 0, maxLen = 0;

        for(int i = 0; i < arr.length; i++) {
            sum += arr[i];

            if(sum == K)
                maxLen = i + 1;

            if(map.containsKey(sum - K))
                maxLen = Math.max(maxLen, i - map.get(sum - K));

            map.putIfAbsent(sum, i);
        }

        System.out.println("Longest subarray length: " + maxLen);
    }
}

Python Implementation

arr = [10, 5, 2, 7, 1, 9]
K = 15

prefix_map = {}
sum_val = 0
max_len = 0

for i, num in enumerate(arr):
    sum_val += num

    if sum_val == K:
        max_len = i + 1

    if sum_val - K in prefix_map:
        max_len = max(max_len, i - prefix_map[sum_val - K])

    if sum_val not in prefix_map:
        prefix_map[sum_val] = i

print("Longest subarray length:", max_len)

Dry Run

arr = [10, 5, 2, 7, 1, 9], K = 15

Index | Element | Sum | sum-K | MaxLen
0     | 10      | 10  | -5    | 0
1     | 5       | 15  | 0     | 2
2     | 2       | 17  | 2     | 2
3     | 7       | 24  | 9     | 2
4     | 1       | 25  | 10    | 4
5     | 9       | 34  | 19    | 4

Approach 2: Sliding Window (Only Positive Numbers)

Note

This fails for negative numbers, so it is not preferred unless explicitly stated.

  • Time: O(n)
  • Space: O(1)

C Implementation

#include<stdio.h>

int main() {
    int arr[] = {1, 2, 3, 7, 5};
    int n = 5, K = 12;

    int start = 0, sum = 0, maxLen = 0;

    for (int end = 0; end < n; end++) {
        sum += arr[end];

        while (sum > K && start <= end) {
            sum -= arr[start];
            start++;
        }

        if (sum == K) {
            int len = end - start + 1;
            if (len > maxLen)
                maxLen = len;
        }
    }

    printf("Longest subarray length: %d", maxLen);
    return 0;
}

Output

Longest subarray length: 3

C++ Implementation

#include<iostream>
using namespace std;

int main() {
    int arr[] = {1, 2, 3, 7, 5};
    int n = 5, K = 12;

    int start = 0, sum = 0, maxLen = 0;

    for (int end = 0; end < n; end++) {
        sum += arr[end];

        while (sum > K && start <= end) {
            sum -= arr[start++];
        }

        if (sum == K) {
            maxLen = max(maxLen, end - start + 1);
        }
    }

    cout << "Longest subarray length: " << maxLen;
    return 0;
}

Output

Longest subarray length: 3

Java Implementation

public class LongestSubarraySlidingWindow {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 7, 5};
        int K = 12;

        int start = 0, sum = 0, maxLen = 0;

        for (int end = 0; end < arr.length; end++) {
            sum += arr[end];

            while (sum > K && start <= end) {
                sum -= arr[start++];
            }

            if (sum == K) {
                maxLen = Math.max(maxLen, end - start + 1);
            }
        }

        System.out.println("Longest subarray length: " + maxLen);
    }
}

Python Implementation

arr = [1, 2, 3, 7, 5]
K = 12

start = 0
sum_val = 0
max_len = 0

for end in range(len(arr)):
    sum_val += arr[end]

    while sum_val > K and start <= end:
        sum_val -= arr[start]
        start += 1

    if sum_val == K:
        max_len = max(max_len, end - start + 1)

print("Longest subarray length:", max_len)

JavaScript Implementation

let arr = [1, 2, 3, 7, 5];
let K = 12;

let start = 0, sum = 0, maxLen = 0;

for (let end = 0; end < arr.length; end++) {
    sum += arr[end];

    while (sum > K && start <= end) {
        sum -= arr[start++];
    }

    if (sum === K) {
        maxLen = Math.max(maxLen, end - start + 1);
    }
}

console.log("Longest subarray length:", maxLen);

 

Summary

  • Subarray must be continuous
  • Prefix Sum + Hash Map gives:
    • Optimal time
    • Works for all cases
  • Store first occurrence only to maximize length
  • Very common follow-up after:
    • Subarray with Given Sum
    • Kadane’s Algorithm

Next Problems in the series

Rearrange Array Alternately (Max–Min)

 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com