Majority Element II
LeetCode 229 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Example 1:
Input: nums = [3,2,3]
Output: [3]
Example 2:
Input: nums = [1]
Output: [1]
Example 3:
Input: nums = [1,2]
Output: [1,2]
Constraints:
- `1 <= nums.length <= 5 * 10^4`
- `-10^9 <= nums[i] <= 10^9`
Follow up: Could you solve the problem in linear time and in O(1) space?
Topics: Array, Hash Table, Sorting, Counting
Approachβ
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
Need fast lookups, counting frequencies, finding complements/pairs.
Sortingβ
Sort the input to bring related elements together or enable binary search. Consider: does sorting preserve the answer? What property does sorting give us?
Grouping, finding closest pairs, interval problems, enabling two-pointer or binary search.
Solutionsβ
Solution 1: C# (Best: 213 ms)β
| Metric | Value |
|---|---|
| Runtime | 213 ms |
| Memory | 44.3 MB |
| Date | 2022-02-08 |
public class Solution {
public IList<int> MajorityElement(int[] nums) {
int n = nums.Length;
int count1 = 0, count2 = 0, c1 = 0, c2 = 0;
foreach(var num in nums)
{
if(c1 == num) count1++;
else if(c2==num) count2++;
else if(count1 == 0)
{
c1 = num;
count1 += 1;
}
else if(count2==0)
{
c2 = num; count2++;
}
else
{
count1--;
count2--;
}
}
List<int> result = new List<int>();
if(nums.Count(x=>x==c1) > n/3) result.Add(c1);
if(c1 != c2 && nums.Count(x=>x==c2) > n/3) result.Add(c2);
return result.ToArray();
}
}
π 1 more C# submission(s)
Submission (2022-02-08) β 249 ms, 44.5 MBβ
public class Solution {
public IList<int> MajorityElement(int[] nums) {
int n = nums.Length;
int count1 = 0, count2 = 0, c1 = 0, c2 = 0;
foreach(var num in nums)
{
if(c1 == num) count1++;
else if(c2==num) count2++;
else if(count1 == 0)
{
c1 = num;
count1 += 1;
}
else if(count2==0)
{
c2 = num; count2++;
}
else
{
count1--;
count2--;
}
}
List<int> result = new List<int>();
if(nums.Count(x=>x==c1) > n/3) result.Add(c1);
if(c1 != c2 && nums.Count(x=>x==c2) > n/3) result.Add(c2);
return result.ToArray();
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Sort + Process | $O(n log n)$ | $O(1) to O(n)$ |
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Hash map gives O(1) lookup β think about what to use as key vs value.
- LeetCode provides 3 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: Think about the possible number of elements that can appear more than β n/3 β times in the array.
Hint 2: It can be at most two. Why?
Hint 3: Consider using Boyer-Moore Voting Algorithm, which is efficient for finding elements that appear more than a certain threshold.