Skip to content

Added stack Problems(medium Leetcode) Rainwater trapping, asteroid co… - #1785

Merged
UTSAVS26 merged 1 commit into
UTSAVS26:mainfrom
snehap27:add-stack-problems
Sep 5, 2025
Merged

UTSAVS26 merged 1 commit into
UTSAVS26:mainfrom
snehap27:add-stack-problems

Conversation

@snehap27

@snehap27 snehap27 commented Sep 4, 2025 •

Copy link
Copy Markdown

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

  • I have provided the issue title.

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.

  • I have described the aim of the project.

Name

Please mention your name.
Sneha Pandey

  • I have provided my name.

GitHub ID

Please mention your GitHub ID.
github.com/snehap27

  • I have provided my GitHub ID.

Email ID

Please mention your email ID for further communication.
snehacherry27@gmail.com

  • I have provided my email ID.

Identify Yourself

Mention in which program you are contributing (e.g., WoB, GSSOC, SSOC, SWOC).
GSSOC contributor

  • I have mentioned my participant role.

Closes

Enter the issue number that will be closed through this PR.
*Closes: #1580 *

  • I have provided the issue number.

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.

  • I have described my changes.

Type of Change

Select the type of change:

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Code style update (formatting, local variables)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

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.).

  • I have described my testing process.

Checklist

Please confirm the following:

  • My code follows the guidelines of this project.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly wherever it was hard to understand.
  • I have made corresponding changes to the documentation.
  • My changes generate no new warnings.
  • I have added things that prove my fix is effective or that my feature works.
  • Any dependent changes have been merged and published in downstream modules.

Summary by CodeRabbit

  • New Features
    • Added a command-line tool to simulate asteroid collisions and output surviving asteroids.
    • Introduced a utility to compute next greater elements for circular arrays.
    • Added a calculator for total trapped rainwater from elevation maps.
    • All tools accept space-separated integers from standard input and print results, supporting quick interactive use.
    • Efficient, linear-time implementations; rainwater tool handles empty input gracefully.

@coderabbitai

coderabbitai Bot commented Sep 4, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds 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

Cohort / File(s) Summary
Stack algorithms (new implementations)
Algorithms_and_Data_Structures/Stack/AsteroidCollision.py, Algorithms_and_Data_Structures/Stack/NextGreaterElementii.py, Algorithms_and_Data_Structures/Stack/TrappingRainWater.py
Add public functions: asteroid_collision(asteroids) using a stack simulation; next_greater_elements(nums) using a monotonic stack over a circular array; trapping_rain_water(height) using precomputed left/right max arrays. Each file includes a __main__ CLI for basic stdin parsing and printing results.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Trapping Rain Water implementation [#1580] ✅
Asteroid Collision implementation [#1580] ✅
Next Greater Element (I & II) implementations [#1580] ❌ Only II implemented; I is missing.
Include explanations and test cases [#1580] ❌ No written explanations or test files added.

Poem

A bunny stacks the stars in line,
Collisions pop—some cease to shine.
Next greater moons around they loop,
While raindrops pool in valley’s scoop.
I twitch my nose, commit complete—
Three scripts hop in, so neat, so sweet! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

👋 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!

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions github-actions Bot added Contributor Denotes issues or PRs submitted by contributors to acknowledge their participation. gssoc25 level2 stale Status: Review Ongoing 🔄 PR is currently under review and awaiting feedback from reviewers. labels Sep 4, 2025
@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

16 similar comments
@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@github-actions

github-actions Bot commented Sep 4, 2025

Copy link
Copy Markdown

✅ PR validation passed! Syncing labels and assignees from the linked issue...

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.py for consistency with AsteroidCollision.py and TrappingRainWater.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 water

Optionally 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 List
Algorithms_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 List

Optional 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 1fc72dd and ffb3a69.

📒 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).

@github-actions github-actions Bot removed the stale label Sep 5, 2025
@UTSAVS26
UTSAVS26 merged commit f848aa0 into UTSAVS26:main Sep 5, 2025
23 checks passed
@UTSAVS26 UTSAVS26 added Status: Approved ✔️ PRs that have passed review and are approved for merging. and removed Status: Review Ongoing 🔄 PR is currently under review and awaiting feedback from reviewers. labels Sep 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Contributor Denotes issues or PRs submitted by contributors to acknowledge their participation. gssoc25 level2 Status: Approved ✔️ PRs that have passed review and are approved for merging.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Code Addition Request]: [DSA: Stack] Add advanced stack-based problems (Rainwater Trapping, Asteroid Collision, Next Greater Element) to the repo

2 participants