FastPrepLongest Target-Mean Subarray After Each Arrival

Longest Target-Mean Subarray After Each Arrival

Google logoGoogle● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given an integer array arrivals and an integer target, treat the array as a stream whose values arrive one at a time in the given order. Values may be positive, zero or negative.

After every arrival, report the length of the longest nonempty contiguous subarray anywhere among the values seen so far whose arithmetic mean is exactly target.

Return an integer array answer of the same length as arrivals, where answer[i] is the result after receiving arrivals[i].

  • Only indices from 0 through i may be used for answer[i].
  • The qualifying subarray does not need to end at i. An earlier longest subarray remains eligible after later arrivals.
  • A subarray from left through right qualifies exactly when its sum equals target * (right - left + 1).
  • Return 0 for that arrival if no nonempty subarray qualifies. Return lengths only, so equal-length choices produce the same result.

Function

longestMeanAfterEachArrival(arrivals: int[], target: int) → int[]

Examples

Example 1

arrivals = [3,-1,5,1,8]target = 2return = [0,0,2,4,4]

The first two prefixes contain no qualifying subarray. After 5 arrives, [-1,5] has mean 2 and length 2. After 1 arrives, [3,-1,5,1] has sum 8, mean 2 and length 4. The final arrival creates no longer qualifying interval, so the result stays 4.

Example 2

arrivals = [2,2,2]target = 2return = [1,2,3]

Every arrived value equals the target, so the entire arrived prefix qualifies after each arrival.

Example 3

arrivals = [1,2,3]target = 4return = [0,0,0]

Every value is below 4. No nonempty interval can have mean 4, so every result is 0.

Constraints

  • 1 <= arrivals.length <= 100000.
  • -10^9 <= arrivals[i] <= 10^9.
  • -10^9 <= target <= 10^9, and target is an integer.
  • Evaluate the mean condition exactly. Original sums, shifted prefix sums and target * length fit a signed 64-bit integer.

More Google problems

See Google hiring insights
public int[] longestMeanAfterEachArrival(int[] arrivals, int target) {
    // Return one longest qualifying length after each arrival.
}
arrivals[3,-1,5,1,8]
target2
expected[0,0,2,4,4]
Checking account…