Skip to content

Commit f5188dd

Browse files
dev-madhurendramadhuredra
and
madhuredra
authoredSep 22, 2023
added an algo which finds unique element in an array (#1359)
* added an algo which finds unique element in an array * fixed code style * updated changes and add some explanations * Delete package-lock.json * Delete package.json * added question link if anyone want to solve * updated changes * added package.json * used JSDoc comment --------- Co-authored-by: madhuredra <madhuredra.tiwari@zemosolabs.com>
1 parent 4fe8a67 commit f5188dd

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed
 

Diff for: ‎Bit-Manipulation/UniqueElementInAnArray.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* Finds the unique element in an array where all other elements are repeated twice.
3+
*
4+
* @param {number[]} arr - The input array of integers.
5+
* @returns {number} The unique element.
6+
*
7+
* @example
8+
* const arr = [1, 2, 1, 2, 3];
9+
* const uniqueElement = findUniqueElement(arr); // Returns 3
10+
*/
11+
const findUniqueElement = (arr) => arr.reduce((acc, val) => acc ^ val, 0)
12+
13+
export { findUniqueElement }

Diff for: ‎Bit-Manipulation/test/UniqueElementInAnArray.test.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { findUniqueElement } from '../UniqueElementInAnArray'
2+
3+
describe('UniqueElementInAnArray', () => {
4+
it.each([
5+
[[1, 2, 1, 3, 3], 2],
6+
[[1, 2, 3, 4, 5, 4, 3, 2, 1], 5]
7+
])('should return an unique element from an array', (arr, expected) => {
8+
expect(findUniqueElement(arr)).toBe(expected)
9+
})
10+
})

0 commit comments

Comments
 (0)