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




Related Posts

Nth Highest Salary Problem

LeetCode 177. Write a SQL query to get the nth...

Rank Scores Problem

LeetCode 178. Write a SQL query to rank scores. If...

Consecutive Numbers Problem

LeetCode 180. Write an SQL query to find all numbers...

Second Highest Salary Problem

LeetCode 176. Given the Employee table, write a SQL query...

Employees Earning More Than Their Managers Problem

LeetCode 181. Given the Employee table, write a SQL query...

Combine Two Tables Problem

LeetCode 175. Write a SQL query for a report that...