Find winner of an election where votes are represented as candidate names
Given an array of names of candidates in an election. A candidate name in the array represents a vote cast to 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
We have four Candidates with name as 'John',
'Johnny', 'jamie', 'jackie'. The candidates
John and Johny get maximum votes. Since John
is alphabetically smaller, we print it.A simple solution is to run two loops and count occurrences of every word. The time complexity of this solution is O(n * n * MAX_WORD_LEN).
An efficient solution is to use Hashing. We insert all votes in a hash map and keep track of counts of different names. Finally, we traverse the map and print the person with maximum votes.
C++
// C++++ program to find winner in an election.#include "bits/stdc++.h"using namespace std; /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ void findWinner(vector<string>& votes) { // Insert all votes in a hashmap unordered_map<string,int> mapObj ; for (auto& str : votes) { mapObj[str]++; } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; string winner; for (auto& entry : mapObj) { string key = entry.first; int val = entry.second; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner>key) winner = key; } cout << winner << endl; } // Driver code int main() { vector<string> votes = { "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" }; findWinner(votes); return 0; } |
Java
// Java program to find winner in an election.import java.util.*;public class ElectoralVotingBallot{ /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ public static void findWinner(String votes[]) { // Insert all votes in a hashmap Map<String,Integer> map = new HashMap<String, Integer>(); for (String str : votes) { if (map.keySet().contains(str)) map.put(str, map.get(str) + 1); else map.put(str, 1); } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; String winner = ""; for (Map.Entry<String,Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer val = entry.getValue(); if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner.compareTo(key) > 0) winner = key; } System.out.println(winner); } // Driver code public static void main(String[] args) { String[] votes = { "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" }; findWinner(votes); }} |
Python3
# Python3 program to find winner in an election.from collections import defaultdict''' We have four Candidates with name as 'John','Johnny', 'jamie', 'jackie'.The votes in String array are as per thevotes casted. Print the name of candidatesreceived Max vote. '''def findWinner(votes): # Insert all votes in a hashmap mapObj = defaultdict(int) for st in votes: mapObj[st] += 1 # Traverse through map to find the # candidate with maximum votes. maxValueInMap = 0 winner = "" for entry in mapObj: key = entry val = mapObj[entry] if (val > maxValueInMap): maxValueInMap = val winner = key # If there is a tie, pick lexicographically # smaller. elif (val == maxValueInMap and winner > key): winner = key print(winner)# Driver codeif __name__ == "__main__": votes = [ "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" ] findWinner(votes)# This code is contributed by ukasp |
C#
// C# program to find winner in an election.using System;using System.Collections.Generic;public class ElectoralVotingBallot{ /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ public static void findWinner(String []votes) { // Insert all votes in a hashmap Dictionary<String,int> map = new Dictionary<String, int>(); foreach (String str in votes) { if (map.ContainsKey(str)) map[str] = map[str] + 1; else map.Add(str, 1); } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; String winner = ""; foreach(KeyValuePair<String, int> entry in map) { String key = entry.Key; int val = entry.Value; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner.CompareTo(key) > 0) winner = key; } Console.WriteLine(winner); } // Driver code public static void Main(String[] args) { String[] votes = { "john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john" }; findWinner(votes); }}// This code is contributed by PrinciRaj1992 |
Javascript
<script>// Javascript program to find winner in an election. /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ function findWinner(votes) { let map = new Map(); for(let i=0;i<votes.length;i++) { if(map.has(votes[i])) { map.set(votes[i], map.get(votes[i]) + 1); } else map.set(votes[i], 1); } // Traverse through map to find the candidate // with maximum votes. let maxValueInMap = 0; let winner = ""; for (let [key, value] of map.entries()) { let Key = key; let val = value; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner>Key) winner = Key; } document.write(winner); } // Driver code let votes=["john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie", "john", "johnny", "jamie", "johnny", "john"]; findWinner(votes); // This code is contributed by rag2127</script> |
Output:
John
Another efficient solution is to use Trie. Please refer most frequent word in an array of strings.
This article is contributed by Ishfaq Ramzan Nagoo. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.



