Intermediate Level

Implement the method majorityElement that returns the value appearing more than half the time.

The majority element appears more than size / 2 times. The test data always contains one.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Use only the first size elements.
  • Return the value, not its count.
  • A constant-memory voting scan is possible.

Example 1

Input
nums (int[]) = [3,3,4]
size (int) = 3
Returns (int) 3

Example 2

Input
nums (int[]) = [2,2,1,1,1,2,2]
size (int) = 7
Returns (int) 2

Example 3

Input
nums (int[]) = [5]
size (int) = 1
Returns (int) 5

Maintain a candidate and counter. Different values cancel each other until the majority candidate remains.

Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.