Subarray Sum Equals K
Updated
Problem statement
You are given an integer array nums and an integer k. A subarray is a run of one or more elements that sit next to each other in the array. Return how many subarrays add up to exactly k.
Two subarrays count separately when they start or end at different positions, even if they hold the same values. Values may be negative or zero. If the array is empty, the answer is zero.
Function
countSubarrays(nums: int[], k: int) → intExamples
Example 1
nums = [1,1,1]k = 2return = 2The first two elements add up to two, and so do the last two. A single element is too small, and all three together are too big. So the answer is two.
Example 2
nums = [1,-1,0]k = 0return = 3Three subarrays add up to zero: [1,-1], [0], and [1,-1,0]. So the answer is three.
Constraints
0 <= nums.length <= 20000.-10^9 <= nums[i], k <= 10^9.- The returned count fits in a signed 32-bit integer. Running sums can go past that range, so add them up in a wider integer type.
More Apple Onsite Interview questions
- Topological OrderingPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- FIFO Mutex Operation TraceONSITE INTERVIEW · Seen Oct 2026
- Implement Hit CounterPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Parse Nested HTML into a TreeONSITE INTERVIEW · Seen Oct 2026
- Thread-Safe Concurrent Linked ListONSITE INTERVIEW · Seen Sep 2026
- Palindrome Match PercentageONSITE INTERVIEW · Seen Sep 2026
- Binary Tree Nodes at Distance KONSITE INTERVIEW · Seen Aug 2026
- BST to Sorted Circular Doubly Linked ListONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- Subarray Sum Equals KServiceNow · ONSITE INTERVIEWServiceNow interview questions
- Count Subarrays with Equal Even and Odd CountsMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Maximum Sum Desirable SubarrayGroww · PHONE SCREEN
- Maximum Subarray Sum with Equal EndpointsGoogle · ONSITE INTERVIEWGoogle interview questions
- Maximum Size Subarray Sum Equals KeBay · PHONE SCREENeBay interview questions
- Count Subarrays with Sum KMakeMyTrip.com · ONSITE INTERVIEWMakeMyTrip.com interview questions
- Detect a Contiguous Subarray with Target SumMeta · PHONE SCREENMeta interview questions
- Count Subarrays With Target SumAmazon · PHONE SCREEN
- Count Subarrays with Sum KByteDance · PHONE SCREENByteDance interview questions
- Longest Equal-Zero-One SubarrayMotive · PHONE SCREEN · ONSITE INTERVIEWMotive interview questions