Skip to content
20 changes: 20 additions & 0 deletions Bit-Manipulation/UniqueElementInAnArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
Problem Statement :

author : @dev-madhurendra

Question : https://leetcode.com/problems/unique-number-of-occurrences/

a) This algo works if all the element is repeating
twice except one element.

Explanation :
[1,2,1,2,3]
a) Basic thing is a^a (a xor a) = 0
b) So if we do like
1^2^1^2^3 => (1^1)^(2^2)^3 => 0^0^3 => 3
*/

const UniqueElementInAnArray = (arr) => arr.reduce((acc, val) => acc ^ val, 0)

export { UniqueElementInAnArray }
10 changes: 10 additions & 0 deletions Bit-Manipulation/test/UniqueElementInAnArray.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { UniqueElementInAnArray } from '../UniqueElementInAnArray'

describe('UniqueElementInAnArray', () => {
it.each([
[[1, 2, 1, 3, 3], 2],
[[1, 2, 3, 4, 5, 4, 3, 2, 1], 5]
])('should return an unique element from an array', (arr, expected) => {
expect(UniqueElementInAnArray(arr)).toBe(expected)
})
})