Problem · Array

Nearest Value Replacement

Learn this problem
MediumGoogleFULLTIMEPHONE SCREEN
See Google hiring insights

Problem statement

You are given an integer array A of length N, a zero-based starting index cur, and a distance D.

Update the array by repeating these steps:

  1. Let nextValue = A[cur] + 1.
  2. Among all indices i with |i - cur| <= D and A[i] = nextValue, choose the nearest index. If distances tie, choose the smaller index.
  3. If no such index exists, stop without changing A[cur].
  4. Otherwise, set A[cur] = nextValue, move cur to the chosen index, and continue.

Return the updated array.

Function

nearestValueReplacement(A: int[], cur: int, D: int) → int[]

Complete nearestValueReplacement with the following parameters:

  1. int[] A: the array to update
  2. int cur: the zero-based starting index
  3. int D: the maximum search distance

Examples

Example 1

A = [1, 3, 2, 3, 4, 5, 2]cur = 2D = 2return = [1, 3, 3, 3, 4, 5, 2]
At index 2, the next value is 3. Indices 1 and 3 both contain 3 at distance 1, so choose index 1 and set A[2] to 3. From index 1, the next value is 4, but the only 4 is at index 4, which is outside distance 2. Stop without changing A[1].

Constraints

  • A is non-empty.
  • 0 <= cur < A.length.
  • D >= 0.

More Google problems

drafts saved locally
public int[] nearestValueReplacement(int[] A, int cur, int D) {
  // write your code here
}
A[1, 3, 2, 3, 4, 5, 2]
cur2
D2
expected[1, 3, 3, 3, 4, 5, 2]
checking account