Advertisement
smj007

Untitled

Apr 6th, 2025
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. SC - O(n)
  2. TC - O(n) - Booyer-Moore algo
  3. class Solution:
  4.     def majorityElement(self, nums: List[int]) -> int:
  5.         """
  6.        Finds the majority element in the given list using the Boyer-Moore Voting Algorithm.
  7.        
  8.        A majority element is an element that appears more than ⌊n/2⌋ times in the list.
  9.        
  10.        Algorithm:
  11.        1. Initialize a candidate as None and count as 0.
  12.        2. Iterate through each element in the list:
  13.           - If count is 0, update the candidate to the current element and set count to 1.
  14.           - If the current element matches the candidate, increment the count.
  15.           - If the current element does not match the candidate, decrement the count.
  16.        3. The candidate at the end of the iteration will be the majority element.
  17.  
  18.        Why This Works:
  19.        - The algorithm pairs each candidate element with a different element and cancels them out.
  20.        - If an element appears more than half the time (majority), it will survive the cancellation process.
  21.        - Even if the candidate is replaced during the process, the final candidate will be the true majority
  22.          due to its dominance.
  23.         """
  24.         candidate = None
  25.         count = 0
  26.  
  27.         for num in nums:
  28.             if count == 0:
  29.                 candidate = num
  30.                 count += 1
  31.                 continue
  32.  
  33.             count = count + 1 if candidate == num else count - 1
  34.  
  35.         return candidate
  36.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement