Longest Subarray With Given Sum K

Given an integer array nums and an integer k, return the length of the longest non-empty contiguous subarray whose elements sum to k. Return 0 if no such…

Given an integer array `nums` and an integer `k`, return the length of the longest non-empty contiguous subarray whose elements sum to `k`. Return `0` if no such subarray exists.

- `1 <= nums.length <= 2 * 10^4` - `-1000 <= nums[i] <= 1000` - `-10^7 <= k <= 10^7` - The interactive visualizer accepts at most 12 values and k from -10000 to 10000; larger statement-valid inputs are execution-only.

Example 1: input nums = [10,5,2,7,1,9], k = 15; output 4. The subarray [5,2,7,1] has sum 15 and length 4.

Example 2: input nums = [-2,-1,2,1], k = 1; output 2. The subarray [-1,2] has sum 1 and length 2.

Category: Arrays & Hashing. Topic: arrays. Difficulty: Medium. Patterns: hashing, prefix-sum.