Majority Element
Given an array `nums` of size `n`, return the majority element. The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array. **Examples:** ```typescript majorityElement([3, 2, 3]) // 3 majorityElement([2, 2, 1, 1, 1, 2, 2]) // 2 ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(n)
- Space complexity: O(1)
Boyer-Moore Voting Algorithm scans the array in a single pass of length n.
Follow-Up Questions Interviewers Ask About Majority Element
- How does Boyer-Moore Voting Algorithm guarantee correctness?
Since the majority element occurs more than n/2 times, pairing it off against non-majority elements still leaves the majority candidate with a positive balance.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.