Maximum Size Subarray Sum Equals k
MediumArrays & Hashingprefix sum
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given an integer array nums (values may be negative) and an integer k, return the length of the longest contiguous subarray whose elements add up to exactly k.
If no such subarray exists, return 0. Target O(n) time.
Examples
Input: nums = [1,-1,5,-2,3], k = 3
Output: 4
The subarray [1,-1,5,-2] sums to 3 and is the longest such run.
Input: nums = [-2,-1,2,1], k = 1
Output: 2
The subarray [-1,2] sums to 1.
Constraints
- 1 <= nums.length <= 2 * 10^5
- -10^4 <= nums[i] <= 10^4
- -10^9 <= k <= 10^9
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.