Nearest Value Replacement
MediumSimulation · Google
You start at index start of the integer list values (0-indexed). Repeat the following step:
- Increase
values[current]by1. Call the new valuetarget. - Among all other indices
jwithvalues[j] == targetandabs(j - current) <= distance, pick the one closest tocurrent. If two are equally close (one on each side), pick the smaller index. - If such an index exists, it becomes
currentand you repeat from step 1. Otherwise, stop.
Return the list after the walk stops. (The walk always stops: target grows by exactly one every step, and a cell you have left never holds a future target again.)
Example 1
- Input:
- values = [1, 2, 2, 3], start = 0, distance = 2
- Output:
- [2, 3, 2, 4]
- Explanation
- Index 0 rises to 2, which now matches index 1 at distance 1 and index 2 at distance 2, so the nearer one wins. Index 1 then rises to 3, which matches index 3, and that rises to 4 with nothing left to match.
Example 2
- Input:
- values = [4, 6, 5, 9, 5], start = 2, distance = 3
- Output:
- [4, 7, 6, 9, 5]
- Explanation
- Index 2 rises from 5 to 6; index 1 holds 6 at distance 1, so move there. Index 1 rises to 7, and no other cell holds 7, so the walk stops.
Example 3
- Input:
- values = [3, 2, 2, 5, 3], start = 2, distance = 2
- Output:
- [4, 2, 3, 5, 3]
- Explanation
- Index 2 rises to 3; both index 0 and index 4 hold 3 at distance 2, so the smaller index 0 wins. Index 0 rises to 4 and nothing within distance 2 holds 4.
Constraints
1 <= values.length <= 10^51 <= values[i] <= 10^90 <= start < values.length0 <= distance <= values.length