#975
Odd Even Jump
HardArrayDynamic ProgrammingStackSortingMonotonic StackOrdered SetDynamic ProgrammingMonotonic StackSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses dynamic programming and a monotonic stack to efficiently determine which indices can reach the end of the array. This reduces the time complexity significantly by avoiding redundant checks.
⚙️
Algorithm
4 steps- 1Step 1: Create two boolean arrays, oddJump and evenJump, initialized to false.
- 2Step 2: Set the last index of both arrays to true, as we can reach the end from itself.
- 3Step 3: Traverse the array backwards, using a monotonic stack to find valid jumps for odd and even jumps.
- 4Step 4: Update the oddJump and evenJump arrays based on the conditions for valid jumps.
solution.py25 lines
1def oddEvenJumps(arr):
2 n = len(arr)
3 if n == 1: return 1
4 oddJump = [False] * n
5 evenJump = [False] * n
6 oddJump[-1] = evenJump[-1] = True
7 oddCount = 0
8
9 from sortedcontainers import SortedList
10 sortedList = SortedList()
11 sortedList.add((arr[-1], n - 1))
12
13 for i in range(n - 2, -1, -1):
14 while sortedList and sortedList[0][0] < arr[i]:
15 sortedList.pop(0)
16 if sortedList:
17 oddJump[i] = evenJump[sortedList[0][1]]
18
19 while sortedList and sortedList[-1][0] <= arr[i]:
20 sortedList.pop()
21 if sortedList:
22 evenJump[i] = oddJump[sortedList[-1][1]]
23 sortedList.add((arr[i], i))
24
25 return sum(oddJump)ℹ
Complexity note: The time complexity is O(n log n) because we use a sorted data structure to maintain the indices for the jumps, allowing us to efficiently find the next valid jump.
- 1Understanding the jump conditions is crucial.
- 2Using data structures like stacks can optimize the search for valid jumps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.