Consecutive Numbers Problem
Description
LeetCode Problem 180.
Table: Logs
1
2
3
4
5
6
7
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| num | varchar |
+-------------+---------+
id is the primary key for this table.
Write an SQL query to find all numbers that appear at least three times consecutively.
Return the result table in any order.
The query result format is in the following example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Logs table:
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
Result table:
+-----------------+
| ConsecutiveNums |
+-----------------+
| 1 |
+-----------------+
1 is the only number that appears consecutively for at least three times.
MySQL Solution
1
2
3
4
5
6
7
select l1.Num as ConsecutiveNums
from Logs l1, Logs l2, Logs l3
where (l1.Num = l2.Num and
l2.Num = l3.Num and
l1.Id = l2.Id + 1 and
l2.Id = l3.Id + 1)
group by l1.Num
LeetCode Database - Medium
LeetCode 177
LeetCode 178
LeetCode 180
LeetCode 184
LeetCode 534
LeetCode 550
LeetCode 570
LeetCode 574
LeetCode 578
LeetCode 580
LeetCode 585
LeetCode 602
LeetCode 608
LeetCode 612
LeetCode 614
LeetCode 626
LeetCode 1045
LeetCode 1070
LeetCode 1077
LeetCode 1098
LeetCode 1107
LeetCode 1112
LeetCode 1126
More LeetCode Database
MySQL Tutorials