15% off all plans & roadmaps Use code
See plansProblem editorial
Implement Solution.majorityElement(nums), where nums is a non-empty array of integers. Let n be the number of elements in nums; an integer is a majority element when it occurs more than n / 2 times in the array.
Majority Element is a Array/Matrix Manipulation Patterns problem, in the Hashing - Frequency Map / Counting subpattern. The pattern covers in-place operations, hashing, prefix sums, spiral traversal, and cyclic sort
The reference solution runs in O(n) time and O(1) space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Majority Element is a Array/Matrix Manipulation Patterns problem, in the Hashing - Frequency Map / Counting subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.