Given an array nums of size n, return the majority element: the value that appears more than ⌊n / 2⌋ times. It always exists.
Keep a candidate and a counter. Matching values vote for it, others vote against. When the counter hits zero, pick the current value. The majority survives all cancellations.
1function majorityElement(nums: number[]): number {2let candidate = 0, count = 0;3for (const x of nums) {4if (count === 0) candidate = x;5count += x === candidate ? 1 : -1;6}7return candidate;8}
No candidate yet; count = 0.
Space: play/pause · ←/→: step