#1964

Find the Longest Valid Obstacle Course at Each Position

Hard
ArrayBinary SearchBinary Indexed TreeBinary SearchDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Using a binary search approach allows us to efficiently find the position of the current obstacle in a dynamic list of valid heights, leading to a faster solution. We maintain a list that tracks the minimum height for each valid length of the obstacle course.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty list 'dp' to store the minimum heights for each length of the obstacle course.
  2. 2Step 2: For each obstacle, use binary search to find the position in 'dp' where the current obstacle can replace or extend the sequence.
  3. 3Step 3: Update 'dp' accordingly and store the length of the valid course in 'ans'.
solution.py14 lines
1# Full working Python code
2import bisect
3
4def longestObstacleCourseAtEachPosition(obstacles):
5    dp = []
6    ans = []
7    for height in obstacles:
8        pos = bisect.bisect_right(dp, height)
9        if pos < len(dp):
10            dp[pos] = height
11        else:
12            dp.append(height)
13        ans.append(pos + 1)
14    return ans

Complexity note: The time complexity is O(n log n) due to the binary search operation in the 'dp' list for each obstacle, while the space complexity is O(n) for storing the 'dp' list.

  • 1The longest valid subsequence can be efficiently tracked using binary search.
  • 2Maintaining a dynamic list of minimum heights allows for quick updates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.