-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0975-odd-even-jump.js
More file actions
85 lines (73 loc) · 2.38 KB
/
0975-odd-even-jump.js
File metadata and controls
85 lines (73 loc) · 2.38 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Odd Even Jump
* Time Complexity: O(N log N)
* Space Complexity: O(N)
*/
var oddEvenJumps = function (arr) {
const arraySize = arr.length;
const canReachOddPath = new Array(arraySize).fill(false);
const canReachEvenPath = new Array(arraySize).fill(false);
canReachOddPath[arraySize - 1] = true;
canReachEvenPath[arraySize - 1] = true;
let goodStartCount = 1;
const nextJumpOddIndexMap = new Array(arraySize);
const nextJumpEvenIndexMap = new Array(arraySize);
const originalIndicesForOdd = Array.from(
{ length: arraySize },
(_, idx) => idx,
);
originalIndicesForOdd.sort((firstIdx, secondIdx) => {
if (arr[firstIdx] !== arr[secondIdx]) {
return arr[firstIdx] - arr[secondIdx];
}
return firstIdx - secondIdx;
});
const monotonicStackOdd = [];
for (const currentValIdx of originalIndicesForOdd) {
while (
monotonicStackOdd.length > 0 &&
monotonicStackOdd[monotonicStackOdd.length - 1] < currentValIdx
) {
nextJumpOddIndexMap[monotonicStackOdd.pop()] = currentValIdx;
}
monotonicStackOdd.push(currentValIdx);
}
const originalIndicesForEven = Array.from(
{ length: arraySize },
(_, idx) => idx,
);
originalIndicesForEven.sort((firstIdxElement, secondIdxElement) => {
if (arr[firstIdxElement] !== arr[secondIdxElement]) {
return arr[secondIdxElement] - arr[firstIdxElement];
}
return firstIdxElement - secondIdxElement;
});
const monotonicStackEven = [];
for (const currentElementIndex of originalIndicesForEven) {
while (
monotonicStackEven.length > 0 &&
monotonicStackEven[monotonicStackEven.length - 1] < currentElementIndex
) {
nextJumpEvenIndexMap[monotonicStackEven.pop()] = currentElementIndex;
}
monotonicStackEven.push(currentElementIndex);
}
for (
let currentPosition = arraySize - 2;
currentPosition >= 0;
currentPosition--
) {
const nextOddJumpTarget = nextJumpOddIndexMap[currentPosition];
const nextEvenJumpTarget = nextJumpEvenIndexMap[currentPosition];
if (nextOddJumpTarget !== undefined) {
canReachOddPath[currentPosition] = canReachEvenPath[nextOddJumpTarget];
if (canReachOddPath[currentPosition]) {
goodStartCount++;
}
}
if (nextEvenJumpTarget !== undefined) {
canReachEvenPath[currentPosition] = canReachOddPath[nextEvenJumpTarget];
}
}
return goodStartCount;
};