Replace Elements with Greatest Element on Right Side - Problem
Given an array arr, your task is to transform it by replacing every element with the greatest element among all the elements to its right side. The rightmost element has no elements to its right, so it should be replaced with -1.
For example, if you have the array [17, 18, 5, 4, 6, 1], you need to:
- Replace
17with the maximum of[18, 5, 4, 6, 1]which is18 - Replace
18with the maximum of[5, 4, 6, 1]which is6 - Replace
5with the maximum of[4, 6, 1]which is6 - Continue this process...
- Replace the last element
1with-1
The goal is to return the modified array after all replacements are complete.
Input & Output
example_1.py โ Basic Array
$
Input:
arr = [17,18,5,4,6,1]
โบ
Output:
[18,6,6,6,1,-1]
๐ก Note:
For index 0: max of [18,5,4,6,1] is 18. For index 1: max of [5,4,6,1] is 6. For index 2: max of [4,6,1] is 6. For index 3: max of [6,1] is 6. For index 4: max of [1] is 1. Index 5 becomes -1.
example_2.py โ Single Element
$
Input:
arr = [400]
โบ
Output:
[-1]
๐ก Note:
There's only one element, so it has no elements to its right. According to the problem, it should be replaced with -1.
example_3.py โ Decreasing Array
$
Input:
arr = [9,7,5,3,1]
โบ
Output:
[7,5,3,1,-1]
๐ก Note:
In a decreasing array, each element's replacement is simply the next element to its right, except the last which becomes -1.
Constraints
- 1 โค arr.length โค 104
- 1 โค arr[i] โค 105
- Follow-up: Could you solve it without using extra space?
Visualization
Tap to expand
Understanding the Visualization
1
Start at the End
Begin from the last element. Since it has no elements to its right, replace it with -1. Track the maximum seen so far.
2
Move Backwards
For each element moving right to left, replace it with the current maximum, then update the maximum with the current element's original value.
3
Complete the Process
Continue until you reach the beginning. Each element gets replaced with the maximum of all elements that were originally to its right.
Key Takeaway
๐ฏ Key Insight: Working backwards allows us to incrementally build the maximum of right-side elements, achieving optimal O(n) time complexity with constant space.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code