Wednesday, 25 November 2015

Kata Day 1: Find The Parity Outlier


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

For example:

[2, 4, 0, 100, 4, 11, 2602, 36]

Should return: 11

[160, 3, 1719, 19, 11, 13, -21]

Should return: 160

Level: 6kyu

Link to the Kata: The Parity Outlier

I have followed an approach where I have to break the problem into two sub-problems.

Problem 1: To find whether its a all even but one an all odd but one array.

To solve this problem I checked the first 3 elements of an array. As it is given that the array has a minimum length of 3, it is safe to check first 3 elements for if they are odd or even. I store the number of odd elements in a odd count variable(m) and number of even elements in an even count variable (n). Comparing these 2, I can solve the problem 1 and find the the type of the array.

Problem 2: To find the parity outlier. There are two paths to check this and we take any 1 of them depending upon the type of our array. We loop through the array using a while loop and check every element by finding its modulus(%) value by dividing it by 2 and find the outlier based on its modulus value.

In case of an all even array the outlier will be the one with modulus value of 1 and in case of an all odd array the outlier will be the one with modulus value of 0.


We use the Math.abs() function of Javascript in order to keep a common ground and treat  all the elements of the array as positive numbers at the time of testing.

Here is a link to the code: Day 1 Kata

Please mention your suggestions or your doubts in the comment below.

Happy coding. :)

No comments:

Post a Comment