Winner of an election | Practice | GeeksforGeeks

Given an array of names (consisting of lowercase characters) of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidate that received Max votes. If there is tie, print lexicographically smaller name.
Example 1:
Input:
n = 13
Votes[] = {john,johnny,jackie,johnny,john 
jackie,jamie,jamie,john,johnny,jamie,
johnny,john}
Output: john 4
Explanation: john has 4 votes casted for 
him, but so does johny. john is 
lexicographically smaller, so we print 
john and the votes he received.
Example 2:
Input:
n = 3
Votes[] = {andy,blake,clark}
Output: andy 1
Explanation: All the candidates get 1 
votes each. We print andy as it is 
lexicographically smaller.

Your Task:
You only need to complete the function winner() that takes an array of strings arr, and n as parameters and returns the name of the candiate with maximum votes and the number of votes the candidate got as an array of size 2.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)
Constraints:
1 <= n <= 105
0
parikshitparmar6 hours ago
from collections import Counter       counter_dict = Counter(arr)       max_val = [max(counter_dict.values())]       d = [k for k,v in counter_dict.items() if v == max_val[0]]       d.sort()       return (d[0], max_val[0])
0
adamyasharma4933 days ago
Easy to Understand Time:O(n) and Space :O(n)    + only two traversals 
 vector<string> winner(string arr[],int n)   {        unordered_map<string , int> m ;         vector<string> ans ;         for(int i=0; i< n ; i++)        {            m[arr[i]]++ ;         }                string s; int res= INT_MIN ;         for(auto x: m)        {            if(x.second > res )            {                s= x.first ;                 res = x.second ;             }            if(x.second == res)            {                if(s.length() != 0)                 {                    s = (s < x.first)? s :x.first ;                 }            }        }        string votes = to_string(res) ;         ans.push_back(s) ; ans.push_back(votes) ;        return ans ; 
 
0
singhvipnesh66 days ago
class Solution{   //Function to return the name of candidate that received maximum votes.   public static String[] winner(String arr[], int n)   {       Arrays.sort(arr);       HashMap<String,Integer>map=new HashMap<>();       for(int i=0;i<arr.length;i++)       {           if(!map.containsKey(arr[i]))           map.put(arr[i],1);           else            map.put(arr[i],map.get(arr[i])+1);       }       int k=0;       String[] s = new String[2];       int count;       int min=Integer.MIN_VALUE;       for(int i=0;i<arr.length;i++)       {           count=map.get(arr[i]);           if(count>min)           {               min=count;               s[0]=arr[i];               s[1]=String.valueOf(min);           }       }       return s;   }}
 
0
ziaurrahman1 week ago
Easy To Understand JAVA Solution
    HashMap<String,Integer> map = new HashMap<String,Integer>();              for(int i=0; i<n; i++){           String s= arr[i];           if(map.containsKey(s)){               map.put(s,map.getOrDefault(s,0)+1);           }           else{               map.put(s,1);           }       }       int max=Integer.MIN_VALUE;              for(String i: map.keySet()){           if(map.get(i) > max){               max=map.get(i);           }       }       ArrayList<String> list= new ArrayList<String>();              for(String i: arr){           if(map.get(i)==max && !list.contains(i)){               list.add(i);           }       }       Collections.sort(list);       String[] ans = new String[2];              ans[0] = list.get(0);       ans[1] =  Integer.toString(max);              return ans;           
0
shubham211019971 week ago
Easiest solution avilable on internet -→using hashing and lambda expression
public static String[] winner(String arr[], int n)
   {
       Map<String,Integer>h=new HashMap<>();
       for(String i:arr){
           h.put(i,h.getOrDefault(i,0)+1);
       }
     Arrays.sort(arr,(n1,n2)->{
         int f1=h.get(n1);
         int f2=h.get(n2);
         
         if(f1!=f2) return f2-f1;
         else
           return n1.compareTo(n2);
         
      });
      
       String[] str=new  String[2];
        str[0]=arr[0];
       str[1]=""+h.get(arr[0]);
       return str;
   }
0
gautam2002pandeyjee1 week ago
See how to make things complex.
class Solution{   //Function to return the name of candidate that received maximum votes.   public static String[] winner(String arr[], int n)   {       // Here you need to make a HashMap of String and integer.       int max = 0;       int num = 0;       String str1= null;       HashMap<String,Integer> has = new HashMap<>();       for(String str: arr){           has.put(str,has.getOrDefault(str,0)+1);       }       for(Map.Entry<String,Integer> set: has.entrySet()){                      if(set.getValue()>max)           max = set.getValue();                  }      for(Map.Entry<String,Integer> set : has.entrySet()){         if(set.getValue()==max){             str1 = set.getKey();         }               }      for(Map.Entry<String,Integer> set: has.entrySet()){          if(set.getValue()==max){              if(str1.compareTo(set.getKey())>0){                  str1 = set.getKey();                                }                                                  }          }      Integer min = max;      String arrr[]= {str1,min.toString()};            return arrr;          }}
 
+3
mazumderg5373 weeks ago
EASY HASHING SOLUTION IN CPP
  vector<string> winner(string arr[],int n)
   {
       // Your code here
       // Return the string containing the name and an integer
       // representing the number of votes the winning candidate got
       unordered_map<string , int>umap;
       for(int i=0;i<n;i++){
           umap[arr[i]]++;
       }
       
       string name = "";
       int max_vote = 0;
       
       for(auto itr = umap.begin(); itr!=umap.end(); itr++){
           string key = itr->first;
           int val = itr->second;
           
           if(val>max_vote){
               max_vote = val;
               name = key;
           }
           else if(val == max_vote){
               if(key<name)
                   name = key;
           }
       }
       
       vector<string> ans;
       ans.push_back(name);
       string temp = to_string(max_vote);
       ans.push_back(temp);
       
       return ans;
   }
0
jerinvarghese0274 weeks ago
total time taken = 0.05
def winner(self,arr,n):       # Your code here       # return the name of the winning candidate and the votes he recieved       vote = {}              for i in arr:           if i in vote.keys():               vote[i] += 1           else:               vote[i] = 1       maxVal = 0       for i in set(vote.values()):           if i > maxVal:               maxVal = i       winners = []       for i,j in vote.items():           if j == maxVal:               winners.append(i)              minWord = min(winners)              return minWord, maxVal
0
haulya4 weeks ago
    vector<string> winner(string arr[],int n)   {       // Your code here       // Return the string containing the name and an integer       // representing the number of votes the winning candidate got
       unordered_map<string, int>um;              for(int i = 0; i < n; i++){           um[arr[i]]++;       }              string winner = arr[0];       int maxvotes = 0;       for(auto it = um.begin(); it != um.end(); it++){           if(maxvotes < (*it).second){               winner = (*it).first;                maxvotes = (*it).second;           }           else if(maxvotes == (*it).second && (winner > (*it).first)){               winner = (*it).first;           }       }              vector<string> res;       res.push_back(winner);       res.push_back(to_string(maxvotes));       return res;   }
+1
kartikeyashokgautam1 month ago
Easy To understand JAVA Solution :-
   public static String[] winner(String arr[], int n)   {             String[] result = new String[2];              // storing candidates with their votes        HashMap<String,Integer> hm = new HashMap<>();              for(String s : arr)       {          if(hm.containsKey(s))          {              hm.put(s,hm.get(s)+1);          }                    else          {              hm.put(s,1);          }       }              // Finding who got the max votes       int max=0;       for(String s: arr)       {           if(hm.get(s)>max)           {               int temp = max;               max=hm.get(s);           }       }          // Since by default priority queue gives ans in ascending order      // therefore here also pq will give ans in lexicographcally (alphabetically ascending order)            PriorityQueue<String> pq = new PriorityQueue<>();                  for(String s: hm.keySet())     {  // Add only if candidate get maximum votes
      // so , only candidates with maximum votes will be added in "lexicographically" fashion 
    // candidate with smallest lexicographical value will at peek of PQ.
         if(hm.get(s)==max)          {             pq.add(s);         }     }              result[0]=pq.peek();       result[1]=Integer.toString(max); //converting  Integer value of vote to string as Return type is String       return result;   }
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.