Winning Candidate — LeetCode 574 Python Solution

MediumLeetCode PremiumDatabase
Problem
#574
Reading time
2 min

The problem

Report the name of the candidate who received the most votes; the data guarantees exactly one winner. Candidate has id (int, unique) and name (varchar); Vote has id (int, primary key, autoincrementing) and candidateId (int), which references a candidate, with one row per vote cast. Return the winner in a column called name.

Example

Input
Candidate(id, name) = (1, 'Ana'), (2, 'Ben'), (3, 'Cleo'); Vote(id, candidateId) = (1, 2), (2, 2), (3, 3), (4, 2), (5, 1)
Output
name = 'Ben'
Explanation
Candidate 2 receives 3 votes to 1 each for candidates 1 and 3.

Python solution

Python
import pandas as pd

def winning_candidate(candidate: pd.DataFrame, vote: pd.DataFrame) -> pd.DataFrame:
    counts = vote.groupby('candidateId').size()
    max_cnt = counts.max()
    winner_id = counts[counts == max_cnt].index.min()
    name = candidate.loc[candidate['id'] == winner_id, 'name'].iloc[0]
    return pd.DataFrame({'name': [name]})

Complexity

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

Related problems

Frequently asked questions

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