In this challenge, you'll be given an array with a length of at least three, containing (possibly quite large) integers. The array is either comprised of entirely odd integers or even integers with one exception. Write a method that returns the integer that is not like the others.
Example:
findOutlier([2, 4, 0, 100, 4, 11, 2602, 36]) => 11
Additional practice arrays:
[160, 3, 1719, 19, 11, 13, -21]
[4, 8, 15, 16, 24, 42]
[16, 6, 40, 66, 68, 28]
Good luck, happy coding~!
This challenge comes from user obnounce. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Top comments (31)
JavaScript 😀
Not efficient, as it's iterating the array twice (I could've used
reduceto iterate once but well... this looks more readable)BTW, the last one looks weird, as it contains only even numbers.
There's a potential bug.
-21will fail bothisOddandisEvenfunction.The function
isOddshould beSince negative odd numbers mod 2 equals to
-1instead of1.Whoa.... you've just caught years worth of bugs I have possibly created... 😅
Thank you @Hao for finding the issue. 😀
I really didn't think that thru. 👍
Here is the updated code
I think I would probably use
!isEvennext time 😎You only need to fetch the firsts 3 items to know what you are searching for.
This goes through the list of numbers only a single time, stopping early if possible. Could probably be code golfed further 😛
I have done a Ruby one, based on counting the number of even values in the first three elements of the array to switch the logic between finding the first even and the first odd element.
Atleast it works somehow 😅
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.
A javascript one that has pretty reasonable complexity
Elixir:
Bad solution! See comments below!
Ruby solution, I tried to do something different.
When the list has no exception, the first element is returned; except when
numberslooks like[3,3](bug that you can fix by adding.uniqwhen computing the sum.)I believe this would fail if the outlier is even and the rest are an odd number of odd numbers. The examples all have an even number of odd numbers. Can you check that?
It seems that I can’t make it right and as simple as it was. So I’ll stick with this solution:
Erlang.