Advertisement
smj007

Buildings with an ocean view

Apr 18th, 2025
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. """
  2. Going from right to left
  3. """
  4. class Solution:
  5.     def findBuildings(self, heights: List[int]) -> List[int]:
  6.  
  7.         # tranverse from right to left
  8.         index = len(heights)-1
  9.         greatest_till_now = heights[-1]
  10.         can_view = [len(heights)-1]
  11.  
  12.         for index in range(len(heights)-2, -1, -1):
  13.             if heights[index] > greatest_till_now:
  14.                 greatest_till_now = heights[index]
  15.                 can_view.append(index)
  16.  
  17.         return  can_view[::-1]
  18.  
  19. """
  20. Going from left to right. Pop all previous buildings from the stack
  21. if they are shorter or equal to the current one (because they can no longer see the ocean).
  22.  
  23. Push the current building’s index onto the stack.
  24. """
  25. class Solution:
  26.     def findBuildings(self, heights: List[int]) -> List[int]:
  27.        
  28.         stack = []
  29.         for i in range(len(heights)):
  30.             # Pop all previous buildings from the stack
  31.             # if they are shorter or equal to the current one  
  32.             while stack and heights[stack[-1]] <= heights[i]:
  33.                 stack.pop()
  34.             stack.append(i)
  35.  
  36.         return stack
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement