Contains Duplicate

Adiam AhmedAdiam Ahmed
5 min read

Problem Statement

Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.

Input: An array of integers nums

Output: Return true if any number appears more than once. Otherwise, return false.

Example 1:

Input: nums = [1, 2, 3, 3]
Output: true

Example 2:

Input: nums = [1, 2, 3, 4]
Output: false

Before Coding: Think Like a Human

Imagine someone hands you a list of numbers and asks:

"Are there any duplicates here?"

A human approach:

  • Look at the first number.

  • Check if it appears again in the list.

  • Repeat this for each number.

  • If a duplicate is found, say true.

  • If none are found, say false.

This intuitive idea leads us to different solutions. Let's walk through them.

đź§  Whiteboard Thinking

Before writing a single line of code, let’s think on paper:

  1. Understand the Problem
    Given an array of integers, return true if any number appears more than once. Otherwise, return false.

  2. Clarify the Input/Output

    • Input: An array of integers nums

    • Output: A boolean (true or false)

  3. Edge Cases to Consider

    • Empty array → [] should return false

    • Array with one element → [1] should return false

    • Large arrays with many duplicates

    • Negative numbers and zeros

  4. Pseudocode

    Pseudocode is a way to describe an algorithm or program in a way that's easy for humans to understand, even if they're not programmers. It's a step-by-step outline using plain English, without needing specific programming language syntax. It's often used to plan out an algorithm before writing actual code, acting as a blueprint or rough draft.

1. Brute Force Approach

So lets go start with a straightforward, exhaustive approach to solving a problem. The term is called "Brute Force" because it relies on raw computing power rather than elegant logic or efficiency, like forcing your way through a locked door instead of picking the lock. In this problem.

Comparing every pair of elements is called brute force because it's the most direct and uninformed way to solve the problem:

  • You don’t skip any combinations.

  • You don’t use any insights about the data.

  • You just try everything until you find a result.

Think of it like this:

Imagine you're looking for a matching sock in a huge pile. You’re not sorting them by color or organizing them in any way—you just compare each sock with every other sock, one by one.

Even to a human, this would exert a lot of effort. Now imagine doing this with millions of socks—or millions of integers. In programming, this is what brute force looks like.

function containsDuplicate(nums){
    for(let i = 0 ; i < nums.length; i++){
        for(let j = i + 1 ; j < nums.length; j++){
            if(nums[i] === nums[j]){
                return true;
        }
    }
    return false;
}

Time Complexity: n(n - 1)/2 → O(n²)
Space Complexity: O(1) (constant space)
Why not to Use: This becomes slow when the array contains thousands or millions of elements.

2. Sorting Approach

Speaking of socks and sorting, a natural next step is to sort the array and then check for duplicates by looking at consecutive numbers—simple and effective. The thought process might go something like this: “If I sort the list, then any duplicates will end up next to each other. So I just need to compare each number with the one right after it.”

Now, if you search for how to sort an array in JavaScript (via Google or ChatGPT), you’ll quickly find that Array.prototype.sort() exists. However, by default, it doesn’t sort numbers the way you'd expect. Instead, it converts elements to strings and sorts them lexicographically (dictionary order), which can lead to incorrect results when working with numbers.

  •         function containsDuplicate(nums) {
              nums.sort((a, b) => a - b);
              for (let i = 0; i < nums.length - 1 ; i++) { //here we use nums.length - 1 
                if (nums[i] === nums[i + 1]) {             //would go out of bounds on the last iteration.
                  return true;
                }
              }
              return false;
            }
    

    Time Complexity: O(n log n)
    Space Complexity: O(1) or O(n) depending on the sort algorithm
    When to Use: If you are allowed to modify the array and want a one-pass check after sorting.

3. Using a Set (Most Efficient and Idiomatic in JS)

  • A Set in JavaScript is a built-in object that only stores unique values. This makes it perfect for detecting duplicates: if you try to add a number that’s already in the set, you’ve found a duplicate!

    It’s fast—checking if a value exists in a set and adding a value both take constant time, O(1).
    So overall, this method runs in O(n) time and uses O(n) space, making it the most efficient and readable approach in JavaScript.

  •       function containsDuplicate(nums) {
            const seen = new Set();
            for (let i = 0; i < nums.length; i++) {
              if (seen.has(nums[i])) return true;
              seen.add(nums[i]);
            }
            return false;
          }
    

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

    When to Use: Most of the time. Fast, readable, and elegant.

Final Thoughts

The Set-based solution is usually the best choice in JavaScript for its clarity and performance. However, understanding all three helps you appreciate algorithmic thinking and make better trade-offs in interviews and real-world coding.

0
Subscribe to my newsletter

Read articles from Adiam Ahmed directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Adiam Ahmed
Adiam Ahmed