#1964
Hard Algorithms Find the longest valid obstacle course at each position
Array Binary Search Binary Indexed Tree
62.6% acceptance
Feb 25, 2026
1890
74
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.
Solution
Rust
Time O(n log n)
Space O(n)
impl Solution {
pub fn longest_obstacle_course_at_each_position(obstacles: Vec<i32>) -> Vec<i32> {
let n = obstacles.len();
let mut ans = vec![0i32; n];
let mut tails: Vec<i32> = Vec::new(); // longest non-decreasing subsequence tails
for i in 0..n {
let val = obstacles[i];
// Find the first element in tails that is strictly greater than val
// (since we allow equal, we use upper_bound)
let pos = tails.partition_point(|&x| x <= val);
if pos == tails.len() {
tails.push(val);
} else {
tails[pos] = val;
}
ans[i] = (pos + 1) as i32;
}
ans
}
}