mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
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>
This commit is contained in:

committed by
GitHub

parent
4fe8a67ea6
commit
f5188ddf16
13
Bit-Manipulation/UniqueElementInAnArray.js
Normal file
13
Bit-Manipulation/UniqueElementInAnArray.js
Normal file
@ -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
Bit-Manipulation/test/UniqueElementInAnArray.test.js
Normal file
10
Bit-Manipulation/test/UniqueElementInAnArray.test.js
Normal file
@ -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)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user