Contains Duplicate - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Goal

Given an array of integers, determine whether any value appears at least twice.

Key Idea (Intuition)

Checking against the previously seen numbers is enough: if the current number has been seen before, we have found a duplicate. Passing a number once does not mean it cannot be a duplicate — we may still encounter it later, and when that happens, the new number is checked against all those seen earlier and the duplicate will be detected. To enable this, we maintain a set seenNums of numbers encountered so far and check in constant time whether the current number has already been seen.

Traversal

Iterate through the array from left to right, examining one number at a time.

Per-Iteration Logic

  1. Duplicate check: If the current number is already in seenNums, return true immediately.
  2. Record as seen: Otherwise, add the current number to seenNums and continue.

Return

If the loop finishes without finding a repeated number, return false.

Time Complexity

The array is traversed once from left to right. At each iteration, checking whether a number is in seenNums and adding a number to seenNums both take amortized constant time. Therefore, the overall time complexity is O(n), where n is the number of elements in the array.

Space Complexity

The algorithm uses a set seenNums to store previously encountered numbers. In the worst case, if all numbers are distinct, the set grows to the size of the array. Therefore, the space complexity is O(n).

Visucodize editorial solution titled JS Solution for LeetCode's Contains Duplicate coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/contains-duplicate.