Skip to content

Instantly share code, notes, and snippets.

@k0ff33
Last active March 30, 2022 15:59
Show Gist options
  • Save k0ff33/3eb60cfb976dee0a0a969fc9f84ae145 to your computer and use it in GitHub Desktop.
Save k0ff33/3eb60cfb976dee0a0a969fc9f84ae145 to your computer and use it in GitHub Desktop.
Odd Occurrences In Array exercise from Codility (JavaScript/NodeJS)
/**
* Finds element without a pair in an unsorted array of integers
* @param {array} A
* @return {int} element without a pair
*/
function solution(A) {
let result = 0;
for (let element of A) {
// Apply Bitwise XOR to the current and next element
result ^= element
}
return result
}
// =======================
// SLOW
// =======================
function slowSolution(A) {
// Convert the array to a map with element as a key and number of occurrences as a value
// Example: { '3': 2, '7': 1, '9': 4 }
let map = A.reduce((map, obj) => {
map[obj] = ++map[obj] || 1
return map
}, {})
// Then filter the map by checking if the key's value is equal to 1
// Returns array with key
let filteredArr = Object.keys(map).filter(el => map[el] === 1)
return +filteredArr[0] || null
}
@RomaSto
Copy link

RomaSto commented Aug 26, 2020

Correct solution with O(n) complexity

function solution(A) {
    let map = A.reduce((map, obj) => {
        map[obj] = ++map[obj] || 1
        return map
    }, {})
    
    let filteredArr = Object.keys(map).filter(el => map[el] %2)
    return  +filteredArr[0] 
}

@kumail-raza
Copy link

kumail-raza commented Oct 25, 2020

@RomaSto

Just want to know how is your solution better from @Edengb? Using filter which will also going to iterate through the array. !!

And what difference you both provide from the initial solution as slowSolution?

Please elaborate either of you. Thanks

@yamankatby
Copy link

yamankatby commented Aug 4, 2021

Fast and understandable 🤯 solution.

function solution(A) {
  A = A.sort();

  let val = A[A.length - 1];
  for (let i = 0; i < (A.length - 1) / 2; i++) {
    if (A[i * 2] !== A[i * 2 + 1]) {
      val = A[i * 2];
      break;
    }
  }
  return val;
}

@SalahAdDin
Copy link

SalahAdDin commented Jan 8, 2022

@k0ff33 I can't figure out how Bitwise XOR operator does work.
@RomaSto It is still O(N**2).

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