Replace Elements with Greatest Element on Right Side

Replace each number in an array with the largest number to its right, in one pass from the right end.

You are given an array of positive integers arr. Replace every number with the largest number that comes after it in the array, and replace the last number with -1, since nothing comes after it. Return the changed array.

Example 1
Input: arr = [17, 18, 5, 4, 6, 1]
Output: [18, 6, 6, 6, 1, -1]
Explanation: after 17 the largest number is 18, after 18 it is 6, and so on.
Example 2
Input: arr = [400]
Output: [-1]
Solution

The Idea

Picture six people standing in a row, each holding a number card: 17, 18, 5, 4, 6 and 1. Each person wants to know the biggest card held by anyone to their right. The person holding 17 sees 18, 5, 4, 6 and 1, so their answer is 18. The person holding 5 sees 4, 6 and 1, so their answer is 6. The last person has nobody to the right and gets -1.

If every person looks at everyone to their right, the six people make 5 + 4 + 3 + 2 + 1 = 15 looks. That is fine for six, but 100,000 numbers would need about 5 billion looks. Does each person really have to look at everyone to the right?

No. Look at the picture below. The top row is the array, and the bottom row is the answer for each position, numbered i = 0 to i = 5.

The array 17, 18, 5, 4, 6, 1 above its answer 18, 6, 6, 6, 1, -1. Each answer is the larger of the array value to its right and the answer to its right, so the answer for 17 is the larger of 18 and 6, which is 18. The walk goes from the right end, starting at -1.

Take the person holding 17, at i = 0. Everything to their right is the 18 next to them, plus everything to the right of 18. The biggest of that second part is already known: it is the answer for 18, which is 6. So the answer for 17 is the larger of 18 and 6, which is 18. The orange arrows come from those two boxes.

Every answer works the same way, as the other arrows show. It is the larger of two boxes on its right: the array value next to it, and the answer next to it. So starting at the right end with -1 and walking left, each answer takes one step to work out.

On the walk, only one number has to be remembered: the largest value seen so far. A value carried along like this is called a running maximum.

Solution Approach

Turning that idea into code means settling three things: which way to walk, what the running maximum starts at, and how to write the answers into the same array.

Walking from the right

What does the simple way cost? It uses two loops, one inside the other: the outer loop goes over each position from the left, and the inner loop scans everything to its right. That is the 15 looks from before, and the work grows with the square of the array's length. Could one walk from the left, carrying a single number, do better? No, because each answer depends on numbers that walk has not reached yet. Walking from the right, every value the next answer needs has already been passed.

The starting value

What should the running maximum hold before the walk begins? The last position has nothing to its right and needs -1, so the running maximum starts at -1. That works because all the numbers are positive: any number in the array is larger than -1 and replaces it at once. If the array could hold negative numbers, the -1 would win against them, and a different start would be needed.

Writing the answers into the same array

Can the answers go straight into arr, without a second array? Yes, but writing the answer into a position wipes out the number that was there, and the running maximum still needs that number. So each step saves the number first, writes the answer, and only then takes the saved number into the running maximum. Updating after the write also keeps a number from counting as being to its own right.

Java Solution

The method replaceElements works in these steps:

  1. First, set maxRight, the running maximum, to -1, the answer for the last position.
  2. Walk the array from right to left with one loop, moving i from the last index down to 0.
  3. Inside the loop, save arr[i] in current, then write maxRight into arr[i].
  4. Then set maxRight to the larger of maxRight and current, so the position to the left sees this number too.
  5. When the loop is done, return arr, which now holds the answers.

The main method runs both examples, a falling array, a rising array, and an array of three equal numbers.

Java
import java.util.Arrays;

public class ReplaceElementsWithGreatestFromRight {

    public static int[] replaceElements(int[] arr) {
        int maxRight = -1;                    // largest value to the right; -1 for the last slot
        for (int i = arr.length - 1; i >= 0; i--) {
            int current = arr[i];             // save it before it is overwritten
            arr[i] = maxRight;
            maxRight = Math.max(maxRight, current);
        }
        return arr;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(replaceElements(new int[] {17, 18, 5, 4, 6, 1})));
        System.out.println(Arrays.toString(replaceElements(new int[] {400})));
        System.out.println(Arrays.toString(replaceElements(new int[] {9, 7, 3, 2})));
        System.out.println(Arrays.toString(replaceElements(new int[] {1, 2, 3, 4})));
        System.out.println(Arrays.toString(replaceElements(new int[] {5, 5, 5})));
    }
}

Running it prints:

Output
[18, 6, 6, 6, 1, -1]
[-1]
[7, 3, 2, -1]
[4, 4, 4, -1]
[5, 5, -1]

[18, 6, 6, 6, 1, -1] matches the answer row of the picture, and [400] becomes [-1] because the loop runs once and writes the starting value. In [7, 3, 2, -1], the array 9, 7, 3, 2 only gets smaller, so each position takes the number right next to it. In [4, 4, 4, -1], the 4 at the end of 1, 2, 3, 4 is the largest, so every other position gets it.

The last line, [5, 5, -1], shows that equal numbers cause no trouble: the first 5 gets the 5 after it, because the answer only has to be the largest number to the right, not one larger than 5.

The order of the last two lines in the loop matters. Updating first, with maxRight = Math.max(maxRight, arr[i]) and then arr[i] = maxRight, lets each number count itself. Example 1 then returns [18, 18, 6, 6, 6, 1], where 18, the 6 and the 1 keep their own values instead of getting 6, 1 and -1.

The original implementation, ReplaceElementsWithGreatestFromRight.java, is on GitHub.

Complexity

The method makes one pass over the array and keeps two numbers besides the index.

  • Time: O(n), for an array of n numbers, because the loop visits each position once and does a read, a write and one Math.max there.
  • Space: O(1). The answers are written into arr itself, and only maxRight and current are kept.

A running maximum from the right is also one half of Trapping Rain Water.