Majority Element

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write majority(nums): return the number that appears more than half the time in nums. You can assume nums isn't empty and that such a number always exists. You may reorder nums if that helps. For example, majority([2, 2, 1, 1, 1, 2, 2]) is 2: it appears 4 times out of 7. The checks include 100,000 numbers, so counting each number by scanning the whole list again is too slow.

Your code must pass

  • Finds the majority in a short list
  • Finds it wherever its copies sit
  • Works with negative numbers
  • Is fast enough for 100,000 numbers