https://repl.it/join/aczpcaoo-nicolegooden
Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
describe('findOddInt', () => {
it('should return true', () => {
expect(true).toBeTruthy()
})
it('should return the correct integer', () => {
const input = [2, 3, 5, 3, 4, 4, 4, 4, 5]
expect(findOdd(input)).toBe(2)
})
it('should return the correct integer', () => {
const input = [3, 3, 4, 5, 4, 5, 5]
expect(findOdd(input)).toBe(5)
})
it('should return the message if all integers appear an even number of times', () => {
const input = [1, 2, 1, 2, 3, 3, 6, 6, 6, 6]
expect(findOdd(input)).toBe('All integers appear an even number of times.')
})
})
const findOdd = (A) => {
const count = A.reduce((count, integer) => {
!count[integer] ? count[integer] = 1 : count[integer] += 1
return count
}, {})
const final = Object.keys(count).find(key => count[key] % 2 !== 0)
return parseInt(final) || 'All integers appear an even number of times.'
}
O(n^2), given there are two array iterator methods: reduce
and find
.
Considering the array could consist of an infinite number of integers, this solution should be refactored so that an object isn't created by reduce
; this object will take up too much space when the length of the input array is much larger than what's provided in these tests.