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:

// typescript

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

Webmentions & Comments

Copyright © Paramdeo Singh · Built with Jekyll in 🇬🇾 · All Rights Reserved

[ this node is permanently morphing last updated on 28 May 2023 ]

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