Replace Elements with Greatest Element on Right Side - Problem

Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.

After doing so, return the array.

Note: The rightmost element should always be replaced with -1 since there are no elements to its right.

Input & Output

Example 1 — Basic Case
$ Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
💡 Note: Element 17 → max(18,5,4,6,1) = 18, element 18 → max(5,4,6,1) = 6, element 5 → max(4,6,1) = 6, element 4 → max(6,1) = 6, element 6 → max(1) = 1, last element 1 → -1
Example 2 — Ascending Order
$ Input: arr = [1,2,3,4,5]
Output: [5,5,5,5,-1]
💡 Note: For elements 1,2,3,4: the greatest element to the right is always 5. The last element 5 becomes -1
Example 3 — Single Element
$ Input: arr = [1]
Output: [-1]
💡 Note: Only one element, so it becomes -1 as there are no elements to its right

Constraints

  • 1 ≤ arr.length ≤ 104
  • 1 ≤ arr[i] ≤ 105

Visualization

Tap to expand
Replace Elements with Greatest Element on Right SideTransform: [17, 18, 5, 4, 6, 1] → [18, 6, 6, 6, 1, -1]Input:17185461For each element, replace with maximum of all elements to its rightmax→ 18max→ 6max→ 6max→ 6max→ 1→ -1Output:186661-1Result: [18, 6, 6, 6, 1, -1]Optimal Solution: Single pass from right to left - O(n) time, O(1) space
Understanding the Visualization
1
Input Array
Original array with elements to be replaced
2
Find Greatest Right
For each element, find maximum among elements to its right
3
Final Result
Array with replacements, last element is -1
Key Takeaway
🎯 Key Insight: Process the array from right to left to efficiently track the maximum element seen so far, eliminating the need to rescan elements multiple times.
Asked in
Amazon 15 Adobe 8
99.6K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen