Imagine you're a frog hopping across lily pads in a magical pond! 🐸 You're given an integer array arr representing the heights of lily pads. Starting from any pad, you can make a series of jumps following special rules:

Odd-numbered jumps (1st, 3rd, 5th, ...): Jump to the closest pad that's at least as high as your current pad. If multiple pads have the same height, choose the leftmost one.

Even-numbered jumps (2nd, 4th, 6th, ...): Jump to the closest pad that's at most as high as your current pad. If multiple pads have the same height, choose the leftmost one.

Your goal is to reach the last lily pad (index arr.length - 1). A starting position is considered "good" if you can successfully reach the end by following these jumping rules.

Return the number of good starting positions.

Input & Output

example_1.py β€” Basic Example
$ Input: [10, 13, 12, 14, 15]
β€Ί Output: 2
πŸ’‘ Note: From index 0: 10β†’12β†’14β†’15 (oddβ†’evenβ†’odd jumps reach end). From index 2: 12β†’14β†’15 (oddβ†’even jumps reach end). From index 4: already at end. Total: 2 good starting positions.
example_2.py β€” Impossible Jumps
$ Input: [17, 13, 14, 15, 2]
β€Ί Output: 2
πŸ’‘ Note: From index 3: 15β†’2 (odd jump, but 2 cannot make any valid jumps). Only indices 3 and 4 (the end) are good starting positions.
example_3.py β€” Single Element
$ Input: [5]
β€Ί Output: 1
πŸ’‘ Note: With only one element, we're already at the end, so there's 1 good starting position.

Constraints

  • 1 ≀ arr.length ≀ 2 Γ— 104
  • 0 ≀ arr[i] < 105
  • Array values can contain duplicates
  • Must reach the last index (arr.length - 1) exactly

Visualization

Tap to expand
🐸 The Magical Frog's Journey10Start1312Good Start1415🎯 GoalOddOddEven🧠 Strategy: Monotonic Stack + DP1. Use stacks to find all possible jump destinations efficiently2. Work backwards from goal using dynamic programming3. Count starting positions that can reach the end
Understanding the Visualization
1
Map the Territory
First, the frog studies all lily pads and maps out possible jump destinations using smart algorithms
2
Work Backwards
Starting from the goal, the frog determines which pads can reach the end
3
Count Good Starts
Finally, count all starting positions where the frog can successfully complete its journey
Key Takeaway
🎯 Key Insight: The optimal approach processes jump destinations efficiently using monotonic stacks, then uses backward DP to determine reachability in O(n log n) time.
Asked in
Google 42 Amazon 28 Meta 35 Microsoft 19
28.6K Views
Medium-High Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen