Find buildings with rightward view
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This interview question evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer for Find buildings with rightward view states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 1 <= heights.length <= 10^5 (the harness also accepts an empty array, returning [])
- 1 <= heights[i] <= 10^9
- Output indices must be in strictly increasing order
Examples
Input: ([4, 2, 3, 1],)
Expected Output: [0, 2, 3]
Explanation: Index 3 (rightmost) sees ocean. Index 2 (h=3) only has h=1 to its right. Index 1 (h=2) is blocked by index 2 (h=3). Index 0 (h=4) is taller than all to its right.
Input: ([4, 3, 2, 1],)
Expected Output: [0, 1, 2, 3]
Explanation: Strictly decreasing heights: every building is taller than all buildings to its right, so all see the ocean.
Hints
- Scan from right to left. A building sees the ocean iff it is taller than every building already seen to its right.
- Track the maximum height encountered so far while scanning right-to-left. A strictly taller building qualifies and updates that maximum.
- Because you scan right-to-left, collected indices come out in decreasing order — reverse them (or prepend) to return increasing order.
- For a LEFTWARD view, scan left-to-right with the same running-max logic. For NON-STRICT comparisons (>= blocks), change the comparison from `>` to `>` against the max but treat equal heights as blocking by comparing with `>=` from the blocker's perspective — i.e. keep a building only when it is strictly greater than the running max even under non-strict rules the running-max approach still applies, just adjust whether equal heights block.