Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//In an array 1-100 exactly one number is duplicate how do you find it?
const findOneDuplicateNum = arr => {
if (!Array.isArray(arr) || !arr.length) {
return null;
}
let count = {};
for (let i = 0; i < arr.length; i++) {
if (count[arr[i]]) {
return arr[i];
} else {
count[arr[i]] = true;
}
}
return null;
};
//Time-complexity: O(n)
//test cases
const testCase = [
{ input: [], output: null },
{ input: ["a", "b", "c"], output: null },
{ input: "engimatic", output: null },
{ input: [1, 2, 3, 4, 5, 2, 6], output: 2 },
{ input: [1, 2, 3, 4, 5, 3, 6], output: 3 },
{ input: [1, 2, 3, 4, 5, 6, 6], output: 6 },
{ input: [1, 1, 3, 4, 5, 2, 6], output: 1 }
];
testCase.forEach(({ input, output }, index) => {
console.log(
`TEST CASE:${index} (${input}):(${
findOneDuplicateNum(input) === output ? "success" : "failure"
})`
);
});
@vaibhav-kumar-tokyo

This comment has been minimized.

Copy link

@vaibhav-kumar-tokyo vaibhav-kumar-tokyo commented Nov 21, 2020

Perfect!

@ShilpiMaurya

This comment has been minimized.

Copy link
Owner Author

@ShilpiMaurya ShilpiMaurya commented Nov 23, 2020

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment