Problem · Array
Nearest Value Replacement
Learn this problemProblem 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:
- Let
nextValue = A[cur] + 1. - Among all indices
iwith|i - cur| <= DandA[i] = nextValue, choose the nearest index. If distances tie, choose the smaller index. - If no such index exists, stop without changing
A[cur]. - Otherwise, set
A[cur] = nextValue, movecurto the chosen index, and continue.
Return the updated array.
Function
nearestValueReplacement(A: int[], cur: int, D: int) → int[]Complete nearestValueReplacement with the following parameters:
int[] A: the array to updateint cur: the zero-based starting indexint 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
Ais non-empty.0 <= cur < A.length.D >= 0.
More Google problems
- Deduplicate Logs: Keep FirstONSITE INTERVIEW · Seen Jul 2026
- Deduplicate Logs: Keep LatestONSITE INTERVIEW · Seen Jul 2026
- Find a Template Across Binary-Tree LeavesONSITE INTERVIEW · Seen Jul 2026
- Maximum Programmer-Problem MatchingONSITE INTERVIEW · Seen Jul 2026
- Minimum Direction ViolationsONSITE INTERVIEW · Seen Jul 2026
- Stream Latest Log VersionsONSITE INTERVIEW · Seen Jul 2026
- Stream Unique Logs in Timestamp OrderONSITE INTERVIEW · Seen Jul 2026
- Top-K IP Addresses from File RecordsONSITE INTERVIEW · Seen Jul 2026