Consecutive Numbers — LeetCode 180 Python Solution

MediumDatabase
Problem
#180
Reading time
3 min

The problem

Find every number that appears three or more times in a row when the log is read in id order. The Logs table has id (int, primary key, autoincrementing from 1) and num (varchar). Report each qualifying number once, in a column named ConsecutiveNums.

Example

Input
Logs(id, num) = (1, '5'), (2, '5'), (3, '5'), (4, '7'), (5, '7'), (6, '5'), (7, '5')
Output
ConsecutiveNums = 5
Explanation
5 occupies ids 1, 2 and 3 — three consecutive rows — while 7 never runs longer than two.

Python solution

Python
import pandas as pd


def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame:
    all_the_same = lambda lst: lst.nunique() == 1
    logs["is_consecutive"] = (
        logs["num"].rolling(window=3, center=True, min_periods=3).apply(all_the_same)
    )
    return (
        logs.query("is_consecutive == 1.0")[["num"]]
        .drop_duplicates()
        .rename(columns={"num": "ConsecutiveNums"})
    )

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 180. Consecutive Numbers?
LeetCode 180. Consecutive Numbers is rated Medium on LeetCode.
What topics does LeetCode 180. Consecutive Numbers cover?
LeetCode 180. Consecutive Numbers is tagged Database on LeetCode.

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