Explain Boyer-Moore voting.
Skip to solutionKEEP THE
easyDSA
How do you find the majority element?
302 views
01
Understand the problem
arraysboyer-moore
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Boyer-Moore voting: keep a candidate and a count; increment when you see the candidate, decrement otherwise, and switch candidate when count hits zero. The element appearing more than n/2 times survives. O(n) time, O(1) space.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Boyer-Moore voting
Run Playgrounddef majority_element(nums):
candidate, count = None, 0
for x in nums:
if count == 0:
candidate = x
count += 1 if x == candidate else -1
return candidate
# --- demo ---
print(majority_element([2, 2, 1, 1, 1, 2, 2])) # 205
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 22 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.