From 0816bfcddd782fe3a9933b3ae8cc397fc9b8b456 Mon Sep 17 00:00:00 2001 From: Pranav Rustagi <57594891+Pranav-Rustagi@users.noreply.github.com> Date: Wed, 12 Oct 2022 06:55:25 +0530 Subject: [PATCH] chore(Javascript): single occurring element among duplicates (#969) --- algorithms/JavaScript/README.md | 1 + .../src/arrays/single-occurring-element.js | 18 ++++++++++++++++++ algorithms/JavaScript/src/index.js | 1 + 3 files changed, 20 insertions(+) create mode 100644 algorithms/JavaScript/src/arrays/single-occurring-element.js diff --git a/algorithms/JavaScript/README.md b/algorithms/JavaScript/README.md index 7222c11a..56159de7 100644 --- a/algorithms/JavaScript/README.md +++ b/algorithms/JavaScript/README.md @@ -3,6 +3,7 @@ ## Arrays - [Counting Inversions](src/arrays/counting-inversions.js) +- [Single Occurring Element](src/arrays/single-occurring-element.js) ## Linked Lists diff --git a/algorithms/JavaScript/src/arrays/single-occurring-element.js b/algorithms/JavaScript/src/arrays/single-occurring-element.js new file mode 100644 index 00000000..1c8da89d --- /dev/null +++ b/algorithms/JavaScript/src/arrays/single-occurring-element.js @@ -0,0 +1,18 @@ +// Problem: Given an array of integers, +// every element appears twice except for one. Find that single one. +// Space Complexity: O(1) +// Time Complexity: O(n) + +function singleOccurringElement(arr) { + let result = 0; + for (const el of arr) { + result ^= el; + } + return result; +} + +const arr = [2, 5, 7, 3, 1, 8, 8, 9, 4, 2, 7, 1, 4, 9, 5]; +console.log(singleOccurringElement(arr)); + +// Input: [2, 5, 7, 3, 1, 8, 8, 9, 4, 2, 7, 1, 4, 9, 5] +// Output: 3 diff --git a/algorithms/JavaScript/src/index.js b/algorithms/JavaScript/src/index.js index a599f73b..5264890b 100644 --- a/algorithms/JavaScript/src/index.js +++ b/algorithms/JavaScript/src/index.js @@ -1,5 +1,6 @@ // Arrays require('./arrays/counting-inversions'); +require('./arrays/single-occurring-element'); // Linked Lists require('./linked-lists/singly');