- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of heights of different buildings. A building with heights value heights[i] can see the ocean when every building on its right are shorter than that building. We have to find the building indices from where we can see the ocean, in ascending order.

So, if the input is like heights = [8, 12, 12, 9, 10, 6], then the output will be [2, 4, 5] because we can see the ocean from building heights 12 at index 2, from building height 10 at index 10 and from last building at index 5.

To solve this, we will follow these steps −

- stack := a new list
- for each index idx and height h in heights, do
- while stack is not empty and heights[top of stack ] <= h, do
- delete last element from stack

- while stack is not empty and heights[top of stack ] <= h, do
- push idx into stack
- return stack

Let us see the following implementation to get better understanding −

def solve(heights): stack = [] for idx, h in enumerate(heights): while stack and heights[stack[-1]] <= h: stack.pop() stack.append(idx) return stack heights = [8, 12, 12, 9, 10, 6] print(solve(heights))

[8, 12, 12, 9, 10, 6]

[2, 4, 5]

- Related Questions & Answers
- Program to find out the buildings that have a better view in Python
- Program to find length of longest word that can be formed from given letters in python
- Shortest Distance from All Buildings in C++
- Program to find out how many transfer requests can be satisfied in Python
- Program to find number of tasks can be finished with given conditions in Python
- Program to find maximum units that can be put on a truck in Python
- Program to check whether list can be partitioned into pairs where sum is multiple of k in python
- Program to find out the sum of numbers where the correct permutation can occur in python
- Program to check subarrays can be rearranged from arithmetic sequence or not in Python
- Program to find number of unique four indices where they can generate sum less than target from four lists in python
- Where can we find Blue Whales?
- Python - Find indices where elements should be inserted to maintain order in Pandas Index
- Where can I find good reference document on python exceptions?
- Find maximum points which can be obtained by deleting elements from array in Python
- Program to find out how many boxes can be put into the godown in Python

Advertisements