All files / exercises/majority-elements index.ts

100% Statements 13/13
81.81% Branches 9/11
100% Functions 2/2
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2130x 5x 5x   5x 11x   11x 8x   3x     11x   8x     2x    
export function majority(nums: number[]): number | null {
  const n = nums.length;
  const map = new Map();
 
  for (const num of nums) {
    let counter = map.get(num);
 
    if (counter === undefined) {
      counter = 1;
    } else {
      counter++;
    }
 
    if (counter >= n / 2) return num;
 
    map.set(num, counter);
  }
 
  return null;
}