Problem

Table: Candidate

+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| id          | int      |
| name        | varchar  |
+-------------+----------+
id is the column with unique values for this table.
Each row of this table contains information about the id and the name of a candidate.

Table: Vote

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| candidateId | int  |
+-------------+------+
id is an auto-increment primary key (column with unique values).
candidateId is a foreign key (reference column) to id from the Candidate table.
Each row of this table determines the candidate who got the ith vote in the elections.

Write a solution to report the name of the winning candidate (i.e., the candidate who got the largest number of votes).

The test cases are generated so that exactly one candidate wins the elections.

The result format is in the following example.

Examples

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Input: 
Candidate table:
+----+------+
| id | name |
+----+------+
| 1  | A    |
| 2  | B    |
| 3  | C    |
| 4  | D    |
| 5  | E    |
+----+------+
Vote table:
+----+-------------+
| id | candidateId |
+----+-------------+
| 1  | 2           |
| 2  | 4           |
| 3  | 3           |
| 4  | 2           |
| 5  | 5           |
+----+-------------+
Output: 
+------+
| name |
+------+
| B    |
+------+
Explanation: 
Candidate B has 2 votes. Candidates C, D, and E have 1 vote each.
The winner is candidate B.

Solution

Method 1 – SQL Aggregation and Join

Intuition

Count the votes for each candidate, then select the candidate with the maximum votes and join with the Candidate table to get the name.

Approach

  1. Group the Vote table by candidateId and count the votes for each candidate.
  2. Find the candidateId with the maximum vote count.
  3. Join with the Candidate table to get the candidate’s name.

Code

1
2
3
4
5
6
7
8
9
SELECT c.name
FROM Candidate c
JOIN (
  SELECT candidateId, COUNT(*) AS cnt
  FROM Vote
  GROUP BY candidateId
  ORDER BY cnt DESC
  LIMIT 1
) v ON c.id = v.candidateId;
1
2
3
4
5
6
7
8
9
SELECT c.name
FROM Candidate c
JOIN (
  SELECT candidateId, COUNT(*) AS cnt
  FROM Vote
  GROUP BY candidateId
  ORDER BY cnt DESC
  LIMIT 1
) v ON c.id = v.candidateId;
1
2
3
4
5
import pandas as pd
def winning_candidate(candidate: pd.DataFrame, vote: pd.DataFrame) -> pd.DataFrame:
    cnt = vote['candidateId'].value_counts().idxmax()
    name = candidate[candidate['id'] == cnt][['name']]
    return name.reset_index(drop=True)

Complexity

  • ⏰ Time complexity: O(n) — Counting votes and finding the max, where n is the number of votes.
  • 🧺 Space complexity: O(n) — For storing the counts.