Problem at: Contains Duplicate

Intuition

Keywords: duplicate

This can be solved with a set or a HashMap. By keeping track and recording of each number in the array, we can check if we have met the number before.

If we have not met the number before, add it to the set. Otherwise, return True, ending the loop. If all the numbers are unique, return False.

Test Cases

Case 1

nums = [1,2,3,1]

StepActionResult
1Add 1 to the hashmapFalse
2Add 2 to the hashmapFalse
3Add 3 to the hashmapFalse
41 is in the hashmapTrue, end the loop

Case 2

nums = [1,1,1,3,3,4,3,2,4,2]

StepActionResult
1Add 1 to the hashmapFalse
21 is in the hashmapTrue, end the loop

Code

The long way

def containsDuplicate(self, nums: List[int]) -> bool:
	numHash = set()
	for num in nums:
		if num in numHash:
			return True
		numHash.add(num)
	return False

Time complexity:

Space complexity:

The shortcut

def containsDuplicate(self, nums: List[int]) -> bool:
	return len(set(nums)) != len(nums)

Time complexity:

Space complexity: