 GFG App
Open App Browser
Continue

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

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.

Recommended Practice

## Naive Approach:

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:

## 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& votes)` `{` `    ``int` `n = votes.size();` `    ``int` `prevCount = 0;` `    ``string result = ``""``;`   `    ``// Iterate over every string` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``int` `count = 0;`   `        ``// Count the occurrence of current string in the` `        ``// given votes[]` `        ``for` `(``int` `j = 0; j < n; j++) {` `            ``if` `(votes[i] == votes[j])` `                ``count++;`   `            ``// Maximise the result if count > previous count` `            ``if` `(count > prevCount) {` `                ``prevCount = count;` `                ``result = votes[i];` `            ``}` `            ``else` `if` `(count == prevCount) {` `                ``result = min(result, votes[i]);` `            ``}` `        ``}` `    ``}`   `    ``// return the result` `    ``cout << result;` `}`   `// Driver code` `int` `main()` `{` `    ``vector votes` `        ``= { ``"john"``, ``"johnny"``, ``"jackie"``, ``"johnny"``,` `            ``"john"``, ``"jackie"``, ``"jamie"``,  ``"jamie"``,` `            ``"john"``, ``"johnny"``, ``"jamie"``,  ``"johnny"``,` `            ``"john"` `};`   `    ``findWinner(votes);` `    ``return` `0;` `}`

## Java

 `import` `java.io.*;` `import` `java.util.*;` `import` `java.util.Vector;`   `public` `class` `Gfg {` `    ``public` `static` `void` `findWinner(List votes)` `    ``{` `        ``int` `n = votes.size();` `        ``int` `prevCount = ``0``;` `        ``String result = ``""``;`   `        ``// Iterate over every string` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``int` `count = ``0``;`   `            ``// Count the occurrence of current string in the` `            ``// given votes[]` `            ``for` `(``int` `j = ``0``; j < n; j++) {` `                ``if` `(votes.get(i).equals(votes.get(j))) {` `                    ``count++;` `                ``}`   `                ``// Maximise the result if count > previous` `                ``// count` `                ``if` `(count > prevCount) {` `                    ``prevCount = count;` `                    ``result = votes.get(i);` `                ``}` `                ``else` `if` `(count == prevCount) {` `                    ``if` `(votes.get(i).compareTo(result) < ``0``)` `                        ``result = votes.get(i);` `                ``}` `            ``}` `        ``}`   `        ``// return the result` `        ``System.out.println(result);` `    ``}`   `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``List votes = ``new` `Vector();` `        ``votes.add(``"john"``);` `        ``votes.add(``"johnny"``);` `        ``votes.add(``"jackie"``);` `        ``votes.add(``"johnny"``);` `        ``votes.add(``"john"``);` `        ``votes.add(``"jackie"``);` `        ``votes.add(``"jamie"``);` `        ``votes.add(``"jamie"``);` `        ``votes.add(``"john"``);` `        ``votes.add(``"johnny"``);` `        ``votes.add(``"jamie"``);` `        ``votes.add(``"johnny"``);` `        ``votes.add(``"john"``);`   `        ``findWinner(votes);` `    ``}` `}`

## Python3

 `# Python program to find winner in an election.` `import` `math`   `# 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. */` `def` `findWinner(votes):` `    ``n ``=` `len``(votes);` `    ``prevCount ``=` `0``;` `    ``result ``=` `"";`   `    ``# Iterate over every string` `    ``for` `i ``in` `range``(``0``, n): ` `        ``count ``=` `0``;`   `        ``# Count the occurrence of current string in the` `        ``# given votes[]` `        ``for` `j ``in` `range``(``0``, n): ` `            ``if` `(votes[i] ``=``=` `votes[j]):` `                ``count ``+``=` `1``;`   `            ``# Maximise the result if count > previous count` `            ``if` `(count > prevCount):` `                ``prevCount ``=` `count;` `                ``result ``=` `votes[i];` `        `  `            ``elif` `(count ``=``=` `prevCount) :` `                ``result ``=` `min``(result, votes[i]);` `        `  `    ``# return the result` `    ``print``(result);`   `# Driver code` `votes ``=` `[ ``"john"``, ``"johnny"``, ``"jackie"``, ``"johnny"``,` `        ``"john"``, ``"jackie"``, ``"jamie"``,  ``"jamie"``,` `        ``"john"``, ``"johnny"``, ``"jamie"``,  ``"johnny"``,` `        ``"john"` `];`   `findWinner(votes);`   `# This code is contributed by agrawalpoojaa976.`

## C#

 `using` `System;` `using` `System.Linq;` `using` `System.Collections.Generic;`   `class` `Gfg {` `  ``public` `static` `void` `findWinner(List<``string``> votes)` `  ``{` `    ``int` `n = votes.Count;` `    ``int` `prevCount = 0;` `    ``string` `result = ``""``;`   `    ``// Iterate over every string` `    ``for` `(``int` `i = 0; i < n; i++) {` `      ``int` `count = 0;`   `      ``// Count the occurrence of current string in the` `      ``// given votes[]` `      ``for` `(``int` `j = 0; j < n; j++) {` `        ``if` `(votes[i] == votes[j]) {` `          ``count++;` `        ``}`   `        ``// Maximise the result if count > previous` `        ``// count` `        ``if` `(count > prevCount) {` `          ``prevCount = count;` `          ``result = votes[i];` `        ``}` `        ``else` `if` `(count == prevCount) {` `          ``if` `(votes[i].CompareTo(result) < 0)` `            ``result = votes[i];` `        ``}` `      ``}` `    ``}`   `    ``// return the result` `    ``Console.WriteLine(result);` `  ``}` `  ``public` `static` `void` `Main(``string``[] args)` `  ``{` `    ``List<``string``> votes = ``new` `List<``string``>() {` `      ``"john"``, ``"johnny"``, ``"jackie"``, ``"johnny"``, ``"john"``,` `      ``"jackie"``, ``"jamie"``, ``"jamie"``, ``"john"``,` `      ``"johnny"``, ``"jamie"``, ``"johnny"``, ``"john"` `      ``};` `    ``findWinner(votes);` `  ``}` `}`   `// This code is contributed by divya_p123.`

## Javascript

 `function` `findWinner(votes) { ` `    ``let n = votes.length; ` `    ``let prevCount = 0; ` `    ``let result = ``""``; ` `  `  `    ``// Iterate over every string ` `    ``for` `(let i = 0; i < n; i++) { ` `        ``let count = 0; ` `  `  `        ``// Count the occurrence of current string in the ` `        ``// given votes[] ` `        ``for` `(let j = 0; j < n; j++) { ` `            ``if` `(votes[i] == votes[j]) ` `                ``count++; ` `  `  `            ``// Maximise the result if count > previous count ` `            ``if` `(count > prevCount) { ` `                ``prevCount = count; ` `                ``result = votes[i]; ` `            ``} ` `            ``else` `if` `(count == prevCount) { ` `                ``result = Math.min(result, votes[i]); ` `            ``} ` `        ``} ` `    ``} ` `  `  `    ``// return the result ` `    ``console.log(result); ` `} ` `  `  `// Driver code ` `let votes ` `    ``= [``"john"``, ``"johnny"``, ``"jackie"``, ``"johnny"``, ` `        ``"john"``, ``"jackie"``, ``"jamie"``, ``"jamie"``, ` `        ``"john"``, ``"johnny"``, ``"jamie"``, ``"johnny"``, ` `        ``"john"``]; ` `  `  `findWinner(votes);`   `// This code is contributed by factworx412`

Output

`john`

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

## Find winner of an election where votes are represented as candidate names using Hashing:

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:

## 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& votes)` `{`   `    ``// Insert all votes in a hashmap` `    ``unordered_map 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 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 map` `            ``= ``new` `HashMap();` `        ``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 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 the` `votes casted. Print the name of candidates` `received 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.` `        ``else` `if` `(val ``=``=` `maxValueInMap ``and` `                 ``winner > key):` `            ``winner ``=` `key`   `    ``print``(winner)`     `# Driver code` `if` `__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 map` `            ``= ``new` `Dictionary();` `        ``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 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

 ``

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.

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.

My Personal Notes arrow_drop_up