Odd Even Jump — LeetCode 975 Python Solution

HardStackArrayDynamic ProgrammingOrdered SetSortingMonotonic Stack
Problem
#975
Pattern
Stack
Reading time
4 min

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

MeasureComplexity
TimeO(n \times \log n)
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview