Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Data-Structures/Array/SingleElement.js
Original file line number Diff line number Diff line change
@@ -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 }
11 changes: 11 additions & 0 deletions Data-Structures/Array/test/SingleElement.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
})
13 changes: 1 addition & 12 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.