Skip to content

Instantly share code, notes, and snippets.

@jsstrn
Created May 2, 2019 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsstrn/35e747d0fbb8d7a2d2394b23540489c0 to your computer and use it in GitHub Desktop.
Save jsstrn/35e747d0fbb8d7a2d2394b23540489c0 to your computer and use it in GitHub Desktop.
Write a function that checks if an array has duplicate values
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)
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