Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 * 104-109 <= nums[i] <= 109Follow up: Could you solve the problem in linear time and in O(1) space?
Problem summary: Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
[3,2,3]
[1]
[1,2]
majority-element)check-if-a-number-is-majority-element-in-a-sorted-array)most-frequent-even-element)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #229: Majority Element II
class Solution {
public List<Integer> majorityElement(int[] nums) {
int n1 = 0, n2 = 0;
int m1 = 0, m2 = 1;
for (int m : nums) {
if (m == m1) {
++n1;
} else if (m == m2) {
++n2;
} else if (n1 == 0) {
m1 = m;
++n1;
} else if (n2 == 0) {
m2 = m;
++n2;
} else {
--n1;
--n2;
}
}
List<Integer> ans = new ArrayList<>();
n1 = 0;
n2 = 0;
for (int m : nums) {
if (m == m1) {
++n1;
} else if (m == m2) {
++n2;
}
}
if (n1 > nums.length / 3) {
ans.add(m1);
}
if (n2 > nums.length / 3) {
ans.add(m2);
}
return ans;
}
}
// Accepted solution for LeetCode #229: Majority Element II
func majorityElement(nums []int) []int {
var n1, n2 int
m1, m2 := 0, 1
for _, m := range nums {
if m == m1 {
n1++
} else if m == m2 {
n2++
} else if n1 == 0 {
m1, n1 = m, 1
} else if n2 == 0 {
m2, n2 = m, 1
} else {
n1, n2 = n1-1, n2-1
}
}
n1, n2 = 0, 0
for _, m := range nums {
if m == m1 {
n1++
} else if m == m2 {
n2++
}
}
var ans []int
if n1 > len(nums)/3 {
ans = append(ans, m1)
}
if n2 > len(nums)/3 {
ans = append(ans, m2)
}
return ans
}
# Accepted solution for LeetCode #229: Majority Element II
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
n1 = n2 = 0
m1, m2 = 0, 1
for m in nums:
if m == m1:
n1 += 1
elif m == m2:
n2 += 1
elif n1 == 0:
m1, n1 = m, 1
elif n2 == 0:
m2, n2 = m, 1
else:
n1, n2 = n1 - 1, n2 - 1
return [m for m in [m1, m2] if nums.count(m) > len(nums) // 3]
// Accepted solution for LeetCode #229: Majority Element II
struct Solution;
type Pair = (i32, usize);
impl Solution {
fn majority_element(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut pairs: Vec<Pair> = vec![];
for &x in &nums {
if pairs.iter().any(|p| p.0 == x) {
pairs = pairs
.into_iter()
.map(|p| (p.0, if p.0 == x { p.1 + 1 } else { p.1 }))
.collect();
} else {
if pairs.len() < 2 {
pairs.push((x, 1));
} else {
pairs = pairs.into_iter().map(|p| (p.0, p.1 - 1)).collect();
pairs = pairs.into_iter().filter(|p| p.1 > 0).collect();
}
}
}
let mut res = vec![];
for pair in pairs {
let sum = nums
.iter()
.fold(0, |acc, &x| if x == pair.0 { acc + 1 } else { acc });
if sum > n / 3 {
res.push(pair.0);
}
}
res
}
}
#[test]
fn test() {
let nums = vec![3, 2, 3];
let res = vec![3];
assert_eq!(Solution::majority_element(nums), res);
let nums = vec![1, 1, 1, 3, 3, 2, 2, 2];
let res = vec![1, 2];
assert_eq!(Solution::majority_element(nums), res);
}
// Accepted solution for LeetCode #229: Majority Element II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #229: Majority Element II
// class Solution {
// public List<Integer> majorityElement(int[] nums) {
// int n1 = 0, n2 = 0;
// int m1 = 0, m2 = 1;
// for (int m : nums) {
// if (m == m1) {
// ++n1;
// } else if (m == m2) {
// ++n2;
// } else if (n1 == 0) {
// m1 = m;
// ++n1;
// } else if (n2 == 0) {
// m2 = m;
// ++n2;
// } else {
// --n1;
// --n2;
// }
// }
// List<Integer> ans = new ArrayList<>();
// n1 = 0;
// n2 = 0;
// for (int m : nums) {
// if (m == m1) {
// ++n1;
// } else if (m == m2) {
// ++n2;
// }
// }
// if (n1 > nums.length / 3) {
// ans.add(m1);
// }
// if (n2 > nums.length / 3) {
// ans.add(m2);
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.