HomeLeetcode217. Contains Duplicate (Hash Table) - Leetcode Solutions

217. Contains Duplicate (Hash Table) – Leetcode Solutions

Description:

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.

Examples:

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

Solution in Python:

Python
from typing import List

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        # Initialize a set to keep track of seen numbers
        seen = set()
        
        # Iterate through each number in the array
        for num in nums:
            # If the number is already in the set, we found a duplicate
            if num in seen:
                return True
            # Otherwise, add the number to the set
            seen.add(num)
        
        # If no duplicates were found, return False
        return False

# Example usage
sol = Solution()
print(sol.containsDuplicate([1, 2, 3, 1]))  # Output: True
print(sol.containsDuplicate([1, 2, 3, 4]))  # Output: False
print(sol.containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]))  # Output: True

Explanation:

  1. Initialization:
    • A set named seen is initialized to keep track of the numbers that have been encountered as we iterate through the array. Sets are used because they provide an average-case time complexity of O(1) for both insertions and lookups.
  2. Iteration:
    • We iterate through each number in the nums array.
  3. Checking for Duplicates:
    • For each number, we check if it is already in the seen set.
    • If it is, this means the number has appeared before, so we return True to indicate that there is at least one duplicate in the array.
    • If it is not in the set, we add the number to the seen set and continue iterating.
  4. Completion:
    • If the loop completes without finding any duplicates, we return False.

Example Execution:

  • For nums = [1, 2, 3, 1]:
    • Iteration 1: num = 1, seen = {1}
    • Iteration 2: num = 2, seen = {1, 2}
    • Iteration 3: num = 3, seen = {1, 2, 3}
    • Iteration 4: num = 1, since 1 is in seen, return True.
  • For nums = [1, 2, 3, 4]:
    • Iteration 1: num = 1, seen = {1}
    • Iteration 2: num = 2, seen = {1, 2}
    • Iteration 3: num = 3, seen = {1, 2, 3}
    • Iteration 4: num = 4, seen = {1, 2, 3, 4}
    • No duplicates found, return False.
  • For nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2]:
    • Iteration 1: num = 1, seen = {1}
    • Iteration 2: num = 1, since 1 is in seen, return True.

Solution in Javascript:

JavaScript
/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function(nums) {
    // Initialize a set to keep track of seen numbers
    let seen = new Set();
    
    // Iterate through each number in the array
    for (let num of nums) {
        // If the number is already in the set, we found a duplicate
        if (seen.has(num)) {
            return true;
        }
        // Otherwise, add the number to the set
        seen.add(num);
    }
    
    // If no duplicates were found, return false
    return false;
};

// Example usage
console.log(containsDuplicate([1, 2, 3, 1]));  // Output: true
console.log(containsDuplicate([1, 2, 3, 4]));  // Output: false
console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]));  // Output: true

Solution in Java:

Java
import java.util.HashSet;
import java.util.Set;

class Solution {
    public boolean containsDuplicate(int[] nums) {
        // Initialize a set to keep track of seen numbers
        Set<Integer> seen = new HashSet<>();
        
        // Iterate through each number in the array
        for (int num : nums) {
            // If the number is already in the set, we found a duplicate
            if (seen.contains(num)) {
                return true;
            }
            // Otherwise, add the number to the set
            seen.add(num);
        }
        
        // If no duplicates were found, return false
        return false;
    }

    // Example usage
    public static void main(String[] args) {
        Solution sol = new Solution();
        System.out.println(sol.containsDuplicate(new int[]{1, 2, 3, 1}));  // Output: true
        System.out.println(sol.containsDuplicate(new int[]{1, 2, 3, 4}));  // Output: false
        System.out.println(sol.containsDuplicate(new int[]{1, 1, 1, 3, 3, 4, 3, 2, 4, 2}));  // Output: true
    }
}

Solution in C#:

C#
using System;
using System.Collections.Generic;

public class Solution {
    public bool ContainsDuplicate(int[] nums) {
        // Initialize a HashSet to keep track of seen numbers
        HashSet<int> seen = new HashSet<int>();
        
        // Iterate through each number in the array
        foreach (int num in nums) {
            // If the number is already in the set, we found a duplicate
            if (seen.Contains(num)) {
                return true;
            }
            // Otherwise, add the number to the set
            seen.Add(num);
        }
        
        // If no duplicates were found, return false
        return false;
    }

}

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments

Popular