Count Subarrays With Target Sum
Updated
Problem statement
Given an integer array nums and an integer target, return the number of non-empty contiguous subarrays whose elements sum exactly to target.
A subarray is a contiguous range of one or more elements. Different index ranges count separately, even when they contain the same values.
Function
countSubarraysWithTargetSum(nums: int[], target: long) → longExamples
Example 1
nums = [1,1,1]target = 2return = 2The subarrays at indices 0 through 1 and 1 through 2 each sum to 2.
Example 2
nums = [1,-1,0]target = 0return = 3The ranges [1, -1], [1, -1, 0], and [0] have sum 0.
Constraints
1 <= nums.length <= 100000-10^9 <= nums[i] <= 10^9-10^14 <= target <= 10^14- The answer fits in a signed 64-bit integer.
More Amazon Phone Screen questions
- Course SchedulePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Search in a Rotated Sorted ArrayPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Top K Frequent ElementsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- LRU Cache for Query ResultsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Course Schedule IIPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Minimum Time to Spread Through a GridPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Consistent-Hash Packet RouterPHONE SCREEN · Seen Nov 2026
- Count Connected ComponentsPHONE SCREEN · Seen Nov 2026
- Second Largest Distinct ElementPHONE SCREEN · Seen Nov 2026
- Task SchedulerOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Maximum Sum Desirable SubarrayGroww · PHONE SCREEN
- Equal Sum Split After One RemovalGoogle · PHONE SCREEN · ONSITE INTERVIEW
- Maximum Size Subarray Sum Equals KeBay · PHONE SCREEN
- Detect a Contiguous Subarray with Target SumMeta · PHONE SCREEN
- Count Subarrays with Sum KByteDance · PHONE SCREEN
- Subarray Sum Equals KApple · PHONE SCREEN · ONSITE INTERVIEW
- Longest Equal-Zero-One SubarrayMotive · PHONE SCREEN · ONSITE INTERVIEW
- Shortest Subarray with an Exact Target SumPeopleStrong · PHONE SCREEN
- Count Subarrays That Add Up to kAdobe · PHONE SCREEN
- Find a Target-Sum SubarrayMorgan Stanley · PHONE SCREEN