Winning Candidate

medium database sql

Problem

Candidate(id, name) and Vote(id, candidate_id). Return the name of the winning candidate.

Inputcand=[(1,'A'),(2,'B'),(3,'C')] votes=[(1,2),(2,2),(3,2),(4,1)]
Output'B'
Candidate B (id 2) has 3 votes, the most.

SELECT name
FROM Candidate
WHERE id = (SELECT candidate_id FROM Vote GROUP BY candidate_id ORDER BY COUNT(*) DESC LIMIT 1);
Time: O(n) Space: O(n)