2023-04-01

 01 Apr 2023

Use a Set to decide whether an Array of Numbers has any Duplicates

Taken from Execute Program

Write a hasDuplicates function. It should use a set to decide whether an array of numbers has any duplicates. It should return true if there are duplicates; otherwise it should return false.

Solution

This is the answer I came up with:

function hasDuplicates(numbers: Array<any>) {
  let tempSet = new Set()
  for (let number of numbers) {
    if (tempSet.has(number)) {
      return true
    }
    tempSet.add(number)
  }
  return false
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?ssl=10&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABACwIYGcAiIAOAbGCVKAU3QAowQBbAIxICd0AuRAQQYdQE8AeVMNwB8ASkQBvAFCJEeElESlqOAMrzEAXkRgSAd0Rqo5EdMTA4DROTkKqdRojjBtNekzFSZMmM-JLV8gB0aBR2biIepl6IDPIgDEhQDCAkUYgAvmn+hoGoACZ5lK6MJjKZMrFQ8UjAqHjoqZmSEAjocHKBeHAA5uSmIdj4hMRk5ADaAIwADAA0iABMswtLAMxTALomYgD024rJqUA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated October 9, 2024 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems