#1299
Replace Elements with Greatest Element on Right Side
EasyArrayArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking all elements to the right for each element, we can keep track of the maximum element seen so far while iterating from the end of the array. This reduces the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to keep track of the maximum element seen so far, starting with -1.
- 2Step 2: Iterate through the array from the last element to the first element.
- 3Step 3: For each element, store the current maximum in the result array, then update the maximum with the current element.
solution.py8 lines
1def replaceElements(arr):
2 n = len(arr)
3 result = [-1] * n
4 max_right = -1
5 for i in range(n - 1, -1, -1):
6 result[i] = max_right
7 max_right = max(max_right, arr[i])
8 return resultℹ
Complexity note: We only make a single pass through the array, leading to O(n) time complexity. The space complexity is O(n) due to the result array.
- 1Iterating from the end allows us to keep track of the maximum efficiently.
- 2Using a single variable to store the maximum reduces the need for nested loops.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.