Python 0975.py
class Solution:
def oddEvenJumps(self, arr: List[int]) -> int:
size = len(arr)
# find next higher index (for odd jumps)
high = [ None ] * size
stack = []
for a, i in sorted( ( a, i ) for i, a in enumerate(arr)):
while stack and stack[-1] < i:
high[stack.pop()] = i
stack.append(i)
# find next lower index (for even jumps)
low = [ None ] * size
stack = []
for a, i in sorted( ( -a, i ) for i, a in enumerate(arr)):
while stack and stack[-1] < i:
low[stack.pop()] = i
stack.append(i)
print(high)
print(low)
@cache
def deeper(pos, isOdd):
if pos == size - 1:
return 1 # reached end
if pos == None:
return 0 # impossible to finish
# next jump
if isOdd:
return deeper(high[pos], False)
else:
return deeper(low [pos], True)
return sum([ deeper(i, True) for i in range(size) ])
Difficulty
and has an acceptance rate of about 41% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Monotonic Stack
- Ordered Set
- Sorting
- Stack
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “odd-even jumps” problem by first pre-computing, for every position in the input array, the index that would be reached on an odd-numbered jump (the next higher value) and on an even-numbered jump (the next lower value). After these tables are built, a memoized depth-first search determines whether a path starting at each index can eventually reach the last element. The final result is the count of starting positions that succeed.
Pre-computing the odd-jump destinations
The algorithm creates an array high that stores, for each index, the smallest index to the right that holds a value greater than or equal to the current value. This is achieved by sorting the pairs (value, index) in ascending order and then using a monotonic stack to link each index to the next larger index that appears later in the sorted order.
high = [ None ] * size
stack = []
for a, i in sorted((a, i) for i, a in enumerate(arr)):
while stack and stack[-1] < i:
high[stack.pop()] = i
stack.append(i)
The sorting guarantees that values are processed from smallest to largest, while the stack ensures that indices are linked only to later positions, satisfying the “smallest index greater than the current one” requirement.
Pre-computing the even-jump destinations
Similarly, the array low holds, for each index, the smallest index to the right that contains a value less than or equal to the current value. The code sorts the pairs by the negated value, which effectively orders them from largest to smallest, and then applies the same stack technique.
low = [ None ] * size
stack = []
for a, i in sorted((-a, i) for i, a in enumerate(arr)):
while stack and stack[-1] < i:
low[stack.pop()] = i
stack.append(i)
By sorting on -a, the algorithm processes values in descending order, allowing the stack to capture the next lower destination for each position.
Recursive reachability check with memoization
A nested function deeper determines whether a jump sequence starting at a given position can reach the end of the array. The function receives the current position and a boolean flag indicating whether the next jump is odd (True) or even (False). Base cases handle reaching the last index (success) and encountering a None destination (failure). The recursive call selects the appropriate pre-computed destination based on the parity of the jump.
@cache
def deeper(pos, isOdd):
if pos == size - 1:
return 1 # reached the end
if pos == None:
return 0 # dead end
if isOdd:
return deeper(high[pos], False)
else:
return deeper(low[pos], True)
The @cache decorator (from functools) stores results for each (pos, isOdd) pair, preventing exponential recomputation and turning the recursion into a linear-time lookup after the first evaluation of each state.
Aggregating successful starting positions
The final answer is obtained by invoking deeper for every possible starting index with an odd jump (the problem definition always begins with an odd jump) and summing the boolean results, which are represented as integers 1 (success) or 0 (failure).
return sum([ deeper(i, True) for i in range(size) ])
The list comprehension iterates over all indices, and the cached deeper calls ensure that each unique state is evaluated at most once.
Edge-case handling
When the input array is empty, size becomes zero, the high and low tables are empty, and the list comprehension iterates over an empty range. The sum of an empty list yields 0, correctly indicating that no starting positions exist.
For a single-element array, the pre-computed tables contain a single None entry, but the recursive call deeper(0, True) immediately matches the pos == size - 1 base case, returning 1. Consequently, the function returns 1, reflecting that the sole element trivially reaches the end.
Duplicate values are accommodated because the sorting step includes the original index as a secondary key. When two equal values appear, the one with the smaller index is processed first, and the stack logic ensures that the next higher (or lower) jump points to the later occurrence, satisfying the “smallest index greater than the current one” rule for both odd and even jumps.
If a position has no valid odd or even jump, the corresponding entry in high or low remains None. The recursive function treats None as a dead end, returning 0 without further recursion, thereby correctly handling scenarios where a jump cannot be made.
Performance optimizations
The most notable optimization is the use of a monotonic stack combined with sorted order to compute the jump destinations in a single pass for each parity. This approach avoids nested loops that would otherwise lead to quadratic work.
Memoization via @cache eliminates repeated exploration of identical sub-problems. Since each state (pos, isOdd) is visited at most once, the recursive portion runs in linear time relative to the number of positions.
Finally, the final aggregation uses a list comprehension that leverages the cached results, ensuring that the overall runtime is dominated by the initial sorting (O(n log n)) and the linear passes for stack processing, rather than by the recursive depth-first search.
ELI5 - Simplified Explanation
Imagine you have a long row of stepping stones, each with a different magic number written on it. You are trying to reach the very last stone.
To help find your way, imagine there is a special box where you keep a list of stones. First, you look at all the stones and sort them so you can easily find the ones that have bigger numbers. You walk through the line and remember which stone comes next if you want to jump to a bigger number. You do the same thing again, but this time you look for stones with smaller numbers, keeping track of where those jumps would land you.
Once you have these two maps of all the possible paths, you start a little game of pretend. You pick a starting stone and take turns jumping. On the first jump, you must look at your map and jump to a stone that is either the same size or bigger. On the next jump, you must look at your other map and jump to a stone that is either the same size or smaller. You keep doing this back and forth, like a dance, to see if you can reach the end.
If you hit a point where there is nowhere to jump, the path is a dead end. If you successfully land on the final stone, that starting spot counts as a win. By checking every single stone to see if it leads to an adventure at the finish line, you find out how many different ways there are to complete the journey.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | ||||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 3115: Maximum Prime Difference
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality