ExamAdda Logo

Longest Subarray with Sum K

Easy

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 1

Input

arr[] = [1, 2, 3, 1, 1, 1, 1], k = 6

Output

4

Explanation

Explanation: Subarray [1, 2, 3] → Sum = 6 Length = 3 Subarray [3, 1, 1, 1] → Sum = 6 Length = 4 Longest Length = 4

Example 2

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

Hints:

Hint 1
test hint

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Jun 29, 2026

Last updated

Aug 6, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output