1 minute read

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.

Example 1:

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

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

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

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function (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;
};

The function uses two nested loops to compare each element in the array with all subsequent elements. The first loop (indexed by i) iterates through each element in the array.

The second loop (indexed by j) starts from the next element after the current element i and iterates through the remaining elements of the array. This ensures that each element is compared with all subsequent elements in the array to check for duplicates.

Inside the inner loop, the function checks if the element at index i is equal to the element at index j. If a duplicate is found (i.e., two elements with the same value exist), the function immediately returns true, indicating that the array contains duplicates.

If the function completes both loops without finding any duplicates, it means that the array contains no duplicate elements, and it returns false.

Leave a comment