DEV Community

Riches
Riches

Posted on

Find The Parity Outlier "Codewars"

You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.

Examples
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)

Steps.

  1. I want to create two arrays that will serve as a store for the odd numbers and the even numbers.
  2. creating a for loop that will iterate through the array given .
  3. on each iteration i will check if the number is an even number or an odd number using the modulus operator.
  4. if even number I will push it inside the even Number array and if odd I will push it inside the odd number array.
  5. still inside the for loop before doing another iteration i will check if the even number array and the odd number array has an element inside it.
  6. if yes i will check the smallest between the two of then and return the value inside that one. Note: the question said the outlier is just one so the array that is the smallest is of course the one that contains the outlier so i will return the first and only element in that array.

Algorithm.

function findOutlier(integers){
    //your code here
    let evenArr = []
    let oddArr = []
    for (let index = 0; index < integers.length; index++) {
        const element = integers[index];
        if(element % 2 == 0){
            evenArr.push(element)
        }else{
            oddArr.push(element)
        }
        if(evenArr.length > 0  && oddArr.length > 0){
            if(evenArr.length > oddArr.length){
                return oddArr[0]
            }else if(oddArr.length > evenArr.length){
                return evenArr[0]
            }
        }
    }
  }
  console.log(findOutlier([2,6,8,10,3]));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)