Sum of Unit-Step Subarrays
Updated
Problem statement
A nonempty contiguous subarray is good when it is a singleton, or when every adjacent difference is the same signed value: all +1 or all -1. A change of direction makes the subarray invalid.
Return the sum of the elements of every good subarray, counting each subarray once. Equal values at different indices remain different occurrences. Return 0 for an empty array. Use O(n) time, where n = nums.length.
Function
sumGoodSubarrays(nums: int[]) → longExamples
Example 1
nums = [3,5,6,7,6]return = 82The source-listed subarrays are [3], [5], [6], [7], [6], [5,6], [6,7], [5,6,7] and [7,6]. Their element sums total 82.
Example 2
nums = [1,2,1]return = 10The singletons total 4 and the two length-2 subarrays each sum to 3. The direction-changing length-3 subarray is invalid.
Example 3
nums = [-1,0,1]return = 0Every subarray is good, and its signed element sum contributions cancel.
Constraints
0 <= nums.length <= 10^4.-10^4 <= nums[i] <= 10^4.- Return the exact signed 64-bit sum, without a modulus.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Assign Escalations to TeamsAmazon · ONSITE INTERVIEW
- Count Subsets With a Target SumSafe Security · ONSITE INTERVIEW
- Maximum Subarray Sum with One DeletionOracle · ONSITE INTERVIEWOracle interview questions
- Best Time to Buy and Sell Stock IIKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Coin ChangeMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Maximum SubarrayUpstart · ONSITE INTERVIEWUpstart interview questions
- Smallest Sufficient TeamExpedia · ONSITE INTERVIEWExpedia interview questions
- Maximum Product SubarrayHartford Financial Services · ONSITE INTERVIEWHartford Financial Services interview questions
- Word BreakMoveworks · ONSITE INTERVIEWMoveworks interview questions
- Maximum Value from Circular HousesDigitalOcean · ONSITE INTERVIEWDigitalOcean interview questions