Code Interview – Coderbyte – Simple Mode – Code challenge – JavaScript Solution Source Code

Coderbyte

Simple Mode

Have the function SimpleMode(arr) take the array of numbers stored in arr and return the number that appears most frequently (the mode). For example: if arr contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode return the one that appeared in the array first (ie. [5, 10, 10, 6, 5] should return 5 because it appeared first). If there is no mode return -1. The array will not be empty.

function SimpleMode(arr) { 

const count = {};
  const firstOccurrence = {};
  let maxCount = 0;
  let mode = -1;
  for (let i = 0; i < arr.length; i++) {
    const num = arr[i];
    if (num in count) {
      count[num]++;
    } else {
      count[num] = 1;
      firstOccurrence[num] = i;
    }
    if (count[num] > maxCount || (count[num] === maxCount && firstOccurrence[num] < firstOccurrence[mode])) {
      maxCount = count[num];
      mode = num;
    }
  }
  return (maxCount > 1) ? mode : -1;

}
   
// keep this function call here 
console.log(SimpleMode(readline()));

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *