Skip to content

Commit

Permalink
Update 1299-Replace-Elements-With-Greatest-Element-On-Right-Side.js
Browse files Browse the repository at this point in the history
  • Loading branch information
aakhtar3 authored Oct 19, 2022
1 parent 851603d commit 7a2a1dc
Showing 1 changed file with 28 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,35 @@
/**
* Reverse - Space O(1)
* Time O(N) | Space O(N)
* https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/
* @param {number[]} arr
* @return {number[]}
*/
var replaceElements = (arr, max = -1, ans = [ -1 ]) => {
arr = arr.reverse(); /* Time O(N) */

for (let i = 0; (i < (arr.length - 1)); i++) {/* Time O(N) */
max = Math.max(max, arr[i]);
ans[(i + 1)] = max; /* Space O(N) */
}

return ans.reverse(); /* Time O(N) */
};

/**
* Backward - In-Place
* Time O(N) | Space O(1)
*
* https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/
* @param {number[]} arr
* @return {number[]}
*/
function replaceElements(arr) {
let max = -1;
var replaceElements = (arr, max = -1) => {
for (let i = (arr.length - 1); (0 <= i); i--) {/* Time O(N) */
const num = arr[i];

for (let i = arr.length - 1; i >= 0; i--) {
const temp = arr[i];
arr[i] = max;
max = Math.max(max, temp);
}
arr[i] = max;
max = Math.max(max, num);
}

return arr;
};
return arr;
};

0 comments on commit 7a2a1dc

Please sign in to comment.