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:
|
|
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
- Group the Vote table by candidateId and count the votes for each candidate.
- Find the candidateId with the maximum vote count.
- Join with the Candidate table to get the candidate’s name.
Code
|
|
|
|
|
|
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.