VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-winner-election-votes-represented-candidate-names/

⇱ Find winner of an election where votes are represented as candidate names - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find winner of an election where votes are represented as candidate names

Last Updated : 18 Jul, 2024

Given an array of names of candidates in an election. A candidate's name in the array represents a vote cast on the candidate. Print the name of candidates who received the maximum vote. If there is a tie, print a lexicographically smaller name.

Examples: 

Input:  votes[] = {"john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john"} 
Output: John
Explanation: We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The candidates John and Johny get maximum votes. Since John is alphabetically smaller.

Input: votes[] = {"virat", "rohit", "rishabh", "rohit", "virat", "rohit"}
Output: rohit
Explanation: We have three Candidates with name as 'virat', 'rohit', 'rishabh'. rohit get maximum votes. 

A simple solution is to run two loops and count the occurrences of every word. And then find the maximum count.

  • Iterate over every string
    • Count the occurrence of the current string in the given votes[]
    • Maximise the result if count > previous count
  • return the result

Below is the implementation of the above approach:


Output
john

Time Complexity: O(n * n * MAX_WORD_LEN).
Auxiliary Space: O(MAX_WORD_LEN) 

An efficient solution is to use Hashing. Insert all votes in a hash map and keep track of counts of different names. Finally, traverse the map and print the person with the maximum votes.

Follow the steps below to solve the problem:

  • Create a map of string, value pair
  • Now iterate on the votes array and increment the count of every string
  • Traverse the map and the string having maximum count store it as a string variable
  • If there is a tie pick the smaller one

Below is the Implementation of the above approach:


Output
john

Time Complexity: O(N), where N is the total number of votes.
Auxiliary Space: O(N), since unordered_map data structure is used.

Another efficient solution is to use Trie. Please refer most frequent word in an array of strings.

Comment
Article Tags: