1231. Replace Elements with Greatest Element on Right Side
My accepted Python solution to LeetCode problem 1231, Replace Elements with Greatest Element on Right Side, running in 55ms.
- Difficulty: Easy
- Python
- Runtime 55ms
- Memory 18.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 55ms, memory 18.6MB, accepted 2025-12-29.
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
# Iterate from right to left, tracking max seen so far
# Time: O(n), Space: O(1) - modify in place
max_right = -1
for i in range(len(arr) - 1, -1, -1):
new_val = max_right
max_right = max(max_right, arr[i])
arr[i] = new_val
return arr