Similar Problems

Similar Problems not available

Winning Candidate - Leetcode Solution

Companies:

LeetCode:  Winning Candidate Leetcode Solution

Difficulty: Medium

Topics: database  

Problem Description:

You are given a list of candidates for an election. Each candidate has a name and a number of votes they have received so far. The election hasn't been conducted yet, so there are no winning candidates yet.

Write a function that takes the list of candidates and returns the candidate(s) with the most number of votes. If there is more than one candidate with the same number of votes, return all of them in a list.

Example:

Input: [["John", 100], ["Mike", 200], ["Emily", 300], ["Mike", 150]]
Output: ["Emily"]
Explanation: Emily has the most number of votes (300), while Mike has two entries, with a total of 350, and John has one entry with 100 votes. Therefore, Emily is the only winner.

Solution:

One way to solve this problem is to first create a dictionary where we keep the vote count for each candidate. Then we can iterate over the dictionary to find the candidate(s) with the maximum vote count.

Here's how the solution would look like:

def winningCandidate(candidates):
    voteCount = {}
    maxVotes = 0
    for candidate in candidates:
        if candidate[0] not in voteCount:
            voteCount[candidate[0]] = candidate[1]
        else:
            voteCount[candidate[0]] += candidate[1]

        if voteCount[candidate[0]] > maxVotes:
            maxVotes = voteCount[candidate[0]]
    
    winners = []
    for candidate, votes in voteCount.items():
        if votes == maxVotes:
            winners.append(candidate)

    return winners

In this solution, we first create an empty dictionary voteCount to keep track of the votes for each candidate. We then iterate over the given list of candidates. For each candidate, we check if their name is already in the dictionary. If not, we add them to the dictionary with their corresponding vote count. If their name is already present in the dictionary, we simply add their current votes to their previous vote count.

After we have counted the votes of all the candidates, we then loop through the dictionary to find the candidate(s) with the maximum vote count. We do this by checking if the current candidate's vote count is equal to the maximum vote count maxVotes. If it is, we add their name to the winners list.

Finally, we return the winners list containing the name(s) of the winning candidate(s).

Winning Candidate Solution Code

1