#TCS #NQT #Coding #Programming #QA
Question: Print the winner of the vote or most frequent of the word
Input - arr=["ram","shaym","jadu","shaym","ram","ram"]
Output - “ram”
=====Solution Given at the end====
===========Follow Us & Download App: ================
LinkedIn : https://www.linkedin.com/company/hack...
FB Page: / hackeralgobydebandranifoundation
Google PlayStore App Link: https://play.google.com/store/apps/de...
Main Website Link: https://www.hackeralgo.com
https://github.com/HackerAlgo
Solution --------------------
******** Please note angular bracket not allowed here, so Used "(" for less than and ")" for greater than*****
import java.util.HashMap;
import java.util.Map;
public class Winner {
public static void main(String[] args) {
String arr[] = {"ram", "ram", "hacker", "hacker", "algo", "rahim", "shyam"};
System.out.println(sol(arr));
}
public String voteWinner(String arr[]) {
Map"("String, Integer")" map = new HashMap"("String, Integer")"();
for (int i = 0; i "(" arr.length; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
int max = 0;
String winner = "";
for (Map.Entry"("String, Integer")" entry : map.entrySet()) {
if (max "(" entry.getValue()) {
max = Math.max(entry.getValue(), max);
winner = entry.getKey();
}
}
return winner;
}
}
Here Time complexity is O(2n), as two sequential for loop is iterating n numbers of time
Thanks & Regards,
HackerAlgo Team