

- 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
Program to find buildings from where sea can be visible 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]
- Related Questions & Answers
- Program to find number of starting point from where we can start travelling in Python
- 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
- Program to find number of islands, from where we cannot leave in Python
- Shortest Distance from All Buildings in C++
- Program to find index, where we can insert element to keep list sorted in Python
- Program to find out number of blocks that can be covered in Python
- Program to find out how many transfer requests can be satisfied in Python
- C++ program to find number of groups can be formed from set of programmers
- Program to check subarrays can be rearranged from arithmetic sequence or not in Python
- Program to check whether list can be partitioned into pairs where sum is multiple of k 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 find out the sum of numbers where the correct permutation can occur in python
- Program to find number of unique four indices where they can generate sum less than target from four lists in python
Advertisements