Similar Problems

Similar Problems not available

Replace Elements With Greatest Element On Right Side - Leetcode Solution

Companies:

LeetCode:  Replace Elements With Greatest Element On Right Side Leetcode Solution

Difficulty: Easy

Topics: array  

The problem "Replace Elements with Greatest Element on Right Side" on LeetCode asks us to replace every element in an array with the greatest element on its right side. The last element in the array should be replaced with -1.

For example, given the array [17, 18, 5, 4, 6, 1], we should return [18, 6, 6, 6, 1, -1].

One way to approach this problem is to iterate over the array from right to left, keeping track of the maximum element seen so far. We can then replace each element with this maximum and update it if we see a larger element.

Here's the Python code that implements this approach:

def replaceElements(arr):
    max_seen = -1
    for i in range(len(arr)-1, -1, -1):
        temp = arr[i]
        arr[i] = max_seen
        max_seen = max(max_seen, temp)
    return arr

We start by initializing the maximum seen so far to -1. Then we iterate over the array from the end to the beginning using a reverse range. For each element i, we save its value in a temporary variable temp, replace it with the current maximum seen so far, and update the maximum seen if temp is greater.

Finally, we return the modified array.

This code runs in O(n) time, where n is the length of the array, since we iterate over the array once. It uses O(1) extra space, since we only need to store a few variables.

Replace Elements With Greatest Element On Right Side Solution Code

1