From f5188ddf16ae0e0e2cb300e3749ab37fbda042af Mon Sep 17 00:00:00 2001 From: Madhurendra Nath Tiwari <68775519+dev-madhurendra@users.noreply.github.com> Date: Fri, 22 Sep 2023 14:52:11 +0530 Subject: [PATCH] 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 --- Bit-Manipulation/UniqueElementInAnArray.js | 13 +++++++++++++ .../test/UniqueElementInAnArray.test.js | 10 ++++++++++ 2 files changed, 23 insertions(+) create mode 100644 Bit-Manipulation/UniqueElementInAnArray.js create mode 100644 Bit-Manipulation/test/UniqueElementInAnArray.test.js diff --git a/Bit-Manipulation/UniqueElementInAnArray.js b/Bit-Manipulation/UniqueElementInAnArray.js new file mode 100644 index 000000000..74b5fe95a --- /dev/null +++ b/Bit-Manipulation/UniqueElementInAnArray.js @@ -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 } diff --git a/Bit-Manipulation/test/UniqueElementInAnArray.test.js b/Bit-Manipulation/test/UniqueElementInAnArray.test.js new file mode 100644 index 000000000..4aa66bc8b --- /dev/null +++ b/Bit-Manipulation/test/UniqueElementInAnArray.test.js @@ -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) + }) +})