Subarray Sum Equals K
Medium Prefix Sum AI round
nums is a list of whole numbers, and k is one more whole number. Any of them may be negative or zero.
A subarray is a run of numbers next to each other in nums: one number, or several with none left out between the first and the last. Two subarrays are different when they start or end at different places, even if their numbers are the same.
Return how many subarrays of nums add up to exactly k.
Example 1
Five subarrays add up to 2: [2] at the start, [2, -1, 3, -2], [-1, 3], [-1, 3, -2, 2] and [2] at the end.
Example 2
Every subarray adds up to 0: three of one number, two of two numbers and the whole list.
Example 3
Constraints
1 ≤ nums.length ≤ 2 × 10⁵-5000 ≤ nums[i] ≤ 5000-10⁹ ≤ k ≤ 10⁹- The answer is less than 2³¹, so it fits in a signed 32-bit integer
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
Watch the explanation
More Prefix Sum
- Product of Array Except SelfAI round · Medium
- Find Pivot IndexAI round · Easy
- Contiguous ArrayMedium
- Running Sum of 1d ArrayVery easy
- Subarray Sums Divisible by KMedium