Buildings With an Ocean View

Asked atMeta
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

There are n buildings in a row. You are given an integer array heights of size n, where** **heights[i] represents the height of the i-th building. A building has an ocean view if all the buildings to its right are shorter. Return an array of indices of buildings that have an ocean view, sorted in increasing order.

Input: heights = [4,2,3,1] Output: [0,2,3] Explanation: Building 1 (0-indexed) does not have an ocean view because building 2 is taller.

Input: heights = [4,3,2,1] Output: [0,1,2,3] Explanation: All the buildings have an ocean view.

Input: heights = [1,3,2,4]

  • 1 <= heights.length <= 105
  • 1 <= heights[i] <= 109

cpp

class Solution {
public:
    vector<int> findBuildings(vector<int>& heights) {
        //Your Code Goes Here
    }
};

java

class Solution {
    public List<Integer> findBuildings(int[] heights) {
       
    }
}

python

class Solution:
    def findBuildings(self, heights):

javascript

class Solution {
    findBuildings(heights) {
    
    }
}

csharp

public class Solution{
    public IList<int> FindBuildings(int[] heights){
        //your code goes here
    }
}

go

func findBuildings(heights []int) []int {

}
Stuck? Show a way to structure it+
  1. 01Scan buildings from right to left.
  2. 02Track the largest height seen to the right.
  3. 03Keep a building if it exceeds that maximum.
  4. 04Reverse the collected indices.

Reference answer

Then expect these follow-ups

  • How would left-ocean view change the scan?

    Tests: symmetry

  • Can the answer be streamed in increasing index order?

    Tests: output constraints

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question