From dfa3896c6296428b9f27891aac33da268b19b370 Mon Sep 17 00:00:00 2001 From: rnema19 Date: Wed, 22 Oct 2025 10:08:49 +0000 Subject: [PATCH] added new algorithm/problem in Array-DS --- Data-Structures/Array/SingleElement.js | 25 +++++++++++++++++++ .../Array/test/SingleElement.test.js | 11 ++++++++ package-lock.json | 13 +--------- 3 files changed, 37 insertions(+), 12 deletions(-) create mode 100644 Data-Structures/Array/SingleElement.js create mode 100644 Data-Structures/Array/test/SingleElement.test.js diff --git a/Data-Structures/Array/SingleElement.js b/Data-Structures/Array/SingleElement.js new file mode 100644 index 0000000000..5281c90617 --- /dev/null +++ b/Data-Structures/Array/SingleElement.js @@ -0,0 +1,25 @@ +/** https://leetcode.com/problems/single-number/description/ + * This function will accept an array and + * Find an element which has only one frequency among other duplicate elements + * The solution is based on using two loops, if the array is large, sorting or hashing is necessary, we can use XOR operator or sum method too + * @param {Array} arr array with elements of integer type + * @returns {Number} with single element + */ + +function SingleElement(arr) { + let n = arr.length + for (let i = 0; i < n; i++) { + let count = 0 + // previous elements are already checked + for (let j = 0; j < n; j++) { + if (arr[j] === arr[i]) { + count++ + } + } + if (count === 1) { + return arr[i] + } + } +} + +export { SingleElement } diff --git a/Data-Structures/Array/test/SingleElement.test.js b/Data-Structures/Array/test/SingleElement.test.js new file mode 100644 index 0000000000..81fdcf1ade --- /dev/null +++ b/Data-Structures/Array/test/SingleElement.test.js @@ -0,0 +1,11 @@ +import { SingleElement } from '../SingleElement' + +describe('single element in an array of duplicates', () => { + test.each([ + [[1, 2, 2, 3, 3], 1], + [[8, 9, 7, 2, 1, 5, 6, 4, 5, 9, 8, 7, 2, 6, 1], 4], + [[10, 8, 5, 6, 8, 5, 6, 10, 11], 11] + ])('returns %p when given %p', (array, expected) => { + expect(SingleElement(array)).toBe(expected) + }) +}) diff --git a/package-lock.json b/package-lock.json index 5c38ba06a8..6b61c5260c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -745,16 +745,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/node": { - "version": "20.11.6", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "undici-types": "~5.26.4" - } - }, "node_modules/@vitest/coverage-v8": { "version": "1.2.1", "dev": true, @@ -1909,8 +1899,7 @@ "version": "5.26.5", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/v8-to-istanbul": { "version": "9.2.0",