Find The Start And End Number Of Continuous Ranges Problem
Description
LeetCode Problem 1285.
Table: Logs
1
2
3
4
5
6
7
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| log_id | int |
+---------------+---------+
id is the primary key for this table.
Each row of this table contains the ID in a log Table.
Since some IDs have been removed from Logs. Write an SQL query to find the start and end number of continuous ranges in table Logs.
Order the result table by start_id.
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
21
22
23
24
25
26
Logs table:
+------------+
| log_id |
+------------+
| 1 |
| 2 |
| 3 |
| 7 |
| 8 |
| 10 |
+------------+
Result table:
+------------+--------------+
| start_id | end_id |
+------------+--------------+
| 1 | 3 |
| 7 | 8 |
| 10 | 10 |
+------------+--------------+
The result table should contain all ranges in table Logs.
From 1 to 3 is contained in the table.
From 4 to 6 is missing in the table
From 7 to 8 is contained in the table.
Number 9 is missing in the table.
Number 10 is contained in the table.
MySQL Solution
1
2
3
4
5
select min(log_id) as start_id, max(log_id) as end_id
from (select l.log_id, (l.log_id - l.row_num) as diff
from (select log_id, row_number() over() as row_num from Logs) l
) l2
group by diff
LeetCode Database - Medium
LeetCode 1132
LeetCode 1149
LeetCode 1158
LeetCode 1164
LeetCode 1174
LeetCode 1193
LeetCode 1204
LeetCode 1205
LeetCode 1212
LeetCode 1264
LeetCode 1270
LeetCode 1285
LeetCode 1308
LeetCode 1321
LeetCode 1341
LeetCode 1355
LeetCode 1364
LeetCode 1393
LeetCode 1398
More LeetCode Database
MySQL Tutorials