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 on Right INPUT Original Array arr[] 17 18 5 4 6 1 i=0 i=1 i=2 i=3 i=4 i=5 Task: For each element, find max of elements to its right Example: arr[0] = 17 Right elements: 18,5,4,6,1 Max = 18 arr = [17,18,5,4,6,1] n = 6 elements ALGORITHM STEPS 1 Initialize maxRight = -1 2 Traverse Right-to-Left i = n-1 down to 0 3 Store & Update temp = arr[i] arr[i] = maxRight 4 Update maxRight maxRight = max(maxRight, temp) Trace (right to left): i=5: arr[5]=(-1), max=1 i=4: arr[4]=(1), max=6 i=3: arr[3]=(6), max=6 i=2: arr[2]=(6), max=6 i=1: arr[1]=(6), max=18 i=0: arr[0]=(18), max=18 FINAL RESULT Modified Array arr[] 18 6 6 6 1 -1 Element Mapping: 17 --> 18 (max of right) 18 --> 6 (max of 5,4,6,1) 5,4 --> 6 (max of right) 1 --> -1 (last element) Output: [18, 6, 6, 6, 1, -1] Complexity: Time: O(n) - single pass Space: O(1) - in-place Status: OK Key Insight: By traversing from right to left, we can track the maximum element seen so far in a single variable. Each element gets replaced with the current max, then we update max if the original value was larger. This eliminates the need for nested loops, reducing time complexity from O(n^2) to O(n). TutorialsPoint - Replace Elements with Greatest Element on Right Side | Optimized Single Right-to-Left Pass
Asked in
Amazon 15 Adobe 8
99.7K 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