Skip to content

Instantly share code, notes, and snippets.

@p0rsche
Created January 30, 2023 10:02
Show Gist options
  • Save p0rsche/e3596ffa358b41233863fd7fb1bdcedd to your computer and use it in GitHub Desktop.
Save p0rsche/e3596ffa358b41233863fd7fb1bdcedd to your computer and use it in GitHub Desktop.
Find unique number in the array of numbers where all except one have duplicates
/**
* Дан массив из чисел
* Все значения, кроме одного, повторяются.
* Найти уникальное значение за O(n).
* Известно, что уникальное значение одно и только одно
* Пример:
* Вход: [5,9,6,1,9,6,5]
* Выход: [1]
*
*/
// Решение с XOR показалось наиболее классным. Если нужен ответ в виде массива, просто поменяйте вывод функции
// Напомню про XOR: x ^ 0 = x, x ^ x = 0
const findUnique = a => a.reduce((acc, cur) => acc ^ cur)
console.log(findUnique([5,9,6,1,9,6,5]))
// 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment