Odd Even Jump — LeetCode 975 Python Solution
HardStackArrayDynamic ProgrammingOrdered SetSortingMonotonic Stack
- Problem
- #975
- Pattern
- Stack
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given an integer array arr. From some starting index, you can make a series of jumps.
Example
- Input
- arr = [10,13,12,14,15]
- Output
- 2
- Explanation
- From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.
Python solution
Python
class Solution:
def oddEvenJumps(self, arr: List[int]) -> int:
@cache
def dfs(i: int, k: int) -> bool:
if i == n - 1:
return True
if g[i][k] == -1:
return False
return dfs(g[i][k], k ^ 1)
n = len(arr)
g = [[0] * 2 for _ in range(n)]
sd = SortedDict()
for i in range(n - 1, -1, -1):
j = sd.bisect_left(arr[i])
g[i][1] = sd.values()[j] if j < len(sd) else -1
j = sd.bisect_right(arr[i]) - 1
g[i][0] = sd.values()[j] if j >= 0 else -1
sd[arr[i]] = i
return sum(dfs(i, 1) for i in range(n))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 975. Odd Even Jump is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
LeetCode 85Maximal RectangleHardLeetCode 907Sum of Subarray MinimumsMediumLeetCode 1130Minimum Cost Tree From Leaf ValuesMediumLeetCode 1504Count Submatrices With All OnesMediumLeetCode 1526Minimum Number of Increments on Subarrays to Form a Target ArrayHardLeetCode 2617Minimum Number of Visited Cells in a GridHard
Frequently asked questions
- How hard is LeetCode 975. Odd Even Jump?
- LeetCode 975. Odd Even Jump is rated Hard on LeetCode.
- What is the time complexity of LeetCode 975. Odd Even Jump?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 975. Odd Even Jump?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 975. Odd Even Jump cover?
- LeetCode 975. Odd Even Jump is tagged Stack, Array, Dynamic Programming, Ordered Set, Sorting and Monotonic Stack on LeetCode.