|
| 1 | +/** |
| 2 | + * @param {number[]} A |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | +const oddEvenJumps = function (A) { |
| 6 | + // Creates an array with ONLY the indices of the sorted array |
| 7 | + let sorted = A.map((el, idx) => idx).sort((a, b) => A[a] - A[b] || a - b) |
| 8 | + // Create an array of '-1's of the same array length for odd and even jumps |
| 9 | + let oddJumps = new Array(A.length).fill(-1) |
| 10 | + let evenJumps = new Array(A.length).fill(-1) |
| 11 | + // Create an empty stack |
| 12 | + let stack = [] |
| 13 | + // Loop the the sorted array of the indices |
| 14 | + for (let i of sorted) { |
| 15 | + // Loops as long the stack is full OR if the index is greater than the the last index of the stack |
| 16 | + while (stack.length && i > stack[stack.length - 1]) { |
| 17 | + // Pops the index from the stack and place and add the 'i' index in sortedJumps |
| 18 | + oddJumps[stack.pop()] = i |
| 19 | + } |
| 20 | + // Pushes the index onto the stack |
| 21 | + stack.push(i) |
| 22 | + } |
| 23 | + // Empty the stack |
| 24 | + stack = [] |
| 25 | + // Reverses the sorted index array |
| 26 | + let reverseSorted = sorted.sort((a, b) => A[b] - A[a] || a - b) |
| 27 | + // Does the exact thing but for even jumps |
| 28 | + for (let i of reverseSorted) { |
| 29 | + while (stack.length && i > stack[stack.length - 1]) { |
| 30 | + evenJumps[stack.pop()] = i |
| 31 | + } |
| 32 | + stack.push(i) |
| 33 | + } |
| 34 | + // Starts the count at 0 |
| 35 | + let count = 1 |
| 36 | + // Creates a boolean array of false elements for even and odd ends |
| 37 | + let oddEnd = new Array(A.length).fill(false) |
| 38 | + let evenEnd = new Array(A.length).fill(false) |
| 39 | + // Switches the end of each array to true |
| 40 | + oddEnd[A.length - 1] = true |
| 41 | + evenEnd[A.length - 1] = true |
| 42 | + // Loops through the array, starting from the 2nd from the right (since we do not need to worry about the last index) |
| 43 | + for (let i = A.length - 2; i >= 0; --i) { |
| 44 | + // If even jumps does |
| 45 | + if (evenJumps[i] !== -1 && oddEnd[evenJumps[i]]) evenEnd[i] = true |
| 46 | + if (oddJumps[i] !== -1 && evenEnd[oddJumps[i]]) { |
| 47 | + oddEnd[i] = true |
| 48 | + count++ |
| 49 | + } |
| 50 | + } |
| 51 | + return count |
| 52 | +} |
0 commit comments