Skip to main content

Winning Candidate - Solution & Explanation

MediumPremiumFree on FleetCodeDatabase4 min read
Practice this problem

Problem Statement

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.

 

Example 1:

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.

Approach Overview

Problem Overview: You are given two tables: Candidate and Vote. Each row in Vote stores a candidateId representing a vote cast for that candidate. The task is to return the name of the candidate who received the highest number of votes.

Approach 1: GROUP BY + COUNT Aggregation (O(n) time, O(k) space)

The most direct solution aggregates votes by candidate. Join the Vote table with Candidate using the candidate ID, group the rows by candidate, and compute the vote count using COUNT(*). Once counts are computed, sort them in descending order with ORDER BY and return the top row using LIMIT 1. The key idea is that SQL aggregation lets the database compute vote totals efficiently in a single scan. Time complexity is O(n) where n is the number of votes, and space complexity is O(k) for storing grouped counts of k candidates. This approach relies on concepts from database queries and SQL aggregation.

Approach 2: Aggregation Subquery + Join (O(n) time, O(k) space)

Another option computes vote counts in a derived table first. Use a subquery that groups the Vote table by candidateId and calculates COUNT(*). Then join this aggregated result with the Candidate table to fetch the candidate name. Finally, sort the aggregated counts and return the highest one. This approach separates counting logic from the final lookup step, which can improve readability when queries become more complex. Complexity remains O(n) time and O(k) space because the database still scans all votes and stores counts per candidate.

Approach 3: Window Function Ranking (O(n) time, O(k) space)

With modern MySQL versions, you can compute vote totals and rank candidates using a window function. First aggregate votes per candidate using GROUP BY. Then apply RANK() or DENSE_RANK() over the counts ordered descending. Finally, select the candidate whose rank equals 1. Window functions make the ranking logic explicit and are useful if the query later needs to return multiple top candidates or additional ranking information. The database still performs aggregation over all votes, so time complexity is O(n) and space complexity is O(k). This approach highlights advanced SQL features and analytical query patterns.

Recommended for interviews: The GROUP BY + COUNT + ORDER BY approach is what interviewers expect. It shows you understand relational aggregation and how to extract the maximum result directly in SQL. Mentioning alternative forms like subqueries or window functions demonstrates deeper familiarity with database query design.

Solution

Code

MySQL

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
GROUP BY + COUNT + ORDER BYO(n)O(k)Standard SQL solution when finding the entity with the highest frequency.
Aggregation Subquery + JoinO(n)O(k)Useful when separating aggregation logic from lookup improves readability.
Window Function RankingO(n)O(k)Best when ranking multiple candidates or returning top-N results.

Video Solution

LeetCode Medium 574 "Winning Candidate" Interview SQL Question With Detailed Explanation • Everyday Data Science • 2,394 views views

Watch 6 more video solutions →

Frequently Asked Questions

Is Winning Candidate easy or hard?
Winning Candidate is generally considered a medium SQL problem. The logic is straightforward once you recognize that it requires counting votes per candidate and selecting the maximum using GROUP BY, COUNT, and ORDER BY.
Winning Candidate Python/Java solution
This problem is typically solved using SQL rather than Python or Java because it operates directly on database tables. In application code, the equivalent logic would count occurrences of candidate IDs using a hash map and then return the key with the maximum frequency.
How to solve Winning Candidate in O(n)?
Aggregate votes using COUNT grouped by candidateId. Join the result with the Candidate table to retrieve the candidate name, then sort by the vote count in descending order and return the first row. The database processes the votes in a single pass, giving O(n) time complexity.
What is the best approach for Winning Candidate?
The best approach uses SQL aggregation with GROUP BY and COUNT. Join the Vote and Candidate tables, group votes by candidate, compute the count, then order the results by vote count descending and return the top row with LIMIT 1. This runs in O(n) time over the votes table.
Is Winning Candidate asked at Google/Amazon/Meta?
Database aggregation problems like this appear frequently in SQL interview rounds across companies such as Amazon, Meta, and Google. Candidates are expected to understand joins, GROUP BY, and how to compute maximum counts using ORDER BY or window functions.
What data structure is used in Winning Candidate?
The problem relies on relational database tables and SQL aggregation rather than in-memory data structures. Internally, the database groups rows by candidateId and maintains a count for each candidate before sorting the results.
What is the time complexity of Winning Candidate?
The query scans all rows in the Vote table to compute counts, giving O(n) time complexity where n is the number of votes. The database stores aggregated counts for each candidate, which requires O(k) space where k is the number of candidates.

Ready to solve this problem?

Practice Winning Candidate with our built-in code editor and test cases.

Practice on FleetCode