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. The rightmost element should be replaced with -1 since there are no elements to its right. Return the modified array.
This is a classic right-to-left DP problem. Start from the end of the array, tracking the maximum value seen so far. For each position from right to left, store the current max in the result, then update the max with the current element if it is larger.
The DP recurrence is: for i from n-1 down to 0, result[i] = maxSoFar, then update maxSoFar = max(maxSoFar, arr[i]). This processes each element once in O(n) time with O(1) extra space.
Edge cases include a single element (return [-1]), an empty array (return []), and all elements equal (all become the same value).
The right-to-left DP pattern is used when each element's value depends on future elements. By iterating backwards, we naturally encounter the dependent elements before the dependent ones. This is similar to how DP solves problems by computing subproblems in dependency order.
This right-to-left DP pattern is widely applicable in computing next greater elements, stock span, and any scenario where future values influence current decisions. The single scalar state variable captures all necessary future information efficiently.
Example Input & Output
Descending.
Empty.
Single element.
18 > 17, 6 > rest, 1 -> -1.
Ascending, max is last.
Algorithm Flow

Solution Approach
Iterate right-to-left, tracking max seen. Replace each element with current max, then update max.
Time O(n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] arr) {
int m=-1;
for (int i=arr.length-1;i>=0;i--) {
int c=arr[i];
arr[i]=m;
if (c>m) m=c;
}
return arr;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
