← Questions

Sum of all consecutive-step subarrays

0
GoogleCodingLast asked Feb 2026

A coding interview question asked in Google's onsite coding round, last asked Feb 2026. It tests arrays and prefix sums.

Call a contiguous subarray consecutive when each element is exactly one more than the one before it, or each element is exactly one less (every single element counts on its own). Return the sum of the values of all consecutive subarrays of an integer array, modulo 10^9 + 7.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • sum_consecutive_subarrays(nums: list[int]) -> int

Example

[1, 2, 3]   ->  20   # [1] [2] [3] [1,2] [2,3] [1,2,3]: 1+2+3+3+5+6
[1, 3, 2]   ->  11   # singles give 6, plus [3,2] = 5
[1, 2, 1]   ->  10   # singles 4, [1,2] = 3, [2,1] = 3; [1,2,1] changes direction
[5]         ->  5

Constraints

  • 1 <= len(nums) <= 10^5, 1 <= nums[i] <= 10^5.
  • Intermediate sums exceed 32 bits: use 64-bit arithmetic or reduce modulo as you go.

Clarifying questions

  • Does a single element count as consecutive?
  • Does a subarray of length 2 count in both directions ([2,1] and [1,2])?
  • Is the answer taken modulo a prime?

What a strong answer covers

  • Brute force over all subarrays is O(n^2) or worse.
  • Splitting the array into maximal runs with step +1 and maximal runs with step -1: an element at position p (from 0) of a run of length L appears in (p + 1) * (L - p) subarrays of that run.
  • Or a dynamic program: for subarrays ending at i, keep the count and sum for the increasing and decreasing cases, extended from i - 1 when the step is +1 or -1.
  • Not double counting single elements, which belong to both an increasing and a decreasing run: subtract the plain sum of the array once.
  • O(n) time, O(1) extra space; checked against brute force on small inputs.

Follow-ups

  • Count the consecutive subarrays instead of summing them.
  • Allow any fixed step d, not only 1.
  • Answer the same question for many ranges [l, r] of the array.

Where it's asked

  • Google · Onsite coding · Last asked Feb 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

arrays · prefix sums

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding