Skip to content

Commit dc8d6ee

Browse files
authored
Merge pull request #72 from iamAntimPal/Branch-1
Branch 1
2 parents c29fe66 + a839102 commit dc8d6ee

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed

LeetCode SQL 50 Solution/180. Consecutive Numbers/180. Consecutive Numbers.py

Whitespace-only changes.
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# 180. Consecutive Numbers
2+
3+
## Problem Statement
4+
You are given a table `Logs` with the following structure:
5+
6+
```
7+
+-------------+---------+
8+
| Column Name | Type |
9+
+-------------+---------+
10+
| id | int |
11+
| num | varchar |
12+
+-------------+---------+
13+
```
14+
- `id` is the primary key and auto-increments starting from 1.
15+
- Find all numbers that appear **at least three times consecutively**.
16+
- Return the result table in **any order**.
17+
18+
## Example 1:
19+
20+
**Input:**
21+
22+
```
23+
Logs table:
24+
+----+-----+
25+
| id | num |
26+
+----+-----+
27+
| 1 | 1 |
28+
| 2 | 1 |
29+
| 3 | 1 |
30+
| 4 | 2 |
31+
| 5 | 1 |
32+
| 6 | 2 |
33+
| 7 | 2 |
34+
+----+-----+
35+
```
36+
37+
**Output:**
38+
39+
```
40+
+-----------------+
41+
| ConsecutiveNums |
42+
+-----------------+
43+
| 1 |
44+
+-----------------+
45+
```
46+
47+
---
48+
49+
## Solution Approaches
50+
51+
### **SQL Solution (Using Self Join)**
52+
```sql
53+
SELECT DISTINCT l1.num AS ConsecutiveNums
54+
FROM Logs l1
55+
JOIN Logs l2 ON l1.id = l2.id - 1 AND l1.num = l2.num
56+
JOIN Logs l3 ON l1.id = l3.id - 2 AND l1.num = l3.num;
57+
```
58+
59+
### **SQL Solution (Using Window Functions)**
60+
```sql
61+
SELECT DISTINCT num AS ConsecutiveNums
62+
FROM (
63+
SELECT num, LAG(num,1) OVER (ORDER BY id) AS prev1,
64+
LAG(num,2) OVER (ORDER BY id) AS prev2
65+
FROM Logs
66+
) temp
67+
WHERE num = prev1 AND num = prev2;
68+
```
69+
70+
### **Pandas Solution**
71+
```python
72+
import pandas as pd
73+
74+
def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame:
75+
logs['prev1'] = logs['num'].shift(1)
76+
logs['prev2'] = logs['num'].shift(2)
77+
78+
result = logs[(logs['num'] == logs['prev1']) & (logs['num'] == logs['prev2'])]
79+
return pd.DataFrame({'ConsecutiveNums': result['num'].unique()})
80+
```
81+
82+
---
83+
84+
85+
## File Structure
86+
```
87+
📂 Problem Name
88+
├── 📄 README.md # Problem statement, approach, solution
89+
├── 📄 sql_solution.sql # SQL Solution
90+
├── 📄 pandas_solution.py # Pandas Solution
91+
└── 📄 example_input_output.txt # Sample input & expected output
92+
```
93+
94+
## Useful Links
95+
- [LeetCode Problem](https://leetcode.com/problems/consecutive-numbers/) 🚀
96+
- [SQL `JOIN` Explained](https://www.w3schools.com/sql/sql_join.asp)
97+
- [MySQL `LAG()` Window Function](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html)
98+
99+
---
100+
101+
Feel free to contribute with optimized solutions! 💡

0 commit comments

Comments
 (0)