Skip to content

Commit dfa3896

Browse files
rnema19rnema19
authored andcommitted
added new algorithm/problem in Array-DS
1 parent 08d8c6b commit dfa3896

File tree

3 files changed

+37
-12
lines changed

3 files changed

+37
-12
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/** https://leetcode.com/problems/single-number/description/
2+
* This function will accept an array and
3+
* Find an element which has only one frequency among other duplicate elements
4+
* 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
5+
* @param {Array} arr array with elements of integer type
6+
* @returns {Number} with single element
7+
*/
8+
9+
function SingleElement(arr) {
10+
let n = arr.length
11+
for (let i = 0; i < n; i++) {
12+
let count = 0
13+
// previous elements are already checked
14+
for (let j = 0; j < n; j++) {
15+
if (arr[j] === arr[i]) {
16+
count++
17+
}
18+
}
19+
if (count === 1) {
20+
return arr[i]
21+
}
22+
}
23+
}
24+
25+
export { SingleElement }
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { SingleElement } from '../SingleElement'
2+
3+
describe('single element in an array of duplicates', () => {
4+
test.each([
5+
[[1, 2, 2, 3, 3], 1],
6+
[[8, 9, 7, 2, 1, 5, 6, 4, 5, 9, 8, 7, 2, 6, 1], 4],
7+
[[10, 8, 5, 6, 8, 5, 6, 10, 11], 11]
8+
])('returns %p when given %p', (array, expected) => {
9+
expect(SingleElement(array)).toBe(expected)
10+
})
11+
})

package-lock.json

Lines changed: 1 addition & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)