Majority Element II
Repeating Number
Problem
Given an integer array of size n
, find all elements that appear more than ⌊ n/3 ⌋
times.
Example:
Thought Process
Moore's Voting Algorithm: We have to use Moore's Voting Algorithm so we can find the potential candidates. Since Moore's Voting Algorithm finds the majority element in a sequence, this is perfect for finding the candidates that may appear more than
⌊ n/3 ⌋
times. In this case, there are two potential candidates.The reason why we can have 2 possible majority elements at max is because the problem asks us to find all elements that appear more than
⌊ n/3 ⌋
times. Suppose there are three elements that appeared more than⌊ n/3 ⌋
times, then there needs to be at least elements in the array, which is not possible ( .e.g. suppose , then the problem asks to find all elements that appeared more than 3 times, which means they have to appear at least 4 times. There can't be 3 items in the array of length 9 that all have appeared 4 times.
Similar to Majority Element I, we will use Moore's Voting Algorithm to find two potential candidates to be later verified that they occur more than
⌊ n/3 ⌋
times.
Solution
Key Facts
We are using Moore's Voting Algorithm to find majority elements so that we can later verify that these elements occure more than
⌊ n/3 ⌋
times. Moore's Voting Algorithm gives us potential candidates since it will find elements that occur the most. We have to then verify these elements.The reason why we can have two majority elements at max is because for finding majority, elements can qualify.
Time Complexity
Time:
Space:
Last updated
Was this helpful?