↓Skip to main content
  1. LeetCode/

LeetCode 229: Majority Element II

·2 mins· ·
LeetCode Medium Array Hash-Table Sorting Counting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-12

  • Submissions: Accepted ×2

Approach
#

At most two values can appear more than n / 3 times. Generalizing Boyer-Moore, keep two candidates with counts: a match adds a vote; another value takes an empty slot if there is one, otherwise both counts drop by one (three distinct values cancel). The survivors need not exceed n / 3, so count them again. Hash-map counting (Hash Table Template 1) also works, without O(1) space.

My Attempts
#

Both submissions passed on the first try by sorting and counting each run of equal values with two pointers, keeping runs longer than n // 3, in O(n log n) rather than with voting.

Solution
#

class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        c1, c2, n1, n2 = None, None, 0, 0
        for x in nums:
            if x == c1:
                n1 += 1
            elif x == c2:
                n2 += 1
            elif n1 == 0:
                c1, n1 = x, 1
            elif n2 == 0:
                c2, n2 = x, 1
            else:
                n1, n2 = n1 - 1, n2 - 1
        return [c for c in (c1, c2) if c is not None and nums.count(c) > len(nums) // 3]

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Check for a match with either candidate before filling an empty slot, or one value may take both slots.
  • Always verify the counts at the end.

Interview Explanation
#

At most two values can exceed a third, so I keep two candidates with votes and decrement both on any other value, cancelling triples of distinct values, then recount the survivors. Time O(n), space O(1).

Related

LeetCode 347: Top K Frequent Elements
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
LeetCode 347 note: count first, then take the k most frequent with a size-k heap or a bucket sort indexed by count
LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group
LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 106 note: the last post-order value is the root; taking roots from the end of the post-order, build the right subtree before the left
LeetCode 105: Construct Binary Tree from Preorder and Inorder Traversal
·2 mins
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 105 note: the first pre-order value is the root, and its position in the in-order tells the left subtree’s size; look positions up in a dictionary for O(n)
LeetCode 215: Kth Largest Element in an Array
·2 mins
LeetCode Medium Array Divide-and-Conquer Sorting Heap-Priority-Queue
LeetCode 215 note: keep a min-heap of size k whose top is the k-th largest, or use quickselect for O(n) on average
LeetCode 128: Longest Consecutive Sequence
·2 mins
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 note: put everything in a set and count upward only from values whose x - 1 is absent; each value is seen at most twice, O(n)