MediumNo. 0574LeetCode Premium

Winning Candidate — LeetCode 574 Python Solution

Topics
Database
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

PythonSolution
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

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0577Employee BonusEasy
0570Managers with at Least 5 Direct ReportsMedium
0584Find Customer RefereeEasy
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium

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.

Free to download. Check it runs on your machine, then pick a plan.