MediumNo. 0180
Consecutive Numbers — LeetCode 180 Python Solution
- Topics
- Database
- Reading time
- 3 min
- Source
- leetcode.com
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
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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0829 | Consecutive Numbers Sum | Hard |
| 0181 | Employees Earning More Than Their Managers | Easy |
| 0178 | Rank Scores | Medium |
| 0182 | Duplicate Emails | Easy |
| 0177 | Nth Highest Salary | Medium |
| 0183 | Customers Who Never Order | Easy |
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.