LeetCode 180- Consecutive Numbers (SQL & Python) Solutions

This article is going to provide the solution to LeetCode 180 Consecutive Numbers. It’s an easy difficulty question.

Find all numbers that appear at least three times consecutively.

Return the result table in any order.

The result format is in the following example.

LeetCode Question Link

If you want to skip the article, check out the full YouTube video where I code the answer live.

LeetCode 180 SQL Solution

with allnums as (
    Select
        id,
        num,
        lead(num, 1) over (order by id) as next_number,
        lead(num, 2) over (order by id) as second_number
    from Logs
)
Select distinct num as ConsecutiveNums
from allnums
where num = next_number and num = second_number

The code first creates a CTE named “allnums”. It represent all the numbers in the table with additional columns indicating the next number and the second number in sequence.

The CTE selects the following columns: id, num, next_number, and second_number.

lead(num, 1) over (order by id) as next_number: This uses the LEAD() window function to get the next number in sequence based on the order of id.

The Second number column is nearly identical, we just switch 1 with a 2.

After defining the CTE, a main query is executed. It selects distinct values of num from the “allnums” CTE. It applies a filter condition in the WHERE clause: where num = next_number and num = second_number:Â

This condition checks if the current number (num) is equal to both the next number (next_number) and the number two positions ahead (second_number).

LeetCode 180 Python Solution

import pandas as pd
def consecutive_numbers(logs: pd.DataFrame) -> pd.DataFrame:
    logs['next_number'] = logs['num'].shift(periods=1)
    logs['second_number'] = logs['num'].shift(periods=2)
    final = logs[(logs['num'] == logs['next_number']) & (logs['num'] == logs['second_number'])]
    final = final[['num']].drop_duplicates().rename(columns={'num':'ConsecutiveNums'})
    return final[['ConsecutiveNums']]

The consecutive_numbers function takes a Pandas DataFrame named logs as input and returns another Pandas DataFrame.

The first line in the function creates a new column next_number in the DataFrame logs, which contains the value of the num column shifted up by one position.

The second line is nearly identical. We shift 2 positions this time for the second number.

After adding the next and second number columns, a new dataframe is created.

Final contains only the rows where the value in the num column is equal to both the next_number column and the second_number column, indicating consecutive numbers

To match the desired LeetCode output, drop duplicate rows, and rename the num column to ConsecutiveNums.

Return the ConsecutiveNums column of the final DataFrame as the output of the function.

Leave a Reply

Your email address will not be published. Required fields are marked *