Repository navigation
Added stack Problems(medium Leetcode) Rainwater trapping, asteroid co… - #1785
Conversation
WalkthroughAdds three new Python modules under Algorithms_and_Data_Structures/Stack implementing: Asteroid Collision (LeetCode 735), Next Greater Element II (LeetCode 503), and Trapping Rain Water (LeetCode 42). Each exposes a single function and includes a main block for simple stdin I/O. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant CLI as Script __main__
participant Func as asteroid_collision(asteroids)
participant Stack as stack
User->>CLI: Provide space-separated integers
CLI->>Func: Call with asteroids list
loop For each asteroid a
Func->>Stack: While top>0 and a<0, compare |top| vs |a|
alt |top| < |a|
Stack-->>Func: pop top
Func->>Func: continue collision loop
else |top| == |a|
Stack-->>Func: pop top
Func->>Func: destroy a (do not push)
else |top| > |a|
Func->>Func: destroy a (do not push)
end
opt No collision
Func->>Stack: push a
end
end
Func-->>CLI: Return surviving stack as list
CLI-->>User: Print result
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
|
👋 Thank you for opening this pull request! We're excited to review your contribution. Please give us a moment, and we'll get back to you shortly! Feel free to join our community on Discord to discuss more! |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
16 similar comments
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
|
✅ PR validation passed! Syncing labels and assignees from the linked issue... |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
Algorithms_and_Data_Structures/Stack/NextGreaterElementii.py (2)
1-7: Add type hints and state complexity in the docstring.Improves readability and discoverability for learners.
Apply:
-def next_greater_elements(nums): +def next_greater_elements(nums: 'List[int]') -> 'List[int]': @@ - for each element in the array. + for each element in the array. + + Time: O(n), Space: O(n).And add at file top (outside the shown range):
from typing import List
22-24: Nit: Align filename with problem name.Consider renaming the file to
NextGreaterElementII.pyfor consistency withAsteroidCollision.pyandTrappingRainWater.py.Algorithms_and_Data_Structures/Stack/TrappingRainWater.py (1)
12-27: Optional: switch to O(1) extra space two-pointer variant.Saves memory and keeps code compact, useful for teaching alternative approaches.
Apply:
- 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 + left, right = 0, n - 1 + left_max = right_max = 0 + water = 0 + while left <= right: + if height[left] <= height[right]: + if height[left] >= left_max: + left_max = height[left] + else: + water += left_max - height[left] + left += 1 + else: + if height[right] >= right_max: + right_max = height[right] + else: + water += right_max - height[right] + right -= 1 + return waterOptionally also annotate types and note complexity:
-def trapping_rain_water(height): +def trapping_rain_water(height: 'List[int]') -> int: @@ - where the width of each bar is 1, compute how much water is trapped. + where the width of each bar is 1, compute how much water is trapped. + + Time: O(n), Space: O(1) with two-pointer approach.Add at file top (outside the shown range):
from typing import ListAlgorithms_and_Data_Structures/Stack/AsteroidCollision.py (1)
1-7: Add type hints and include complexity in the docstring; consider the “alive” loop for clarity.Type hints help learners; the “alive” pattern mirrors standard editorial solutions.
Apply minimal annotations:
-def asteroid_collision(asteroids): +def asteroid_collision(asteroids: 'List[int]') -> 'List[int]': @@ - Simulate asteroid collisions moving along a line. + Simulate asteroid collisions moving along a line. Positive -> right, Negative -> left. + + Time: O(n), Space: O(n).Add at file top (outside the shown range):
from typing import ListOptional clarity refactor:
- 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 + stack: List[int] = [] + for a in asteroids: + alive = True + while alive and a < 0 and stack and stack[-1] > 0: + if stack[-1] < -a: + stack.pop() + elif stack[-1] == -a: + stack.pop() + alive = False + else: + alive = False + if alive: + stack.append(a) + return stack
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
Algorithms_and_Data_Structures/Stack/AsteroidCollision.py(1 hunks)Algorithms_and_Data_Structures/Stack/NextGreaterElementii.py(1 hunks)Algorithms_and_Data_Structures/Stack/TrappingRainWater.py(1 hunks)
🔇 Additional comments (3)
Algorithms_and_Data_Structures/Stack/NextGreaterElementii.py (1)
12-19: Correct, linear-time monotonic stack for circular NGE.Handles duplicates via
<=pop, fills answers only on first pass, and appends current value each iteration. Time/space O(n).Algorithms_and_Data_Structures/Stack/TrappingRainWater.py (1)
23-27: Correct two-pass DP solution.Left/right maxima and summation are implemented correctly; returns 0 for empty input. O(n) time, O(n) space.
Algorithms_and_Data_Structures/Stack/AsteroidCollision.py (1)
9-16: Algorithm is correct and passes typical edge cases.Pops smaller right-movers, annihilates equals, and leaves larger survivors; runs in O(n).
Pull Request for PyVerse 💡
Requesting to submit a pull request to the PyVerse repository.
Issue Title
Please enter the title of the issue related to your pull request.
[DSA: Stack] Add advanced stack-based problems (Rainwater Trapping, Asteroid Collision, Next Greater Element) to the repo
Info about the Related Issue
What's the goal of the project?
The goal is to enhance the repository with medium-level stack-based problems from LeetCode, helping contributors and learners practice real interview-level coding questions.
Name
Please mention your name.
Sneha Pandey
GitHub ID
Please mention your GitHub ID.
github.com/snehap27
Email ID
Please mention your email ID for further communication.
snehacherry27@gmail.com
Identify Yourself
Mention in which program you are contributing (e.g., WoB, GSSOC, SSOC, SWOC).
GSSOC contributor
Closes
Enter the issue number that will be closed through this PR.
*Closes: #1580 *
Describe the Add-ons or Changes You've Made
Give a clear description of what you have added or modified.
Implemented Trapping Rain Water (LeetCode #42)
Implemented Asteroid Collision (LeetCode #735)
Implemented Next Greater Element II (LeetCode #503)
All problems are coded in Python with clear comments for readability and understanding.
Type of Change
Select the type of change:
How Has This Been Tested?
Describe how your changes have been tested.
Tested the solutions with sample LeetCode test cases.
Verified correctness using additional custom test inputs.
Checked for edge cases (empty arrays, all negatives, single elements, etc.).
Checklist
Please confirm the following:
Summary by CodeRabbit