Find the Longest Valid Obstacle Course at Each Position - Problem

You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle.

For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:

  • You choose any number of obstacles between 0 and i inclusive.
  • You must include the ith obstacle in the course.
  • You must put the chosen obstacles in the same order as they appear in obstacles.
  • Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it.

Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.

Input & Output

Example 1 — Basic Sequence
$ Input: obstacles = [1,2,3,2]
Output: [1,2,3,2]
💡 Note: At index 0: longest course is [1] with length 1. At index 1: longest course is [1,2] with length 2. At index 2: longest course is [1,2,3] with length 3. At index 3: longest course is [1,2] with length 2 (can't include 3 since 3 > 2).
Example 2 — Decreasing Sequence
$ Input: obstacles = [2,2,1]
Output: [1,2,1]
💡 Note: At index 0: longest course is [2] with length 1. At index 1: longest course is [2,2] with length 2. At index 2: longest course is [1] with length 1 (can't use previous obstacles since they're taller).
Example 3 — All Same Heights
$ Input: obstacles = [3,1,5,6,4,2]
Output: [1,1,2,3,2,2]
💡 Note: At each position, we find the longest non-decreasing subsequence ending at that position. For example, at index 3 (value 6), the longest course is [1,5,6] with length 3.

Constraints

  • 1 ≤ obstacles.length ≤ 105
  • 1 ≤ obstacles[i] ≤ 107

Visualization

Tap to expand
Longest Valid Obstacle Course at Each Position1232HeightHeightHeightHeight1232LengthLengthLengthLengthGreen lines show valid courses, dashed red shows invalid (3 > 2)
Understanding the Visualization
1
Input
Array of obstacle heights: [1,2,3,2]
2
Process
For each position, find longest valid course ending there
3
Output
Array of lengths: [1,2,3,2]
Key Takeaway
🎯 Key Insight: This is a variation of Longest Increasing Subsequence where we find the longest non-decreasing sequence ending at each position
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.0K Views
Medium Frequency
~25 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