
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Buildings with Sea View in Python
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
Example
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))
Input
[8, 12, 12, 9, 10, 6]
Output
[2, 4, 5]
Advertisements