Count Visible People to the Left
Problem statement
There are n people standing in a line, indexed from left to right. Every person faces left, and heights[i] is person i's height. All heights are distinct.
Person i can see person j to the left, where j < i, exactly when no person k between them is taller than both endpoints. In other words, there must be no k with j < k < i and heights[k] > max(heights[i], heights[j]).
Examples
Example 1
heights = [1,10,6,7,9,8,2,4,3,5]return = [0,1,1,2,3,2,3,4,4,6]The warm-up asks only about the last person, whose height is 5. Looking left, that person can see heights 3, 4, 2, 8, 9, and 10, so the last count is 6. Height 9 blocks heights 7 and 6, while height 10 blocks height 1. Applying the same rule to every position gives the returned array.
Unlock this recently reported problem
FastPrep Pro gives you full access to interview problems reported within the last week.
- Full problem statement and constraints
- 2 more worked examples, explained
- Guided hints and editorial
- Run your code on real test cases
$99 billed yearly — or $19 month-to-month. Cancel anytime.