Longest Subarray with Sum K
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
Example 2
Input
arr[] = [2, 1, 1, 1, 3, 2] k = 5
Output
4
Explanation
Constraints
Hints:
Hint 1
Author & Technical Reviewer
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.
Expected Output