00:00

Problem Statement

Input/Output Examples

Visual Explanation

When the votes drop to zero, the next value becomes the new candidate. A true majority can never be cancelled out completely, but the second pass is needed to confirm that a majority exists at all.

Approaches

The voting algorithm uses constant memory. The map approach counts every value.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of elements and k the number of distinct values. Voting needs two passes and two variables; counting needs one pass and a map.

Interview Tips and Recommended Approach

  • Always verify unless a majority is guaranteed. The candidate is meaningless otherwise.
  • Explain the cancellation idea rather than just reciting the code.
  • Majority means more than half. Exactly half, as in [1, 1, 2, 2], is not a majority.
  • Know the extension. Elements appearing more than n / 3 times need two candidates.

Recommended Approach: Boyer-Moore Voting

Why: it finds the majority in linear time with only two variables, which is the elegant answer interviewers hope to hear.