Skip to content

Latest commit

 

History

History
60 lines (48 loc) · 1.15 KB

File metadata and controls

60 lines (48 loc) · 1.15 KB

180. Consecutive Numbers

Description

Table: Logs

+-------------+---------+
| 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:

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.

Solution

/*
 Success Detail:
 Runtime: 317 ms, faster than 99.43% of MySQL online submissions for Consecutive Numbers.
 Memory Usage: 0 MB, less than 100% of MySQL online submissions for Consecutive Numbers.
 */
SELECT DISTINCT l1.Num as ConsecutiveNums
FROM Logs l1,Logs l2,Logs l3
WHERE l2.id=l1.id+1 and l3.id=l1.id+2
  and l1.Num=l2.Num and l1.Num=l3.Num