![]() |
VOOZH | about |
Given a list of n buildings in a line, each building's height is given in heights[] array. Find and return the indices (0-indexed) of buildings with an unobstructed "ocean view," meaning they can see the ocean without taller buildings blocking their view to the right. The task is to return the indices (0-indexed) of the buildings that have an ocean view, sorted in increasing order.
Example:
Input: heights = {4,2,3,1}
Output: {0,2,3}Input: heights = {4,3,2,1}
Output: {0,1,2,3}
Approach:
The idea is to use a right-to-left approach, starting from the rightmost building and moving towards the left. Maintains a variable tallestBuildingSoFar or maxx to keep track of the tallest building encountered so far. For each building, checks if its height is greater than maxx. If it is, the building has an ocean view and its index is added to the result vector. The maxx is then updated to the current building’s height if it’s greater. After iterating through all the buildings, the result[] array contains the indices of the buildings with an ocean view in descending order. Therefore, the vector is reversed to get the indices in ascending order.
Steps-by-step approach:
Below are the implementation of the above approach:
2 4
Time Complexity: O(n), where n is the number of buildings.
Auxililary Space: O(n)