Majority Element II

Given an integer array `nums` of size n, return every element that appears more than ⌊n / 3⌋ times. The answer can be in any order. Aim for linear time and O(1) extra space.

30:00

Majority Element II
medium
Free written solution
Topics
Companies

Given an integer array nums of size n, return every element that appears more than ⌊n / 3⌋ times. The answer can be in any order. Aim for linear time and O(1) extra space.

Example 1:
Input: {"nums":[3,2,3]}
Output: [3]
Constraints:
  • 1≤nums.length≤5×1041 \leq \text{nums.length} \leq 5 \times 10^4

  • −109≤nums[i]≤109-10^9 \leq \text{nums}[i] \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,2,3]}

Two candidate slots start empty (count 0). At most two values can appear more than 1 times in 3 numbers.

nums

● voted slot 1

● voted slot 2

✕ cancelled

3
2
3

candidate 1

(empty)

count = 0

candidate 2

(empty)

count = 0

second pass: a winner must appear more than ⌊3/3⌋ = 1 times

waiting for the scan to finish

res

[ ]

Variables
VariableValue
cand10
count10
cand21
count20
DepthFunction Call
Stack empty
0/8