Arrays and Hashing Prefix sums

75. Maximum Size Subarray Sum Equals k

Medium

You are given an array of integers nums and an integer k. Return the length of the longest subarray whose elements add up to exactly k. If no subarray adds up to k, return 0.

A subarray is a contiguous sequence of elements from nums. Its length is the number of elements in it.

Example 1

Input: nums = [4, -2, 1, 3, -2, 2], k = 4

Output: 5

Explanation: Four subarrays add up to 4: [4], [1, 3], [1, 3, -2, 2] and the first five elements [4, -2, 1, 3, -2]. The longest of them has 5 elements.

Example 2

Input: nums = [2, 2, 2], k = 5

Output: 0

Explanation: Every subarray adds up to an even number, so none adds up to 5.

Example 3

Input: nums = [-1, 2, -1, 0, 1], k = 1

Output: 5

Explanation: The whole array adds up to 1, so the answer is its length. Shorter subarrays such as [-1, 2] and [2, -1, 0] add up to 1 as well.

Check your understanding

Work out the answer for this input before you write any code.

nums = [0, 0, 0], k = 0

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • -109 ≤ k ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.