Odd Even Jump (LeetCode 975): Solution and Explanation
From a starting index you alternate two kinds of forward jumps. Odd jumps go to the smallest value at or above the current one, even jumps go to the largest value at or below it, and ties go to the smallest index. Count the starting indices from which you can reach the last index.
Watch it run step by step
Try your own input and write the code →Intuition
There are two separate problems hiding here. The first is computing, for every index, where an odd jump and an even jump would land. The second is deciding which starts succeed given those targets. The second part is a simple DP once the first is done: define odd[i] as whether starting at i with an odd jump reaches the end, and even[i] the same for an even jump. Then odd[i] = even[oddNext[i]] and even[i] = odd[evenNext[i]], because jumps alternate. The last index is trivially good for both, so we fill from right to left and count the true values in odd, since every journey starts with an odd jump.
The hard part is the jump targets. Scanning right from each index is O(n²). A sorted map built from the right gives O(n log n) with ceiling and floor lookups, but Python has no built-in tree map. The reference solution uses a neat alternative. Sort the indices by value (ties by index). For an odd jump from i, the target is the first index after i in that sorted order that is also to the right of i in the array. That is a classic next greater element question, except the order we walk is the sorted order and the comparison is on positions.
So walk the indices in sorted order with a stack. Whenever the current index is larger than the index on top of the stack, it is the next position to the right among values at least as big, so it becomes that index's odd target. For even jumps, sort by value descending (ties by index ascending) and run the same routine. Both passes are linear after sorting.
Approach: Sorted indices with monotonic stack, then DP
- Sort indices by
(arr[i], i)and pass them tobuildNext, which yieldsodd_next, the landing index of an odd jump from each position. - Sort indices by
(-arr[i], i)and callbuildNextagain to geteven_next. - In
buildNext, walk the sorted indices with a stack. While the top of the stack is a smaller index than the current one, pop it and record the current index as its target, then push the current index. - Set
odd[n - 1] = even[n - 1] = True. - For
ifrom n - 2 down to 0, setodd[i] = even[odd_next[i]]andeven[i] = odd[even_next[i]]when those targets exist. - Return the number of indices where
odd[i]is true.
Step-by-step example
arr = [10, 13, 12, 14, 15]
- Ascending order of indices is [0, 2, 1, 3, 4]. The stack pass gives
odd_next = [2, 3, 3, 4, None], so from 10 the odd jump lands on 12, from 13 or 12 it lands on 14, and from 14 it lands on 15. - Descending order is [4, 3, 1, 2, 0], which gives
even_next = [None, 2, None, None, None]. Only 13 has a smaller or equal value to its right, namely 12. - Index 4 is the end, so
odd[4] = even[4] = True. Index 3:odd[3] = even[4] = True, and it has no even jump. - Index 2:
odd[2] = even[3] = False. Index 1:odd[1] = even[3] = False, andeven[1] = odd[2] = False. Index 0:odd[0] = even[2] = False. oddis [False, False, False, True, True], so the answer is 2.
Code: Python, Java, C++
1class Solution:
2 def oddEvenJumps(self, arr: List[int]) -> int:
3 n = len(arr)
4 # odd[i] = True if can reach end starting at i with odd jump
5 # even[i] = True if can reach end starting at i with even jump
6 odd = [False] * n
7 even = [False] * n
8 odd[n - 1] = even[n - 1] = True
9
10 # Build next greater/smaller element indices using sorted indices
11 sorted_idx = sorted(range(n), key=lambda i: (arr[i], i))
12 odd_next = self.buildNext(sorted_idx)
13
14 sorted_idx = sorted(range(n), key=lambda i: (-arr[i], i))
15 even_next = self.buildNext(sorted_idx)
16
17 for i in range(n - 2, -1, -1):
18 if odd_next[i] is not None:
19 odd[i] = even[odd_next[i]]
20 if even_next[i] is not None:
21 even[i] = odd[even_next[i]]
22
23 return sum(odd)
24
25 def buildNext(self, sorted_idx):
26 n = len(sorted_idx)
27 next_arr = [None] * n
28 stack = []
29 for i in sorted_idx:
30 while stack and stack[-1] < i:
31 next_arr[stack.pop()] = i
32 stack.append(i)
33 return next_arr1class Solution {
2 public int oddEvenJumps(int[] arr) {
3 int n = arr.length;
4 boolean[] odd = new boolean[n];
5 boolean[] even = new boolean[n];
6 odd[n - 1] = even[n - 1] = true;
7
8 TreeMap<Integer, Integer> map = new TreeMap<>();
9 map.put(arr[n - 1], n - 1);
10
11 for (int i = n - 2; i >= 0; i--) {
12 Integer oddKey = map.ceilingKey(arr[i]);
13 Integer evenKey = map.floorKey(arr[i]);
14
15 if (oddKey != null) odd[i] = even[map.get(oddKey)];
16 if (evenKey != null) even[i] = odd[map.get(evenKey)];
17
18 map.put(arr[i], i);
19 }
20
21 int count = 0;
22 for (boolean b : odd) if (b) count++;
23 return count;
24 }
25}1class Solution {
2public:
3 int oddEvenJumps(vector<int>& arr) {
4 int n = arr.size();
5 vector<bool> odd(n, false), even(n, false);
6 odd[n - 1] = even[n - 1] = true;
7
8 map<int, int> mp;
9 mp[arr[n - 1]] = n - 1;
10
11 for (int i = n - 2; i >= 0; i--) {
12 auto oddIt = mp.lower_bound(arr[i]);
13 auto evenIt = mp.upper_bound(arr[i]);
14
15 if (oddIt != mp.end()) odd[i] = even[oddIt->second];
16 if (evenIt != mp.begin()) {
17 evenIt--;
18 even[i] = odd[evenIt->second];
19 }
20
21 mp[arr[i]] = i;
22 }
23
24 return count(odd.begin(), odd.end(), true);
25 }
26};Time and space complexity
O(n log n)
The two sorts dominate. Each stack pass pushes and pops every index once, and the DP is a single linear sweep.
O(n)
The sorted index lists, the two next arrays, the stack and the two boolean arrays are all linear in n.
Other approaches
Tree map built from the right (time O(n log n), space O(n))
Scan from right to left while inserting values into a balanced tree map. For each index, ceiling(arr[i]) gives the odd target and floor(arr[i]) gives the even target, and the map keeps the most recent (smallest) index for each value. It is the most direct solution in Java or C++.
Common mistakes
- Sorting even jumps by
(-arr[i], -i). Ties must still prefer the smallest index, so the key is(-arr[i], i). - Counting starts where
even[i]is true. The first jump is always odd, so onlyoddcounts. - Using a strict comparison on values, which misses jumps to an equal value. Odd jumps allow greater or equal and even jumps allow less or equal.
- Forgetting that the last index counts as a good start on its own.
Frequently asked questions
Why does a monotonic stack over sorted indices find the next jump?
In sorted order, the indices after i are exactly the candidates with acceptable values, ordered from best to worst. The first one that is also to the right of i in the array is the jump target, which is a next greater index query that a stack answers in linear time.
Why fill the DP from right to left?
Every jump moves forward, so the answer for index i depends only on indices to its right. Processing from the end guarantees those values are ready.
Can Odd Even Jump be solved in O(n)?
Not in general, because finding the next greater or equal value to the right for arbitrary numbers needs ordering information, which costs O(n log n) by sorting or by a tree map.