An array arr
consisting of n
integers is given. The dominator of arr
is the value that occurs in more than half of the elements of arr
.
Write a function dominator(arr)
that returns the dominator of arr
. The function should return −1 if array does not have a dominator. All values in arr will be >=0.
For example, consider the array such that arr = [3,4,3,2,3,1,3,3]
The dominator of arr is 3 because it occurs in 5 out of 8 elements of arr and 5 is more than half of 8.
dominator([3,4,3,2,3,1,3,3]) => 3
dominator([1,2,3,4,5]) => -1
Tests:
dominator([3,4,3,2,3,1,3,3])
dominator([1,1,1,2,2,2]),
dominator([1,1,1,2,2,2,2])
Good luck!
This challenge comes from joh_pot on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (12)
TypeScript
Swift solution :
And hardcore version :
A solution in JavaScript:
C++ solution
Not tested (written on the phone) but should do the trick
C#
Go Soultion
output:
JavaScript
The edge cases made this one tricky. Here's a working function in Ruby without using Tally
Results
Here's my solution in JavaScript. I'm not sure how to embed Gists, but here is the link to it .... 😥
Doing this taught me about Array.prototype.some. I originally wanted to use .forEach, but needed a way to break out of the loop once we found the dominator -- no need to keep processing once the answer has been found, especially if the scenario was an array of something ridiculous, like 15,000 items.
.tally
is the best!