AceYourInterviews
Checking sign-in…

7. Majority Element

IntermediateBoyer–Moore cancellation plus verification

Find a value that occurs strictly more than half as many times as the array length. The input does not guarantee that such a value exists, so absence is a real outcome you must handle.

Exactly half the positions is not a majority. Follow the reference API's optional-result convention instead of inventing a numeric sentinel that could be a valid value.

Example 1

Input

[3,2,3]

Output

OptionalInt[3]

Explanation: 3 occurs twice among three positions.

Example 2

Input

[1,2,3]

Output

OptionalInt.empty

Explanation: The first pass may leave a candidate, but no value is a majority.

Example 3

Input

[1,1,2,2]

Output

OptionalInt.empty

Explanation: Exactly half does not satisfy a strict majority.

Constraints

  • 0 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • A strict majority occurs more than floor(nums.length / 2) times. Return an optional value when none exists.
Hints
Hint 1

What happens to a strict majority when two different values are removed?

Hint 2

Represent only the unmatched residue.

Hint 3

Select by cancellation, then verify the candidate’s full count.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Candidate must be verified

[1,2,3]
null