Created
December 26, 2022 07:21
-
-
Save dharshan/358d37ba59190bef5783bde1d9718a62 to your computer and use it in GitHub Desktop.
Ruby find dominator/leader element
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
class Dominator | |
def solution(a) | |
counter = 0 | |
candidate = 0 | |
a.each do |elem| | |
if counter == 0 | |
candidate = elem | |
counter += 1 | |
elsif candidate == elem | |
counter += 1 | |
else | |
counter -= 1 | |
end | |
end | |
occurence = a.inject(0) { |sum, x| sum + if x == candidate then 1 else 0 end } | |
if occurence > (a.length / 2) | |
a.find_index(candidate) | |
else | |
-1 | |
end | |
end | |
end | |
puts Dominator.new.solution([3, 0, 1, 1, 4, 1, 1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment