Find majority element (Boyer–Moore Majority Vote Algorithm)

def majorityElement(A):
 
    # `m` stores the majority element (if present)
    m = -1
 
    # initialize counter `i` with 0
    i = 0
 
    # do for each element `A[j]` in the list
    for j in range(len(A)):
 
        # if counter `i` becomes 0
        if i == 0:
 
            # set the current candidate to `A[j]`
            m = A[j]
 
            # reset the counter to 1
            i = 1
 
        # otherwise, increment the counter if `A[j]` is a current candidate
        elif m == A[j]:
            i = i + 1
 
        # otherwise, decrement the counter if `A[j]` is a current candidate
        else:
            i = i - 1
 
    return m

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source