Skip to content

Instantly share code, notes, and snippets.

@nicolegooden
Last active January 31, 2021 21:41
Show Gist options
  • Save nicolegooden/5ccd5122ff6ed7d6454bd9400b90c951 to your computer and use it in GitHub Desktop.
Save nicolegooden/5ccd5122ff6ed7d6454bd9400b90c951 to your computer and use it in GitHub Desktop.
Codewars

REPL

https://repl.it/join/aczpcaoo-nicolegooden

Challenge

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.

Tests (Jest)

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.')
  })
})

Solution

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.'
}

Big O Notation

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment