Skip to content

Instantly share code, notes, and snippets.

@ShilpiMaurya
Last active November 23, 2020 12:47
Show Gist options
  • Save ShilpiMaurya/7ad744f8f5d10a5dd5256d9361c80d6d to your computer and use it in GitHub Desktop.
Save ShilpiMaurya/7ad744f8f5d10a5dd5256d9361c80d6d to your computer and use it in GitHub Desktop.
//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"
})`
);
});
@ShilpiMaurya
Copy link
Author

Thank you.

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