Buildings With an Ocean View
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+
- 01Scan buildings from right to left.
- 02Track the largest height seen to the right.
- 03Keep a building if it exceeds that maximum.
- 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