-
-
Save jsstrn/35e747d0fbb8d7a2d2394b23540489c0 to your computer and use it in GitHub Desktop.
Write a function that checks if an array has duplicate values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function hasDuplicateValue(array) { | |
let counter = 0 | |
for (let i = 0; i < array.length; i++) { | |
for (let j = 0; j < array.length; j++) { | |
counter++ | |
if (i !== j && array[i] === array[j]) { | |
return true | |
} | |
} | |
} | |
console.log('number of steps', counter) | |
return false | |
} | |
hasDuplicateValue([1, 2, 3, 5, 9]) | |
// O(n^2) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function hasDuplicateValue(array) { | |
const set = new Set() | |
let counter = 0 | |
array.forEach((element) => { | |
counter++ | |
set.add(element) | |
}) | |
if (set.size !== array.length) { | |
return true | |
} | |
console.log('number of steps', counter) | |
return false | |
} | |
hasDuplicateValue([3, 2, 1, 5, 6]) | |
// O(2n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment