re: Daily Challenge #35 - Find the Outlier VIEW POST

FULL DISCUSSION
 

in JavaScript. o(n), uses constant space.

in the worst case (outlier is at the end of the loop) it will go through all items. but if the outlier is found before, the loop stops.

function findOutlier(nums) {
  let lastOddOrEven = [null, null];
  for (let i = 0; i < nums.length; i++) {
    const parity = nums[i] % 2;
    if (lastOddOrEven[0] !== null && lastOddOrEven[1] !== null) {
      // we've already seen one odd and one even number,
      // so the outlier is the one number we've seen with a
      // different parity
      return lastOddOrEven[1 - parity];
    }
    lastOddOrEven[parity] = nums[i];
  }
  // if the loop can't return the outlier, this is because it's the last item
  return nums[nums.length - 1];
}
code of conduct - report abuse