1299. Replace Elements With Greatest Element On Right Side - Explanation
Description
You are 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.
Example 1:
Input: arr = [2,4,5,3,1,2]
Output: [5,5,3,2,2,-1]Example 2:
Input: arr = [3,3]
Output: [3,-1]Constraints:
1 <= arr.length <= 10,0001 <= arr[i] <= 100,000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Array Traversal - Iterating through arrays both forward and backward
- Suffix Maximum Pattern - Maintaining a running maximum while traversing from right to left
1. Brute Force
Intuition
For each element at index i, we need to find the maximum value among all elements to its right. The most straightforward approach is to scan every element to the right for each position using index j. The last element has no elements to its right, so it becomes -1.
Algorithm
- Create a result array
ansof the same size as the input. - For each index
i, initializerightMaxto-1. - Iterate through all indices
jfromi + 1to the end, updatingrightMaxwith the maximum value found. - Store
rightMaxinansat positioni. - Return the
ansarray.
Time & Space Complexity
- Time complexity:
- Space complexity:
The output array is not counted towards space complexity, as the standard convention measures only auxiliary working space.
2. Suffix Max
Intuition
By traversing right to left, we can maintain a running maximum of all elements seen so far in rightMax. When we visit position i, the current running maximum represents the greatest element to the right of i. We then update rightMax to include arr[i] for the next iteration. This eliminates redundant scanning.
Algorithm
- Create a result array
ansof the same size as the input. - Initialize
rightMaxto-1(the value for the last position). - Traverse the array from right to left using index
i. - For each index
i, store the currentrightMaxinans. - Update
rightMaxto be the maximum of itself andarr[i]. - Return the
ansarray.
Time & Space Complexity
- Time complexity:
- Space complexity:
The output array is not counted towards space complexity, as the standard convention measures only auxiliary working space.
Common Pitfalls
Traversing Left to Right
Processing the array from left to right requires recalculating the maximum of all right elements for each position, resulting in O(n^2) time complexity. The optimal approach traverses right to left, maintaining a running maximum in a single pass.
Updating the Maximum Before Storing the Result
When traversing right to left, the current element's value must be stored in the result before updating rightMax. Updating rightMax first causes the current element to incorrectly include itself in its own replacement value.
Sign in to join the discussion