Number of Visible People in a Queue

HardStackmonotonic stack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

n people stand in a line from left to right, and heights[i] is the height of person i. All heights are **distinct**. Person i can see person j (with i < j) if everyone standing strictly between them is shorter than **both** of them, i.e. min(heights[i], heights[j]) > max(heights[i+1], ..., heights[j-1]). Adjacent people can always see each other. Return an array answer of length n where answer[i] is the number of people to the right that person i can see. Target O(n) time.

Examples

Input: heights = [10,6,8,5,11,9]
Output: [3,1,2,1,1,0]
Person 0 (10) sees 6, 8, and 11; the 5 is hidden behind 8 and the 9 behind 11.
Input: heights = [5,1,2,3,10]
Output: [4,1,1,1,0]
Person 0 sees everyone because each next person is taller than all before them.

Constraints

  • n == heights.length
  • 1 <= n <= 10^5
  • 1 <= heights[i] <= 10^5
  • All values in heights are unique

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More monotonic stack problems