This series will be focused on Coding interview questions curated from various interviews / via online source.
”Â
Hackland Election
There are n citizens voting in this year’s Hackland election. Each voter writes the name of their chosen candidate on a ballot and places it in a ballot box. The candidate with the highes number of votes win the election; if two or more candidates have the same number of votes, then the tied candidates’ names are ordered alphabetically and the last name wins.
Complete the election Winner function in your editor. It has 1 parameter:L an array of strings, votes, describing the votes in the ballot box. This function must review these votes and return a string representing the name of the winning candidate.
Constraints
- 1<= n <= 10^4
Input Format An array of Strings
Output Format Name of the person who has the max votes. If there are multiple people with same number of votes(max) then print the last name of the list arranged in dictionary order.
Input Example:
5
Vamsi
Krishna
Vamsi
Krishna
Tallapudi
Output:
Vamsi
“
Related Links
Coding Approach for Hackland Election Problem
Here is the output using Kotlin Programming Language. Here I am using Collection Framework’s HashMap with the approach of storing key value pairs with new key addition for every new word and incrementing the value for every repeated word:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main.interview.hacklandelection | |
import com.sun.xml.internal.fastinfoset.util.StringArray | |
import java.util.* | |
fun main() { | |
val list = StringArray() | |
var iter = readLine()!!.toInt() | |
while(iter– > 0) { | |
list.add(readLine()!!) | |
} | |
electionWinner(list) | |
} | |
fun electionWinner(list: StringArray) { | |
var winner = "" | |
var max = 0 | |
val hashMap = HashMap<String, Int>() | |
for (i in 0 until list.size) { | |
if (hashMap.containsKey(list[i])) { | |
hashMap[list[i]] = hashMap.getValue(list[i])+1 | |
} else { | |
hashMap[list[i]] = 0 | |
} | |
} | |
for (entry in hashMap.entries) { | |
if(entry.value > max) { | |
max = entry.value | |
winner = entry.key | |
} else if(entry.value == max) { | |
winner = if(entry.key > winner) entry.key else winner | |
} | |
} | |
println(winner) | |
} |
Hope it will be helpful to you guys for your interview preparation. Feel free to suggest modifications if any. Contact us here if you want to share your interview questions with fellow developers.
Good one