Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Algorithms_and_Data_Structures/Stack/AsteroidCollision.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
def asteroid_collision(asteroids):
"""
LeetCode #735 - Asteroid Collision
----------------------------------
Simulate asteroid collisions moving along a line.
Positive -> right, Negative -> left.
"""
stack = []
for a in asteroids:
while stack and stack[-1] > 0 and a < 0 and stack[-1] < abs(a):
stack.pop()
if not stack or a > 0 or stack[-1] < 0:
stack.append(a)
elif stack[-1] == -a:
stack.pop()
return stack


if __name__ == "__main__":
arr = list(map(int, input("Enter asteroid values separated by space: ").split()))
print("Result after collisions:", asteroid_collision(arr))
24 changes: 24 additions & 0 deletions Algorithms_and_Data_Structures/Stack/NextGreaterElementii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def next_greater_elements(nums):
"""
LeetCode #503 - Next Greater Element II
---------------------------------------
Given a circular array, find the next greater element
for each element in the array.
"""
n = len(nums)
ans = [-1] * n
stack = []

for i in range(2 * n - 1, -1, -1):
while stack and stack[-1] <= nums[i % n]:
stack.pop()
if i < n:
ans[i] = stack[-1] if stack else -1
stack.append(nums[i % n])

return ans


if __name__ == "__main__":
arr = list(map(int, input("Enter numbers separated by space: ").split()))
print("Next greater elements:", next_greater_elements(arr))
32 changes: 32 additions & 0 deletions Algorithms_and_Data_Structures/Stack/TrappingRainWater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
def trapping_rain_water(height):
"""
LeetCode #42 - Trapping Rain Water
----------------------------------
Given n non-negative integers representing an elevation map
where the width of each bar is 1, compute how much water is trapped.
"""
n = len(height)
if n == 0:
return 0

left_max = [0] * n
right_max = [0] * n

left_max[0] = height[0]
for i in range(1, n):
left_max[i] = max(height[i], left_max[i - 1])

right_max[n - 1] = height[n - 1]
for i in range(n - 2, -1, -1):
right_max[i] = max(height[i], right_max[i + 1])

total = 0
for i in range(n):
total += min(left_max[i], right_max[i]) - height[i]

return total


if __name__ == "__main__":
arr = list(map(int, input("Enter heights separated by space: ").split()))
print("Water trapped:", trapping_rain_water(arr))