Problem Description
Given an array arr, replace every element with the greatest element among the elements to its right and replace the last element with -1. Return the modified array.
Key Insights
- The last element always becomes -1 since there are no elements to its right.
- By iterating the array from right to left, you can maintain the maximum element seen so far.
- This reverse traversal allows constant time updates and avoids the need for nested loops.
Space and Time Complexity
Time Complexity: O(n) - where n is the number of elements in the array (single pass from right to left). Space Complexity: O(1) - in-place updates with only a few extra variables.
Solution
The strategy is to start from the end of the array and move leftwards. Track the maximum value observed so far (initialized as -1). For each element, replace it with the current maximum, then update the maximum if the current element is greater. This approach guarantees that each element is replaced by the greatest element to its right in a single traversal.