Find majority element

June 24, 2022 · 1 min read

https://practice.geeksforgeeks.org/problems/majority-element/0

Moore’s voting algorithm

class Solution {
public:
  int majorityElement(vector<int> &nums) {
    int major = nums[0], count = 1;

    for (int i = 1; i < nums.size(); i++) {
      if (major == nums[i]) {
        count++;
      } else if (count == 0) {
        count++;
        major = nums[i];
      } else {
        count--;
      }
    }

    return major;
  }
};
Find missing and repeating
Searching in an array where adjacent differ by at most K