Skip to main content
Back to problems
#1285
Medium Database

Find the start and end number of continuous ranges

Database
81.8% acceptance
Mar 31, 2026
592
36

No description available.

Solution

Pandas
Time O(1)
Space O(1)
LeetCode
solution.pandas
# 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.
# 
#  
# 
# Write a solution to find the start and end number of continuous ranges in the table Logs.
# 
# Return the result table ordered by start_id.
# 
# The result format is in the following example.
#
# Example 1:
# Input:
# Logs table:
# +------------+
# | log_id     |
# +------------+
# | 1          |
# | 2          |
# | 3          |
# | 7          |
# | 8          |
# | 10         |
# +------------+
# Output:
# +------------+--------------+
# | start_id   | end_id       |
# +------------+--------------+
# | 1          | 3            |
# | 7          | 8            |
# | 10         | 10           |
# +------------+--------------+
# Explanation:
# 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 from the table.
# Number 10 is contained in the table.

import pandas as pd

def find_continuous_ranges(logs: pd.DataFrame) -> pd.DataFrame:
  logs = logs.sort_values('log_id').reset_index(drop=True)
  logs['grp'] = logs['log_id'] - range(len(logs))
  result = logs.groupby('grp')['log_id'].agg(
    start_id='min',
    end_id='max'
  ).reset_index(drop=True)
  return result.sort_values('start_id').reset_index(drop=True)