1. Brute Force — Nested Frequency Count
Intuition
For each unique element, count its occurrences across the entire array using a nested loop. Return the element if its count exceeds n / 2.
Algorithm
- Let
majorityThreshold = n / 2. - Loop
ifrom0ton - 1: - Initialize
count = 0. - Loop
jfrom0ton - 1: - If
nums[j] == nums[i], incrementcount. - If
count > majorityThreshold, returnnums[i]. - Return -1 (fallback).
Brute Force Candidate Count Scan
2 of 2 questions left todayPhase 1 — Count occurrences of 2 across the entire array: Step 1: Pick candidate nums[0] = 2
Phase 1 — Count occurrences of 2 across the entire array: Step 1: Pick candidate nums[0] = 2. We need > 3 occurrences to be the majority.
#include <iostream>#include <vector>using namespace std; // Brute Force: Quadratic nested countingint majorityElement(vector<int>& nums) { int n = nums.size(); int majorityThreshold = n / 2; for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { if (nums[j] == nums[i]) { count++; } } if (count > majorityThreshold) { return nums[i]; } } return -1;} int main() { vector<int> nums = {2, 2, 1, 1, 1, 2, 2}; cout << "Output: " << majorityElement(nums) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Approach 1: Brute Force — Nested Frequency Count. - Space complexity:
O(1)— Space complexity for Approach 1: Brute Force — Nested Frequency Count.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.