LeetCode 1964, Hard. Topics: Array, Binary Search, Binary Indexed Tree, Longest Increasing Subsequence. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 22 parametrized pytest cases, and a playground notebook:
Problem
You want to build some obstacle courses. You are given a <strong>0-indexed</strong> integer array <code>obstacles</code> of length <code>n</code>, where <code>obstacles[i]</code> describes the height of the <code>i<sup>th</sup></code> obstacle.
For every index <code>i</code> between <code>0</code> and <code>n - 1</code> (<strong>inclusive</strong>), find the length of the <strong>longest obstacle course</strong> in <code>obstacles</code> such that:
<ul>
<li>You choose any number of obstacles between <code>0</code> and <code>i</code> <strong>inclusive</strong>.</li>
<li>You must include the <code>i<sup>th</sup></code> obstacle in the course.</li>
<li>You must put the chosen obstacles in the <strong>same order</strong> as they appear in <code>obstacles</code>.</li>
<li>Every obstacle (except the first) is <strong>taller</strong> than or the <strong>same height</strong> as the obstacle immediately before it.</li>
</ul>
Return <em>an array</em> <code>ans</code> <em>of length</em> <code>n</code>, <em>where</em> <code>ans[i]</code> <em>is the length of the <strong>longest obstacle course</strong> for index</em> <code>i</code><em> as described above</em>.
Examples
Constraints
- n == obstacles.length
- 1 <= n <= 10^5
- 1 <= obstacles[i] <= 10^7
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026