Election Results - Problem
You are given a table Votes with voter and candidate information.
Table: Votes
| Column Name | Type |
|---|---|
| voter | varchar |
| candidate | varchar |
The combination (voter, candidate) is the primary key for this table. Each row contains the name of a voter and their chosen candidate.
Election Rules:
- Each person has exactly 1 vote total
- If a person votes for multiple candidates, their vote is split equally
- Example: voting for 2 candidates means each gets 0.5 votes
Task: Find the candidate(s) who received the most votes and won the election. If there's a tie, return all winners ordered by candidate name ascending.
Table Schema
Votes
| Column Name | Type | Description |
|---|---|---|
voter
PK
|
varchar | Name of the person voting |
candidate
PK
|
varchar | Name of the candidate being voted for |
Primary Key: (voter, candidate)
Note: Each voter can vote for multiple candidates, splitting their single vote equally
Input & Output
Example 1 — Split Votes with Clear Winner
Input Table:
| voter | candidate |
|---|---|
| Alice | John |
| Alice | Bob |
| Bob | John |
Output:
| candidate |
|---|
| John |
💡 Note:
Vote Calculation:
- Alice votes for 2 candidates (John, Bob) → each gets 0.5 votes
- Bob votes for 1 candidate (John) → John gets 1.0 vote
Final Totals:
- John: 0.5 + 1.0 = 1.5 votes
- Bob: 0.5 votes
John wins with 1.5 votes.
Example 2 — Tie Between Candidates
Input Table:
| voter | candidate |
|---|---|
| Alice | John |
| Alice | Bob |
| Bob | John |
| Bob | Bob |
| Charlie | Bob |
Output:
| candidate |
|---|
| Bob |
| John |
💡 Note:
Vote Calculation:
- Alice votes for 2 candidates → 0.5 each to John and Bob
- Bob votes for 2 candidates → 0.5 each to John and Bob
- Charlie votes for 1 candidate → 1.0 to Bob
Final Totals:
- John: 0.5 + 0.5 = 1.0 vote
- Bob: 0.5 + 0.5 + 1.0 = 2.0 votes
Bob wins with 2.0 votes.
Example 3 — Single Voter Multiple Candidates
Input Table:
| voter | candidate |
|---|---|
| Alice | John |
| Alice | Bob |
| Alice | Charlie |
Output:
| candidate |
|---|
| Bob |
| Charlie |
| John |
💡 Note:
Vote Calculation:
- Alice votes for 3 candidates → each gets 1/3 = 0.333... votes
Final Totals:
- All candidates tie with 0.333... votes each
All three candidates win and are returned in alphabetical order.
Constraints
-
1 ≤ voter.length, candidate.length ≤ 100 - Voter and candidate names contain only letters and spaces
- Each voter votes for at least one candidate
Visualization
Tap to expand
Understanding the Visualization
1
Input
Voter-candidate pairs from election
2
Weight Calculation
Split each voter's 1.0 vote among their choices
3
Aggregation
Sum weighted votes per candidate and find winners
Key Takeaway
🎯 Key Insight: When voters can split their single vote among multiple candidates, use vote weighting with GROUP BY aggregation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code