This is my solution to a “Daily Coding Problem” and it’s one of the Facebook interview questions.

Given an array of integers in which two elements appear exactly once and all other elements appear exactly twice, find the two elements that appear only once.

For example, given the array `[2, 4, 6, 8, 10, 2, 6, 10]`, return `4` and `8`. The order does not matter.

Follow-up: Can you do this in linear time and constant space?

Here’s my solution in Typescript.

``````class Codingproblems {

oneForty(arr: Array<number>) {
let dupArry = new Array<number>();
let valMap = new Map<number, number>();
arr.forEach((val, idx, array) => {
let count = valMap.get(val);
if(count != null && count != undefined) {
valMap.set(val, count + 1);
} else {
valMap.set(val, 1);
}
});
valMap.forEach((val:number, key: number) => {
if(val == 1) {
dupArry.push(key);
}
});
console.log(dupArry);
}
oneFortyEfficient(arr: Array<number>) {
let valMap = new Map<number, number>();
arr.forEach((val, idx, array) => {
if(valMap.has(val)) {
//delete the key
valMap.delete(val);
} else {
valMap.set(val, 1);
}
});
console.log(valMap.keys());
}
}

let cp = new Codingproblems();
cp.oneForty([2, 4, 6, 8, 10, 2, 6, 10]);
cp.oneFortyEfficient([2, 4, 6, 8, 10, 2, 6, 10]);``````

If you know a more optimal solution to this then please let me know. I suppose, the second solution could be better? Maybe leave a comment and let me know how to improve it.

#### Like the blog? Subscribe for updates

As usual, if you find any of my posts useful support me by  buying or even trying one of my apps on the App Store.

My apps: https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.

Categories: Algorithms