diff --git a/Algorithms_and_Data_Structures/Stack/AsteroidCollision.py b/Algorithms_and_Data_Structures/Stack/AsteroidCollision.py new file mode 100644 index 0000000000..ca3a8ad2c6 --- /dev/null +++ b/Algorithms_and_Data_Structures/Stack/AsteroidCollision.py @@ -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)) diff --git a/Algorithms_and_Data_Structures/Stack/NextGreaterElementii.py b/Algorithms_and_Data_Structures/Stack/NextGreaterElementii.py new file mode 100644 index 0000000000..40a7a35de0 --- /dev/null +++ b/Algorithms_and_Data_Structures/Stack/NextGreaterElementii.py @@ -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)) diff --git a/Algorithms_and_Data_Structures/Stack/TrappingRainWater.py b/Algorithms_and_Data_Structures/Stack/TrappingRainWater.py new file mode 100644 index 0000000000..4668acfc13 --- /dev/null +++ b/Algorithms_and_Data_Structures/Stack/TrappingRainWater.py @@ -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))