Skip to content

Commit 3a81ec9

Browse files
committed
Create consecutive-numbers.sql
add new solution
1 parent 64620ce commit 3a81ec9

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

MySQL/consecutive-numbers.sql

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
#
4+
# Write a SQL query to find all numbers that appear at least three times consecutively.
5+
#
6+
# +----+-----+
7+
# | Id | Num |
8+
# +----+-----+
9+
# | 1 | 1 |
10+
# | 2 | 1 |
11+
# | 3 | 1 |
12+
# | 4 | 2 |
13+
# | 5 | 1 |
14+
# | 6 | 2 |
15+
# | 7 | 2 |
16+
# +----+-----+
17+
# For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.
18+
#
19+
20+
# Write your MySQL query statement below
21+
SELECT DISTINCT(Num) AS ConsecutiveNums
22+
FROM (
23+
SELECT
24+
Num,
25+
@counter := IF(@prev = Num, @counter + 1, 1) AS how_many_cnt_in_a_row,
26+
@prev := Num
27+
FROM
28+
Logs y
29+
, (SELECT @counter:=1, @prev:=NULL) vars
30+
) sq
31+
WHERE how_many_cnt_in_a_row >= 3

0 commit comments

Comments
 (0)