Count Subarrays with a 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 to target.
The array may be empty and may contain positive, zero, and negative values. Return 0 when no qualifying subarray exists.
Function
subarraySum(nums: int[], target: int) → intExamples
Example 1
nums = [1,1,1]target = 2return = 2The subarrays at indices [0,1] and [1,2] both sum to 2.
Example 2
nums = [1,-1,0]target = 0return = 3The qualifying subarrays are [1,-1], [0], and [1,-1,0].
Example 3
nums = []target = 5return = 0An empty array has no non-empty subarrays.
Constraints
- Every element and
targetfit in a signed32-bit integer. - Prefix sums are accumulated with a signed
64-bit integer. - The returned count fits in a signed
32-bit integer.
More Meta Phone Screen questions
- Convert a Sorted Linked List to a Balanced BSTPHONE SCREEN · Seen Nov 2026
- Fuzzy Word Lookup With One Misspelled LetterPHONE SCREEN · Seen Nov 2026
- Multi-Head Attention Forward PassPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Run-Length Encoded Vector Dot ProductPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Mutual-Friend RecommendationsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Time to Buy and Sell StockPHONE SCREEN · Seen Nov 2026
- First Element Greater Than KPHONE SCREEN · Seen Nov 2026
- Count Events in Rolling Minute WindowsPHONE SCREEN · Seen Oct 2026
- Valid Word AbbreviationPHONE SCREEN · Seen Oct 2026
- Shortest Path in a Binary MatrixPHONE SCREEN · Seen Sep 2026
Similar questions at other companies
- Maximum Sum Desirable SubarrayGroww · PHONE SCREEN
- Equal Sum Split After One RemovalGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Maximum Size Subarray Sum Equals KeBay · PHONE SCREENeBay interview questions
- Count Subarrays With Target SumAmazon · PHONE SCREEN
- Count Subarrays with Sum KByteDance · PHONE SCREENByteDance interview questions
- Subarray Sum Equals KApple · PHONE SCREEN · ONSITE INTERVIEWApple interview questions
- Longest Equal-Zero-One SubarrayMotive · PHONE SCREEN · ONSITE INTERVIEWMotive interview questions
- Shortest Subarray with an Exact Target SumPeopleStrong · PHONE SCREENPeopleStrong interview questions
- Count Subarrays That Add Up to kAdobe · PHONE SCREENAdobe interview questions
- Find a Target-Sum SubarrayMorgan Stanley · PHONE SCREENMorgan Stanley interview questions