You are given an array arr
. For each index i
in the array, you need to replace the element arr[i]
with the greatest element among the elements to its right, and replace the last element with -1
.
For example:
[17,18,5,4,6,1]
[18,6,6,6,1,-1]
arr
is between 1 and 10^4.-1
.def replaceElements(arr):
n = len(arr)
if n == 0:
return arr
# Initialize max_so_far with -1 since the last element should be replaced by -1
max_so_far = -1
# Iterate from the end to the beginning
for i in range(n - 1, -1, -1):
# Store the current element before we overwrite it
current = arr[i]
# Replace the current element with max_so_far
arr[i] = max_so_far
# Update max_so_far if current element is higher than max_so_far
if current > max_so_far:
max_so_far = current
return arr
# Example usage
print(replaceElements([17,18,5,4,6,1])) # Output: [18,6,6,6,1,-1]
n
is the length of the array.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?