Interview 150

Majority Element

Problem
LC 169
File
interview150_LC169MajorityElement.java
Path
pkg5leetcode/interview150/interview150_LC169MajorityElement.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC169MajorityElement.java
Approach
Boyer-Moore voting finds candidate majority.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC169MajorityElement.java
1package pkg5leetcode.interview150;2 3/*4 * Majority Element | LC 1695 * APPROACH: Boyer-Moore voting finds candidate majority.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class interview150_LC169MajorityElement {9    static int majorityElement(int[] nums) {10        int cand = 0, count = 0;11        for (int x : nums) {12            if (count == 0) { cand = x; count = 1; }13            else count += x == cand ? 1 : -1;14        }15        return cand;16    }17 18    public static void main(String[] args) {19        check(majorityElement(new int[]{3, 2, 3}) == 3, "case1");20        check(majorityElement(new int[]{2, 2, 1, 1, 1, 2, 2}) == 2, "case2");21        System.out.println("all tests passed");22    }23 24    static void check(boolean cond, String name) {25        if (!cond) throw new AssertionError("FAILED: " + name);26        System.out.println("  PASS " + name);27    }28}