EasyNo. 1299

Replace Elements with Greatest Element on Right Side — LeetCode 1299 Python Solution

Topics
Array
Reading time
2 min

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

PythonSolution
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 arr

Complexity

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

Related problems

Related problems
No.ProblemDifficulty
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy
0665Non-decreasing ArrayMedium
0674Longest Continuous Increasing SubsequenceEasy
0699Falling SquaresHard

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.