DEV Community


Posted on

Contains Duplicate

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct

Brute Force Approach
Time Complexity : O(n^2)
Space Complexity : O(1)

Sort Approach
Time Complexity : O(nlogn)
Space Complexity : O(1)

Optimized Approach via hash

var containsDuplicate = function (nums) {
    let hashMap = {};
    for (let num of nums) {
        if (num in hashMap) {
            return true;
        hashMap[num] = 1;
    return false;
Enter fullscreen mode Exit fullscreen mode

Time Complexity : O(n)
Space Complexity : O(n)

Top comments (0)