Count Subarrays with a Target Sum
Updated
Problem statement
Given an integer array nums and a target, count the nonempty consecutive parts of the array whose sum is exactly the target. Count two subarrays separately if they have different start or end indices.
For this exercise, assume values may be negative or zero. Return a 64-bit integer because the number of matching subarrays may exceed a signed 32-bit integer. An empty array has answer zero.
Function
countTargetSubarrays(nums: int[], target: long) → longExamples
Example 1
nums = [1,-1,1]target = 1return = 3The matching index ranges are [0,0], [0,2] and [2,2].
Example 2
nums = [0,0,0]target = 0return = 6All three length-one, both length-two and the length-three subarrays qualify.
Constraints
- For this exercise, assume
0 <= nums.length <= 10^5. -10^9 <= nums[i] <= 10^9.-10^14 <= target <= 10^14; use 64-bit prefix sums and counts.
More PeopleStrong Onsite Interview questions
- Add Two Binary StringsONSITE INTERVIEW · Seen Mar 2026
- Four SumONSITE INTERVIEW · Seen Mar 2026
- LRU Cache OperationsONSITE INTERVIEW · Seen Mar 2026
- Sliding Window MaximumONSITE INTERVIEW · Seen Mar 2026
- Find the Entry of a Linked List CycleONSITE INTERVIEW · Seen Sep 2025
- Integer to English Words: Up to 20 DigitsONSITE INTERVIEW · Seen Sep 2025
- Word Ladder II: All Shortest TransformationsONSITE INTERVIEW · Seen Sep 2025
- Detect a Cycle in a Linked ListONSITE INTERVIEW · Seen May 2025
- First Nonrepeating CharacterONSITE INTERVIEW · Seen May 2025
- Longest Subarray with a Target SumONSITE INTERVIEW · Seen May 2025
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
- 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
- Count Subarrays With Target SumAmazon · PHONE SCREEN