7. Majority Element
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.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Candidate must be verified
[1,2,3]
null