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.
Input: ([1, 3, 2, 4],)
Expected Output: [3]
Explanation: Only the rightmost building (h=4) sees the ocean; every other building has a strictly taller building (height 4) somewhere to its right.
Input: ([2, 2, 2, 2],)
Expected Output: [3]
Explanation: Equal heights do not block (comparison is strict), but only the rightmost qualifies because each non-last building has an equal-height neighbor — equal is not strictly taller, yet the running-max starts at the rightmost, so indices 0-2 are not strictly greater than the max to their right (which equals 2). Only index 3 has nothing to its right.
Input: ([5],)
Expected Output: [0]
Explanation: Single building always sees the ocean.
Input: ([],)
Expected Output: []
Explanation: Empty input yields an empty result.
Input: ([1, 2, 3, 4, 5],)
Expected Output: [4]
Explanation: Strictly increasing: only the last (tallest, rightmost) building sees 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.