Longest Winning Streak — LeetCode 2173 Python Solution

HardLeetCode PremiumDatabase
Problem
#2173
Reading time
5 min

Table schema

SQL
Table: Matches +-------------+------+ | Column Name | Type | +-------------+------+ | player_id | int | | match_day | date | | result | enum | +-------------+------+ (player_id, match_day) is the primary key (combination of columns with unique values) for this table. Each row of this table contains the ID of a player, the day of the match they played, and the result of that match.

Example

SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| player_id   | int  |
| match_day   | date |
| result      | enum |
+-------------+------+
(player_id, match_day) is the primary key (combination of columns with unique values) for this table.
Each row of this table contains the ID of a player, the day of the match they played, and the result of that match.
The result column is an ENUM (category) type of ('Win', 'Draw', 'Lose').

Python solution

Python
import duckdb
import pandas as pd

def solution(matches: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Matches", matches)
    return con.execute("""WITH
    S AS (
        SELECT
            *,
            ROW_NUMBER() OVER (
                PARTITION BY player_id
                ORDER BY match_day
            ) - ROW_NUMBER() OVER (
                PARTITION BY player_id, result
                ORDER BY match_day
            ) AS rk
        FROM Matches
    ),
    T AS (
        SELECT player_id, SUM(result = 'Win') AS s
        FROM S
        GROUP BY player_id, rk
    )
SELECT player_id, MAX(s) AS longest_streak
FROM T
GROUP BY player_id;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 2173. Longest Winning Streak?
LeetCode 2173. Longest Winning Streak is rated Hard on LeetCode.
What topics does LeetCode 2173. Longest Winning Streak cover?
LeetCode 2173. Longest Winning Streak is tagged Database on LeetCode.
Is LeetCode 2173. Longest Winning Streak a premium problem?
Yes. LeetCode 2173. Longest Winning Streak 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