#975
Hard Algorithms Odd even jump
Array Dynamic Programming Stack Sorting Monotonic Stack Ordered Set
41.1% acceptance
Feb 25, 2026
2111
532
You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.
You may jump forward from index i to index j (with i < j) in the following way:
During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.
During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.
It may be the case that for some index i, there are no legal jumps.
A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once).
Return the number of good starting indices.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn odd_even_jumps(arr: Vec<i32>) -> i32 {
let n = arr.len();
if n == 1 { return 1; }
let make_next = |order: Vec<usize>| -> Vec<usize> {
let mut result = vec![n; n];
let mut stack: Vec<usize> = Vec::new();
for j in order {
while stack.last().map_or(false, |&s| s < j) {
result[stack.pop().unwrap()] = j;
}
stack.push(j);
}
result
};
let mut idx_asc: Vec<usize> = (0..n).collect();
idx_asc.sort_by_key(|&i| (arr[i], i as i32));
let odd_next = make_next(idx_asc);
let mut idx_desc: Vec<usize> = (0..n).collect();
idx_desc.sort_by_key(|&i| (-arr[i], i as i32));
let even_next = make_next(idx_desc);
let mut odd_can = vec![false; n];
let mut even_can = vec![false; n];
odd_can[n-1] = true; even_can[n-1] = true;
for i in (0..n-1).rev() {
if odd_next[i] < n { odd_can[i] = even_can[odd_next[i]]; }
if even_next[i] < n { even_can[i] = odd_can[even_next[i]]; }
}
odd_can.iter().filter(|&&x| x).count() as i32
}
}