Skip to main content

Majority Element

Return the element that appears more than n/2 times Example: [3,2,3] => 3

I keep one candidate and a count. Each different value cancels one vote, so the majority survives in constant space.

Examples

You write

majority_element(nums: List[int])

  1. Example 1

    Input
    [3,2,3]
    returns
    3
  2. Example 2

    Input
    [2,2,1,1,1,2,2]
    returns
    2

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Majority Elementeasy

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.