LeetCode: Replace Elements with Greatest Element on Right Side Solution
Backward iteration, create an array of right maxApproach
I prefer reverse array and iterate forward
Implementation (in-place operation)
1/**2 * @param {number[]} arr3 * @return {number[]}4 */5var replaceElements = function (arr) {6 arr.reverse()78 let max = -1910 for (let i = 0; i < arr.length; i++) {11 let temp = arr[i]12 arr[i] = max13 max = Math.max(max, temp)14 }1516 return arr.reverse()17}
Implementation (create new array)
1/**2 * @param {number[]} arr3 * @return {number[]}4 */5var replaceElements = function (arr) {6 const reversedArr = [...arr].reverse()78 let max = -1910 const rightMax = reversedArr.map((_, index) => {11 if (index === 0) return -11213 max = Math.max(max, reversedArr[index - 1])14 return max15 })1617 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.