Subarray Sum Equals K
Updated
Problem statement
You are given an integer array nums and an integer k. Return how many subarrays of nums have a sum equal to k.
A subarray is a non-empty run of elements that are next to each other in nums. Two subarrays at different positions count separately, even if they hold the same values.
Function
subarraySum(nums: int[], k: int) → intExamples
Example 1
nums = [1,2,3,-2,2]k = 3return = 4Four subarrays add up to 3: [1, 2], [3], [2, 3, -2] and [3, -2, 2].
Example 2
nums = [2,2,2]k = 4return = 2The first two 2 values and the last two 2 values are two different subarrays, so the answer is 2.
Example 3
nums = [1,-1,1,-1]k = 0return = 4The subarrays with sum 0 are [1, -1] at the start, [-1, 1] in the middle, [1, -1] at the end, and the whole array. That is 4.
Constraints
1 <= nums.length <= 2 * 10^4-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7
More ServiceNow interview questions
Similar questions at other companies
- Count Subarrays with Equal Even and Odd CountsMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Maximum Subarray Sum with Equal EndpointsGoogle · ONSITE INTERVIEWGoogle interview questions
- Count Subarrays with Sum KMakeMyTrip.com · ONSITE INTERVIEWMakeMyTrip.com interview questions
- Subarray Sum Equals KApple · PHONE SCREEN · ONSITE INTERVIEWApple interview questions
- Longest Equal-Zero-One SubarrayMotive · PHONE SCREEN · ONSITE INTERVIEWMotive interview questions
- Find and Measure the Longest Target-Sum SubarrayMeta · ONSITE INTERVIEWMeta interview questions
- Longest Subarray with a Target SumPeopleStrong · ONSITE INTERVIEWPeopleStrong interview questions
- Count Subarrays Whose Sum Is KExpedia · ONSITE INTERVIEWExpedia interview questions
- Maximum Sum Desirable SubarrayGroww · PHONE SCREEN
- Maximum Size Subarray Sum Equals KeBay · PHONE SCREENeBay interview questions