MediumNo. 0574LeetCode Premium
Winning Candidate — LeetCode 574 Python Solution
- Topics
- Database
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0577 | Employee Bonus | Easy |
| 0570 | Managers with at Least 5 Direct Reports | Medium |
| 0584 | Find Customer Referee | Easy |
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
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.