Odd Even Jump - Problem
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
jsuch thatarr[i] <= arr[j]andarr[j]is the smallest possible value. If there are multiple such indicesj, you can only jump to the smallest such indexj. - During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index
jsuch thatarr[i] >= arr[j]andarr[j]is the largest possible value. If there are multiple such indicesj, you can only jump to the smallest such indexj.
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.
Input & Output
Example 1 — Basic Jump Sequence
$
Input:
arr = [10,13,12,14,15]
›
Output:
2
💡 Note:
From index 0: 10→13(odd)→12(even)→14(odd)→15 reaches end. From index 2: 12→14(odd)→15 reaches end. Positions 1,3,4 cannot reach end due to jump constraints.
Example 2 — Single Element
$
Input:
arr = [2]
›
Output:
1
💡 Note:
Single element array - position 0 is already at the end, so it's a good starting index.
Example 3 — No Valid Jumps
$
Input:
arr = [5,1,3,4,2]
›
Output:
3
💡 Note:
From index 0: 5→no valid odd jump (need ≥5). From index 2: 3→4(odd) reaches end. From index 3: 4→no valid jump. Only indices 2, 3, 4 are good.
Constraints
- 1 ≤ arr.length ≤ 2 × 104
- 0 ≤ arr[i] < 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with jump constraints: odd jumps go to smallest ≥ value, even jumps to largest ≤ value
2
Jump Rules
Alternate between odd and even jumps, must jump forward
3
Count Good Starts
Count positions that can reach the last index
Key Takeaway
🎯 Key Insight: Use monotonic stacks to efficiently find next jump targets, then DP backwards to determine reachability
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code