Find the Start and End Number of Continuous Ranges — LeetCode 1285 Python Solution

MediumLeetCode PremiumDatabase
Problem
#1285
Reading time
4 min

Table schema

SQL
Table: Logs +---------------+---------+ | Column Name | Type | +---------------+---------+ | log_id | int | +---------------+---------+ log_id is the column of unique values for this table. Each row of this table contains the ID in a log Table.

Example

SQL
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| log_id        | int     |
+---------------+---------+
log_id is the column of unique values for this table.
Each row of this table contains the ID in a log Table.

Python solution

Python
import duckdb
import pandas as pd

def solution(logs: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Logs", logs)
    return con.execute("""WITH
    T AS (
        SELECT
            log_id,
            SUM(delta) OVER (ORDER BY log_id) AS pid
        FROM
            (
                SELECT
                    log_id,
                    IF((log_id - LAG(log_id) OVER (ORDER BY log_id)) = 1, 0, 1) AS delta
                FROM Logs
            ) AS t
    )
SELECT MIN(log_id) AS start_id, MAX(log_id) AS end_id
FROM T
GROUP BY pid;""").df()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1285. Find the Start and End Number of Continuous Ranges?
LeetCode 1285. Find the Start and End Number of Continuous Ranges is rated Medium on LeetCode.
What topics does LeetCode 1285. Find the Start and End Number of Continuous Ranges cover?
LeetCode 1285. Find the Start and End Number of Continuous Ranges is tagged Database on LeetCode.
Is LeetCode 1285. Find the Start and End Number of Continuous Ranges a premium problem?
Yes. LeetCode 1285. Find the Start and End Number of Continuous Ranges is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview