Skip to content

Commit a3f47de

Browse files
Replace Elements w. Greatest Element on Right Side
Difficulty: Easy 15 / 15 test cases passed. Runtime: 112 ms Memory Usage: 14.8 MB
1 parent 83cbe86 commit a3f47de

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
Given an array arr, replace every element in that array with the greatest
3+
element among the elements to its right, and replace the last element with -1.
4+
After doing so, return the array.
5+
6+
Example:
7+
Input: arr = [17,18,5,4,6,1]
8+
Output: [18,6,6,6,1,-1]
9+
"""
10+
#Difficulty: Easy
11+
#15 / 15 test cases passed.
12+
#Runtime: 112 ms
13+
#Memory Usage: 14.8 MB
14+
15+
#Runtime: 112 ms, faster than 99.50% of Python3 online submissions for Replace Elements with Greatest Element on Right Side.
16+
#Memory Usage: 14.8 MB, less than 100.00% of Python3 online submissions for Replace Elements with Greatest Element on Right Side.
17+
18+
class Solution:
19+
def replaceElements(self, arr: List[int]) -> List[int]:
20+
i = len(arr)-1
21+
greater = -1
22+
while i >= 0:
23+
if arr[i] > greater:
24+
arr[i], greater = greater, arr[i]
25+
else:
26+
arr[i] = greater
27+
i -= 1
28+
return arr

0 commit comments

Comments
 (0)