EasyNo. 1299
Replace Elements with Greatest Element on Right Side — LeetCode 1299 Python Solution
- Topics
- Array
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- arr = [17,18,5,4,6,1]
- Output
- [18,6,6,6,1,-1]
- Explanation
- - index 0 --> the greatest element to the right of index 0 is index 1 (18).
Python solution
from typing import List
def replaceElements(arr: List[int]) -> List[int]:
max_right = -1
for i in range(len(arr) - 1, -1, -1):
arr[i], max_right = max_right, max(max_right, arr[i])
return arrComplexity
- Time
- O(n)where n is the length of the array
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
Frequently asked questions
- How hard is LeetCode 1299. Replace Elements with Greatest Element on Right Side?
LeetCode 1299. Replace Elements with Greatest Element on Right Side is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1299. Replace Elements with Greatest Element on Right Side?
The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 1299. Replace Elements with Greatest Element on Right Side?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1299. Replace Elements with Greatest Element on Right Side cover?
LeetCode 1299. Replace Elements with Greatest Element on Right Side is tagged Array on LeetCode.