utopia logo
Blog / Leetcode: 217. Contains Duplicate

Leetcode: 217. Contains Duplicate

217. Contains Duplicate

blind75
leetcode
KJ

KJ

Author

Published 6th July, 2025

Leetcode: 217. Contains Duplicate

Problem

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.

First thoughts

This is practically identical to Two Sum. Except we're returning True or False. We just iterate through the list, keep track of the numbers we've encountered. If we encounter it again, then return True. Else False.

Using this logic got to the solution first try:

python

Refining logic

I used enumerate here out of habit. We actually don't need to store the index, as knowing where the number is is less important than what. Index here is redundant.

Because of this, we can simply use a set. It is a dictionary without keys, and great for storing unique items and checking membership quickly:

Solution

python

There are other ways to solve this. For example we could sort the array first, and if there are duplicates they will be next to each other. While this makes our space complexity O(1), out time complexity grows to O(n logn).

Another way is, since sets can't contain duplicates by definition, you can simply compare the length of the original list to the length of a set made from that list. A simple one liner return len(set(nums)) != len(nums) will work fine.

Time and space

Time complexity: O(n)

This is because we iterate through the input array once. Checking whether an item is in a set, and adding to a set, is O(1). Doing that over the entire array would be O(n).

Space complexity: O(n)

This is because of our seen set. Worst case scenario we add our entire array to it if we don't find anything.

For the future

If existence is the only thing we need to check, a set is fine. For where an item is, dict.

utopia logo

Footer stuff...

I'll put what you typically put in footers here soon.