Google questions

Good Subarray Sums

GoogleOnsiteMedium

A subarray is a contiguous run of elements of an array. A subarray is good when it has exactly one element, or when every element is exactly 1 more than the one before it, or every element is exactly 1 less than the one before it. Subarrays at different positions count separately, even if they hold the same values.

Part 1: Sum of good subarrays

You are given an integer array nums. Return the total of the sums of all good subarrays of nums.

Every single element is a good subarray. A longer subarray is good when its values go up by exactly 1 each step, or down by exactly 1 each step. Equal neighbors do not form a good subarray of length 2 or more.

The answer may be large; any integer width is accepted.

  1. Example 1
    nums
    [3,5,6,7,6]
    Output
    82

    Why: The five single elements sum to 27. The good longer subarrays are [5, 6], [6, 7], [5, 6, 7] and [7, 6], summing to 11 + 13 + 18 + 13 = 55. Total 27 + 55 = 82.

  2. Example 2
    nums
    [1,2,3]
    Output
    20

    Why: The singles sum to 6, the pairs [1, 2] and [2, 3] to 3 + 5, and [1, 2, 3] to 6, giving 20.

Constraints

  • 1 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Good Subarray Sums: Google interview question | LoopCoach