Skip to content

Commit 28b3e81

Browse files
authored
Merge pull request #89 from iamAntimPal/Branch-1
Branch 1
2 parents fcc3719 + a37cf6b commit 28b3e81

File tree

5 files changed

+790
-0
lines changed

5 files changed

+790
-0
lines changed
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# 📰 Article Views I - LeetCode 1148
2+
3+
## 📌 Problem Statement
4+
You are given the **Views** table that records article views.
5+
6+
### Views Table
7+
| Column Name | Type |
8+
| ----------- | ---- |
9+
| article_id | int |
10+
| author_id | int |
11+
| viewer_id | int |
12+
| view_date | date |
13+
14+
- The table **may contain duplicate rows**.
15+
- Each row indicates that **some viewer viewed an article** written by some author on a specific date.
16+
- If `author_id = viewer_id`, it means **the author viewed their own article**.
17+
18+
### Task:
19+
Find **all authors** who have viewed **at least one of their own articles**.
20+
- **Return the result sorted by `id` in ascending order**.
21+
22+
---
23+
24+
## 📊 Example 1:
25+
### Input:
26+
**Views Table**
27+
| article_id | author_id | viewer_id | view_date |
28+
| ---------- | --------- | --------- | ---------- |
29+
| 1 | 3 | 5 | 2019-08-01 |
30+
| 1 | 3 | 6 | 2019-08-02 |
31+
| 2 | 7 | 7 | 2019-08-01 |
32+
| 2 | 7 | 6 | 2019-08-02 |
33+
| 4 | 7 | 1 | 2019-07-22 |
34+
| 3 | 4 | 4 | 2019-07-21 |
35+
| 3 | 4 | 4 | 2019-07-21 |
36+
37+
### Output:
38+
| id |
39+
| --- |
40+
| 4 |
41+
| 7 |
42+
43+
### Explanation:
44+
- **Author 4** viewed their own article (`viewer_id = author_id`).
45+
- **Author 7** viewed their own article (`viewer_id = author_id`).
46+
- The result is sorted in **ascending order**.
47+
48+
---
49+
50+
## 🖥 SQL Solutions
51+
52+
### 1️⃣ Standard MySQL Solution
53+
#### Explanation:
54+
- **Filter rows** where `author_id = viewer_id`.
55+
- Use `DISTINCT` to **remove duplicates**.
56+
- **Sort the result** in ascending order.
57+
58+
```sql
59+
SELECT DISTINCT author_id AS id
60+
FROM Views
61+
WHERE author_id = viewer_id
62+
ORDER BY id ASC;
63+
```
64+
65+
---
66+
67+
### 2️⃣ Alternative Solution Using `GROUP BY`
68+
#### Explanation:
69+
- **Group by** `author_id` and **filter authors** who have viewed at least one of their own articles.
70+
71+
```sql
72+
SELECT author_id AS id
73+
FROM Views
74+
WHERE author_id = viewer_id
75+
GROUP BY author_id
76+
ORDER BY id ASC;
77+
```
78+
79+
---
80+
81+
## 🐍 Pandas Solution (Python)
82+
#### Explanation:
83+
- **Filter rows** where `author_id == viewer_id`.
84+
- **Select distinct author IDs**.
85+
- **Sort the result** in ascending order.
86+
87+
```python
88+
import pandas as pd
89+
90+
def authors_who_viewed_own_articles(views: pd.DataFrame) -> pd.DataFrame:
91+
# Filter rows where author_id == viewer_id
92+
filtered = views[views["author_id"] == views["viewer_id"]]
93+
94+
# Select unique author IDs and sort
95+
result = pd.DataFrame({"id": sorted(filtered["author_id"].unique())})
96+
97+
return result
98+
```
99+
100+
---
101+
102+
## 📁 File Structure
103+
```
104+
📂 Article-Views-I
105+
│── 📜 README.md
106+
│── 📜 solution.sql
107+
│── 📜 solution_group_by.sql
108+
│── 📜 solution_pandas.py
109+
│── 📜 test_cases.sql
110+
```
111+
112+
---
113+
114+
## 🔗 Useful Links
115+
- 📖 [LeetCode Problem](https://leetcode.com/problems/article-views-i/)
116+
- 📚 [SQL DISTINCT vs GROUP BY](https://www.w3schools.com/sql/sql_distinct.asp)
117+
- 🐍 [Pandas Unique Function](https://pandas.pydata.org/docs/reference/api/pandas.Series.unique.html)
118+
119+
## Let me know if you need any changes! 🚀
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
# 🏦 Monthly Transactions I - LeetCode 1193
2+
3+
## 📌 Problem Statement
4+
You are given the **Transactions** table that records financial transactions.
5+
6+
### Transactions Table
7+
| Column Name | Type |
8+
| ----------- | ------- |
9+
| id | int |
10+
| country | varchar |
11+
| state | enum |
12+
| amount | int |
13+
| trans_date | date |
14+
15+
- **id** is the **primary key**.
16+
- The **state** column is an `ENUM` type with values **"approved"** and **"declined"**.
17+
- Each row **records a transaction** with an amount and a transaction date.
18+
19+
### Task:
20+
Find **monthly statistics** for each country:
21+
- Total **number of transactions**.
22+
- Total **amount of transactions**.
23+
- Total **number of approved transactions**.
24+
- Total **amount of approved transactions**.
25+
26+
The **month format should be `YYYY-MM`**.
27+
28+
---
29+
30+
## 📊 Example 1:
31+
### Input:
32+
**Transactions Table**
33+
| id | country | state | amount | trans_date |
34+
| --- | ------- | -------- | ------ | ---------- |
35+
| 121 | US | approved | 1000 | 2018-12-18 |
36+
| 122 | US | declined | 2000 | 2018-12-19 |
37+
| 123 | US | approved | 2000 | 2019-01-01 |
38+
| 124 | DE | approved | 2000 | 2019-01-07 |
39+
40+
### Output:
41+
| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount |
42+
| ------- | ------- | ----------- | -------------- | ------------------ | --------------------- |
43+
| 2018-12 | US | 2 | 1 | 3000 | 1000 |
44+
| 2019-01 | US | 1 | 1 | 2000 | 2000 |
45+
| 2019-01 | DE | 1 | 1 | 2000 | 2000 |
46+
47+
### Explanation:
48+
- **December 2018 (US)**:
49+
- **2 transactions** (1000 + 2000).
50+
- **1 approved transaction** (1000).
51+
- **January 2019 (US)**:
52+
- **1 transaction** (2000).
53+
- **1 approved transaction** (2000).
54+
- **January 2019 (DE)**:
55+
- **1 transaction** (2000).
56+
- **1 approved transaction** (2000).
57+
58+
---
59+
60+
## 🖥 SQL Solution
61+
62+
### 1️⃣ Standard MySQL Solution
63+
#### Explanation:
64+
- **Extract the month** from `trans_date` using `DATE_FORMAT()`.
65+
- **Count transactions** for each `month` and `country`.
66+
- **Sum transaction amounts**.
67+
- **Filter only approved transactions** separately using `CASE WHEN`.
68+
69+
```sql
70+
SELECT
71+
DATE_FORMAT(trans_date, '%Y-%m') AS month,
72+
country,
73+
COUNT(id) AS trans_count,
74+
SUM(CASE WHEN state = 'approved' THEN 1 ELSE 0 END) AS approved_count,
75+
SUM(amount) AS trans_total_amount,
76+
SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END) AS approved_total_amount
77+
FROM Transactions
78+
GROUP BY month, country
79+
ORDER BY month, country;
80+
```
81+
82+
---
83+
84+
## 🐍 Pandas Solution (Python)
85+
#### Explanation:
86+
- **Extract the month (`YYYY-MM`)** from `trans_date`.
87+
- **Group by month and country**.
88+
- **Compute counts and sums** using `.agg()`.
89+
90+
```python
91+
import pandas as pd
92+
93+
def monthly_transactions(transactions: pd.DataFrame) -> pd.DataFrame:
94+
# Extract 'YYYY-MM' from the trans_date
95+
transactions['month'] = transactions['trans_date'].dt.strftime('%Y-%m')
96+
97+
# Aggregate transaction counts and sums
98+
result = transactions.groupby(['month', 'country']).agg(
99+
trans_count=('id', 'count'),
100+
approved_count=('state', lambda x: (x == 'approved').sum()),
101+
trans_total_amount=('amount', 'sum'),
102+
approved_total_amount=('amount', lambda x: x[transactions['state'] == 'approved'].sum())
103+
).reset_index()
104+
105+
return result.sort_values(['month', 'country'])
106+
```
107+
108+
---
109+
110+
## 📁 File Structure
111+
```
112+
📂 Monthly-Transactions
113+
│── 📜 README.md
114+
│── 📜 solution.sql
115+
│── 📜 solution_pandas.py
116+
│── 📜 test_cases.sql
117+
```
118+
119+
---
120+
121+
## 🔗 Useful Links
122+
- 📖 [LeetCode Problem](https://leetcode.com/problems/monthly-transactions-i/)
123+
- 📚 [SQL `GROUP BY` Clause](https://www.w3schools.com/sql/sql_groupby.asp)
124+
- 🐍 [Pandas GroupBy Documentation](https://pandas.pydata.org/docs/reference/groupby.html)
125+
126+
## Let me know if you need any modifications! 🚀
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# 🚌 Last Person to Fit in the Bus - LeetCode 1204
2+
3+
## 📌 Problem Statement
4+
You are given the **Queue** table, which contains information about people waiting for a bus.
5+
6+
### Queue Table
7+
| Column Name | Type |
8+
| ----------- | ------- |
9+
| person_id | int |
10+
| person_name | varchar |
11+
| weight | int |
12+
| turn | int |
13+
14+
- **person_id** contains unique values.
15+
- The **turn** column determines the order in which people will board (`turn = 1` means the first person to board).
16+
- The **bus has a weight limit of 1000 kg**.
17+
- Only **one person can board at a time**.
18+
19+
### Task:
20+
Find **the last person** who can board the bus **without exceeding the 1000 kg weight limit**.
21+
22+
---
23+
24+
## 📊 Example 1:
25+
### Input:
26+
**Queue Table**
27+
| person_id | person_name | weight | turn |
28+
| --------- | ----------- | ------ | ---- |
29+
| 5 | Alice | 250 | 1 |
30+
| 4 | Bob | 175 | 5 |
31+
| 3 | Alex | 350 | 2 |
32+
| 6 | John Cena | 400 | 3 |
33+
| 1 | Winston | 500 | 6 |
34+
| 2 | Marie | 200 | 4 |
35+
36+
### Output:
37+
| person_name |
38+
| ----------- |
39+
| John Cena |
40+
41+
### Explanation:
42+
Ordering by `turn`:
43+
| Turn | ID | Name | Weight | Total Weight |
44+
| ---- | --- | --------- | ------ | ------------ |
45+
| 1 | 5 | Alice | 250 | 250 |
46+
| 2 | 3 | Alex | 350 | 600 |
47+
| 3 | 6 | John Cena | 400 | 1000 | ✅ (last person to board) |
48+
| 4 | 2 | Marie | 200 | 1200 | ❌ (exceeds limit) |
49+
| 5 | 4 | Bob | 175 ||
50+
| 6 | 1 | Winston | 500 ||
51+
52+
---
53+
54+
## 🖥 SQL Solution
55+
56+
### 1️⃣ Standard MySQL Solution
57+
#### Explanation:
58+
- **Use a self-join** to accumulate the total weight up to each person's turn.
59+
- **Filter out** people whose cumulative weight exceeds **1000**.
60+
- **Find the last person** who can board.
61+
62+
```sql
63+
SELECT a.person_name
64+
FROM
65+
Queue AS a,
66+
Queue AS b
67+
WHERE a.turn >= b.turn
68+
GROUP BY a.person_id
69+
HAVING SUM(b.weight) <= 1000
70+
ORDER BY a.turn DESC
71+
LIMIT 1;
72+
```
73+
74+
---
75+
76+
### 📝 Step-by-Step Breakdown:
77+
78+
1️⃣ **Self-Join on the Table**
79+
```sql
80+
FROM Queue AS a, Queue AS b
81+
WHERE a.turn >= b.turn
82+
```
83+
- This pairs each row `a` with all rows `b` where `b.turn` is less than or equal to `a.turn`.
84+
- Allows us to calculate the **cumulative sum of weights** for each person.
85+
86+
2️⃣ **Group by Each Person**
87+
```sql
88+
GROUP BY a.person_id
89+
```
90+
- Groups all rows by `person_id` so we can perform calculations per person.
91+
92+
3️⃣ **Compute the Cumulative Weight**
93+
```sql
94+
HAVING SUM(b.weight) <= 1000
95+
```
96+
- Filters out people whose cumulative boarding weight exceeds **1000 kg**.
97+
98+
4️⃣ **Find the Last Person Who Can Board**
99+
```sql
100+
ORDER BY a.turn DESC
101+
LIMIT 1;
102+
```
103+
- **Sorts by turn in descending order** so that we find the **last person** who can board.
104+
- **Limits to 1 row** to return only the last eligible person.
105+
106+
---
107+
108+
## 🐍 Pandas Solution (Python)
109+
#### Explanation:
110+
- **Sort by `turn`** to simulate the boarding order.
111+
- **Compute the cumulative sum** of weights.
112+
- **Find the last person** whose weight sum **does not exceed 1000**.
113+
114+
```python
115+
import pandas as pd
116+
117+
def last_person_to_fit(queue: pd.DataFrame) -> pd.DataFrame:
118+
# Sort by turn
119+
queue = queue.sort_values(by="turn")
120+
121+
# Compute cumulative weight sum
122+
queue["cumulative_weight"] = queue["weight"].cumsum()
123+
124+
# Filter those who fit on the bus
125+
queue = queue[queue["cumulative_weight"] <= 1000]
126+
127+
# Return the last person to fit
128+
return queue.tail(1)[["person_name"]]
129+
```
130+
131+
---
132+
133+
## 📁 File Structure
134+
```
135+
📂 Last-Person-Fit
136+
│── 📜 README.md
137+
│── 📜 solution.sql
138+
│── 📜 solution_pandas.py
139+
│── 📜 test_cases.sql
140+
```
141+
142+
---
143+
144+
## 🔗 Useful Links
145+
- 📖 [LeetCode Problem](https://leetcode.com/problems/last-person-to-fit-in-the-bus/)
146+
- 📚 [SQL `GROUP BY` Clause](https://www.w3schools.com/sql/sql_groupby.asp)
147+
- 🐍 [Pandas cumsum() Documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.cumsum.html)
148+
149+
## Let me know if you need any modifications! 🚀

0 commit comments

Comments
 (0)