imashutosh51

Majority element

Jan 26th, 2026 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.63 KB | None | 0 0
  1. #Boyer Moore voting algorithm
  2. """
  3. Imagine removing pairs of different numbers again and again.
  4. Example: [2, 2, 1, 1, 2]
  5. First 2 stays, next 2 strengthens it, then 1 cancels one 2, next 1 cancels another 2.
  6. In the end, only 2 is left because it appears more times than all others.
  7. So the last remaining number must be the majority element.
  8. """
  9. class Solution:
  10.     def majorityElement(self, nums: List[int]) -> int:
  11.         num,count=0,0
  12.         for i in nums:
  13.             if count==0:
  14.                 num=i
  15.             if i==num:
  16.                 count+=1
  17.             else:
  18.                 count-=1
  19.         return num
  20.  
  21.        
Advertisement
Add Comment
Please, Sign In to add comment