CodingNodes / Arrays & Hashing / Majority Element System design Space play · ←→ step · R restart

Problem

You are given an array nums of length n. One value in it appears more than n / 2 times (rounded down). Return that value.

You may assume such a value always exists.

Constraints

  • 1 ≤ nums.length ≤ 5 · 10⁴
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • A majority element always exists

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: One pass over nums, with constant work per number.

Space: Only a candidate and a count are stored, no matter how long nums is.

Keep a candidate and a count. A number equal to the candidate adds one vote, any other number removes one. When the count is zero, the next number becomes the candidate. Since the majority element has more copies than all other numbers together, it survives every cancellation.