explained
September 23, 2024

Contains Duplicate


Here we gonna explain how to resolve the issue which is called Contains Duplicate. The problem is marked as ease and exactly it is. Make long story short, we have to follow these steps for resolving this problem:

  • We will use a hashset structure for tracking existed values;
  • Then: we need to iterate throught the data’s array;
  • Then: on each iteration check whether value exists in hashset or not;
  • If it does, that means that the value has already been added to our structure before. This is a duplicate. We should return false;
  • If it doesn’t exist, that means that the value hasn’t been added before. This isn’t a duplicate. We should add the value into hashset.

Basically that’s it. So let’s do some code relying on steps which have been described above. We will use Python programming language by the way.

def containsDuplicate(nums):
  hashset = set()
  
  for num in nums:
    if num in hashset:
      return True
    hashset.add(num)
  
  return False

Time complexity: O(n);
Space complexity: O(n).

Pretty ease, isn't it?