Hello Dev Community,
I'm posting my solution to the Leetcode problem #1299 - Replace Elements with Greatest Element on Right Side Easy
Problem description:
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.
var replaceElements = function (arr) { let res = new Array(arr.length); let max = 0; res[arr.length - 1] = -1; for (let i = arr.length - 1; i > 0; i--) { max = Math.max(arr[i], max); res[i - 1] = max; } return res; }; console.log(replaceElements([17, 18, 5, 4, 6, 1])); // [ 18, 6, 6, 6, 1, -1 ]
Method - Two pointers (i and i-1)
Complexity - Time O(n) | Space O(n)
Leetcode stats:
Runtime - beats 78.21%
Memory - beats 60.18%
I welcome your comments or suggestions!
Top comments (0)