Skip to content

✨ (solution): Problem 42. Trapping Rain Water #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 27, 2025
Merged
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
30 changes: 30 additions & 0 deletions .github/workflows/code-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Code Quality Check

on:
push:
branches: [ main, master ]
pull_request:
branches: [ main, master ]

jobs:
python-check:
name: Python Code Check
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install ruff

- name: Run Ruff
run: |
# Run ruff on Python files in solutions directory
ruff check ./solutions
43 changes: 43 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
[tool.ruff]
# Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
select = ["E", "F"]
ignore = []

# Allow autofix for all enabled rules (when `--fix`) is provided.
fixable = ["A", "B", "C", "D", "E", "F"]
unfixable = []

# Exclude a variety of commonly ignored directories.
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".mypy_cache",
".md",
".nox",
".pants.d",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"venv",
]

# Same as Black.
line-length = 88

# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"

# Assume Python 3.12
target-version = "py312"
97 changes: 97 additions & 0 deletions solutions/42. Trapping Rain Water/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
comments: true
difficulty: easy
# Follow `Topics` tags
tags:
- Array
- Two Pointers
- Dynamic Programming
- Stack
- Monotonic Stack
---

# [42. Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/description/)

## Description

Given an elevation map with width of 1 which representing by `n` non-negative integers. Calculate amount of water that can be trapped after rainfall.

**Example 1:**
```
Input: height = [0,1,0,0,1,0,1,3,2,0,1]
Output: 4
Explanation: [1,0,0,1] can trapped 2 units, [1,0,1] can trapped 1 units, [2,0,1] can trapped 1 units.
```

**Example 2:**
```
Input: height = [4,1,2,4,5]
Output: 5
Explanation: [4,1,2,4] can trapped 5 units.
```


**Constraints:**
`n == height.length`
`1 <= n <= 2 * 10^4`
`0 <= height[i] <= 10^5`

## Solution

Shrink from the border. If the outside is higher than the inside, rain will accumulate. Therefore, the difference between the higher and lower bars represents the amount of retained rainwater.


```java
class Solution {
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = height[left], rightMax = height[right];
int water = 0;

while (left < right) {
if (leftMax < rightMax) {
left++;
leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left];
} else {
right--;
rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right];
}
}
return water;
}
}
```

```python
class Solution:
def trap(self, height: list[int]) -> int:
if not height:
return 0

left = 0
right = len(height) - 1
left_max = height[left]
right_max = height[right]
water = 0

while left < right:
if left_max < right_max:
left += 1
left_max = max(left_max, height[left])
water += left_max - height[left]
else:
right -= 1
right_max = max(right_max, height[right])
water += right_max - height[right]
return water
```

## Complexity

- Time complexity: $$O(n)$$
<!-- Add time complexity here, e.g. $$O(n)$$ -->

- Space complexity: $$O(1)$$
<!-- Add space complexity here, e.g. $$O(n)$$ -->
20 changes: 20 additions & 0 deletions solutions/42. Trapping Rain Water/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution {
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = height[left], rightMax = height[right];
int water = 0;

while (left < right) {
if (leftMax < rightMax) {
left++;
leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left];
} else {
right--;
rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right];
}
}
return water;
}
}
21 changes: 21 additions & 0 deletions solutions/42. Trapping Rain Water/Solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution:
def trap(self, height: list[int]) -> int:
if not height:
return 0

left = 0
right = len(height) - 1
left_max = height[left]
right_max = height[right]
water = 0

while left < right:
if left_max < right_max:
left += 1
left_max = max(left_max, height[left])
water += left_max - height[left]
else:
right -= 1
right_max = max(right_max, height[right])
water += right_max - height[right]
return water
Loading