LeetCode: Replace Elements with Greatest Element on Right Side Solution

Backward iteration, create an array of right max

Approach

I prefer reverse array and iterate forward

Implementation (in-place operation)

1/**
2 * @param {number[]} arr
3 * @return {number[]}
4 */
5var replaceElements = function (arr) {
6 arr.reverse()
7
8 let max = -1
9
10 for (let i = 0; i < arr.length; i++) {
11 let temp = arr[i]
12 arr[i] = max
13 max = Math.max(max, temp)
14 }
15
16 return arr.reverse()
17}

Implementation (create new array)

1/**
2 * @param {number[]} arr
3 * @return {number[]}
4 */
5var replaceElements = function (arr) {
6 const reversedArr = [...arr].reverse()
7
8 let max = -1
9
10 const rightMax = reversedArr.map((_, index) => {
11 if (index === 0) return -1
12
13 max = Math.max(max, reversedArr[index - 1])
14 return max
15 })
16
17 return rightMax.reverse()
18}

Comments

Loading comments...

Tags

leetcode

array

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Sort Array By Parity

Filter and concat

Previous Post

HoningJS

Search Posts