1. Nested Loops Counting
Intuition
For every unique element, count its occurrences across the entire array using a nested loop and check if count > floor(n / 3).
Algorithm
- 1. Let n = nums.length, threshold = floor(n / 3).
- 2. Initialize result list.
- 3. For i from 0 to n-1: - If nums[i] already in result, continue. - Count occurrences of nums[i] across nums. - If count > threshold, append nums[i] to result.
- 4. Return result.
Brute Force All-Elements Frequency Scan
2 of 2 questions left todayPhase 1 — Step 1: Step 1: Target element is nums[0] = 1
Phase 1 — Step 1: Step 1: Target element is nums[0] = 1. To be a majority element, count must be > 8/3 = 2 (i.e. at least 3 occurrences).
import java.util.*; public class Main { public static class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> res = new ArrayList<>(); int n = nums.length; int threshold = n / 3; for (int i = 0; i < n; i++) { if (res.contains(nums[i])) continue; int count = 0; for (int j = 0; j < n; j++) { if (nums[j] == nums[i]) count++; } if (count > threshold) res.add(nums[i]); } return res; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {1, 1, 1, 3, 3, 2, 2, 2}; System.out.println("Majority elements (> n/3): " + sol.majorityElement(nums)); }}Time & Space Complexity
- Time complexity:
O(N^2)— Nested loops examine all N elements against the entire array of size N, resulting in O(N2) time. - Space complexity:
O(1)— Auxiliary space is O(1) as at most 2 elements can satisfy the condition.
Why Brute Force Doesn't Scale:
Since at most 2 elements can satisfy the > n/3 condition, we only need to track 2 candidate integers and their balance counters. When we see 3 mutually distinct elements, canceling all 3 reduces array size without altering the relative majority of the surviving elements. This brings auxiliary space down from O(N) to O(1).
For N = 50,000 unique ints: Hash map takes ~2 MB heap. Boyer-Moore uses 4 integer registers (16 bytes).