DEV Community

Discussion on: Daily Challenge #220 - What Dominates Your Array?

Collapse
 
empereol profile image
Empereol

TypeScript

/**
 * Return the dominator of the given array.
 *
 * The dominator is the value that occurs in more than half of the elements of
 * the given array.
 *
 * @param nums Array of numbers.
 *
 * @returns `-1` if there is no dominator.
 *
 * @example
 * dominator([3,4,3,2,3,1,3,3]) → 3
 * dominator([1,2,3,4,5])       → -1 // No val occurs more than half the array
 */
function dominator(nums: number[]): number {
  for (const item of new Set(nums)) {
    if (nums.filter(i => i === item).length > nums.length / 2) {
      return item;
    }
  }

  return -1;
}
Enter fullscreen mode Exit fullscreen mode