forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js
56 lines (46 loc) · 1.53 KB
/
1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 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[]}
*/
var replaceElements = (arr, max = -1) => {
for (let i = (arr.length - 1); (0 <= i); i--) {/* Time O(N) */
const num = arr[i];
arr[i] = max;
max = Math.max(max, num);
}
return arr;
};
// This is brute force with O(n^2). Just for reference's sake.
// submission link: https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/submissions/844439163/
var replaceElementsBrute = function(arr) {
for(let i = 0; i < arr.length; i++) {
arr[i] = biggestElement(i, arr);
}
arr[arr.length - 1] = -1;
return arr;
};
function biggestElement(index, arr) {
let biggest = 0;
for(let i = index + 1; i < arr.length; i++) {
biggest = Math.max(biggest, arr[i]);
}
return biggest;
}