Replace Elements with Greatest Element on Right Side
Given an array arr, replace every element with the greatest element among the elements to its right, and replace the last element with -1. Walk the array from right to left , keeping a running maximum of everything already visited, so every position can be overwritten using only values further right.
Constraints
- 1 ≤ arr.length ≤ 104
- 1 ≤ arri ≤ 105
Example
arr = [17, 18, 5, 4, 6, 1][18, 18, 6, 6, 1, -1]Explanation The greatest element to the right of index 0 is 18, of index 1 is 6, and so on; the last element becomes -1.
Scan from the right, tracking the max seen so far
i=5 (value 1). runningMax=-1. Set arr[5]=-1, then runningMax becomes max(-1, 1)=1.
What happens in this step
i = 5, arr[5] = 1, runningMax = -1 arr[5] = runningMax = -1 runningMax = max(-1, 1) = 1
Steps to visualize
- Start a runningMax at -1 and walk the array from the last index to the first.
- At each index, save the current value before overwriting it.
- Set arri to runningMax.
- Update runningMax to be the larger of runningMax and the saved value.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
i=5 (value 1). runningMax=-1. Set arr[5]=-1, then runningMax becomes max(-1, 1)=1.
What happens in this step
i = 5, arr[5] = 1, runningMax = -1 arr[5] = runningMax = -1 runningMax = max(-1, 1) = 1
Solution
function replaceElements(arr) {
const result = arr.slice();
let runningMax = -1;
for (let i = result.length - 1; i >= 0; i--) {
const current = result[i];
result[i] = runningMax;
runningMax = Math.max(runningMax, current);
}
return result;
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
arr = [17, 18, 5, 4, 6, 1] | [18, 6, 6, 6, 1, -1] | example from the docstring |
arr = [400] | [-1] | smallest valid input, a single element becomes -1 |
arr = [1, 2] | [2, -1] | boundary case, exactly two elements |
arr = [5, 4, 3, 2, 1] | [4, 3, 2, 1, -1] | strictly decreasing array, each element is its own right neighbor max |
arr = [3, 3, 3] | [3, 3, -1] | every value identical except the trailing -1 |
arr = [1, 2, 3, 4] | [4, 4, 4, -1] | strictly increasing array, max always comes from the far right |