‹ DS&A interview · Socratic
DSA · Array / String · #109

Majority Element

Module 73 · difficulty 2/5·30:00starts on first keystroke

Given an array `nums` of size `n`, return the **majority element** — the element that appears **more than** `⌊n / 2⌋` times. You may assume the majority element always exists in the array. Implement the function `majorityElement(nums)` that returns this element.

Examples
  • nums = [3, 2, 3] 33 appears 2 times, which is more than ⌊3/2⌋ = 1.
  • nums = [2, 2, 1, 1, 1, 2, 2] 22 appears 4 times, which is more than ⌊7/2⌋ = 3.
  • nums = [7] 7A single element is trivially the majority.
Constraints
  • · n == nums.length
  • · 1 <= n <= 5 * 10^4
  • · -10^9 <= nums[i] <= 10^9
  • · The majority element always exists in the array.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.