Skip to content

Contains Duplicate

Problem Statement

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. :contentReference[oaicite:1]1

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

Output: true

Solution

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function (nums) {
  let unique = {};

  for (let n of nums) {
    if (unique[n] == undefined) {
      unique[n] = 1;
    } else {
      return true;
    }
  }

  return false;
};

const nums = [1, 2, 3, 1];
const result = containsDuplicate(nums);
console.log(result);

Mermaid Test