DEV Community

Dumb Down Demistifying Dev
Dumb Down Demistifying Dev

Posted on

Duplicate Arguments

Given N number of arguments, write a function CheckArgsDuplicates to determine if its arguments have any duplicate.

Thoughts:

  • One-liner in JavaScript does exist for such question
  • Since it is not needed to count the number of duplicates, once it exist in the hash we return true
// Time complexity - O(n)
// Space complexity - O(n)
function CheckArgsDuplicates(...args) {
    const argumentz = [...args];
    const argsLength = argumentz.length;

    let argCounter = {};
    for (let i=0; i<argsLength; i++) {
        if (argCounter[argumentz[i]]) return true;
        argCounter[argumentz[i]] = 1;
    }

    return false;
}

// one-liner solution which should only be used as naive solution
function CheckArgsDuplicates(...args) {
    return Array.from(new Set(args)).length !== args.length;
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)