Replace elements with greatest element on right side
[Leetcode][Arrays]
Problem Statement
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. URL
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:
1 <= arr.length <= 10^4
1 <= arr[i] <= 10^5
#collapse-hide
from typing import List
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
for i in range(len(arr)-1):
arr[i] = returnMax(arr[i+1:])
arr[len(arr)-1] = -1
return arr
def returnMax(arr):
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
return arr[len(arr)-1]
sol = Solution()
sol.replaceElements([17,18,5,4,6,1])
testCastList[:10]
len(testCastList)
Worst case performance in Time: $O(n^{2})$
#collapse-hide
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
arrLen = len(arr)
maxSoFar = arr[arrLen-1]
arr[arrLen-1] = -1
for i in range(arrLen-2, -1, -1):
temp = arr[i]
arr[i] = maxSoFar
if temp > maxSoFar:
maxSoFar = temp
return arr
sol = Solution()
sol.replaceElements([17,18,5,4,6,1])
Worst case performance in Time: $O(n)$