Skip to content

Commit

Permalink
added an algo which finds unique element in an array (#1359)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
dev-madhurendra and madhuredra authored Sep 22, 2023
1 parent 4fe8a67 commit f5188dd
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Bit-Manipulation/UniqueElementInAnArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Finds the unique element in an array where all other elements are repeated twice.
*
* @param {number[]} arr - The input array of integers.
* @returns {number} The unique element.
*
* @example
* const arr = [1, 2, 1, 2, 3];
* const uniqueElement = findUniqueElement(arr); // Returns 3
*/
const findUniqueElement = (arr) => arr.reduce((acc, val) => acc ^ val, 0)

export { findUniqueElement }
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 { findUniqueElement } 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(findUniqueElement(arr)).toBe(expected)
})
})

0 comments on commit f5188dd

Please sign in to comment.