hasDuplicate

Easy · Data Structures · 4 test cases

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Examples

hasDuplicate([1, 2, 3, 1]) → true
hasDuplicate([1, 2, 3, 4]) → false
hasDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]) → true

Starter code

function hasDuplicate(nums) {

}

Complexity of the optimal solution

Time O(n), space O(n). Creating a `Set` from an array of n elements takes O(n) time, as each element is inserted into the hash set. The space required for the Set is also O(n) in the worst case (all unique elements).

Solve hasDuplicate in the browser