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
Explanation:
The element 1 occurs at the indices 0 and 3.
Example 2:
Input: nums = [1,2,3,4]
Output: false
Explanation:
All elements are distinct.
Example 3:
Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force way to check for duplicates is very straightforward. It involves comparing each item in the collection to every other item. If we find two identical items, we know there's a duplicate.
Here's how the algorithm would work step-by-step:
def contains_duplicate_brute_force(numbers):
list_length = len(numbers)
for first_index in range(list_length):
first_number = numbers[first_index]
# Compare the first number with the rest of the numbers in the list
for second_index in range(first_index + 1, list_length):
second_number = numbers[second_index]
# Check if the numbers are the same
if first_number == second_number:
# Found a duplicate, so we can return True immediately
return True
# No duplicates were found after checking all pairs
return False
The core idea is to efficiently remember if we've seen a number before. Instead of comparing each number to every other number, we use a tool to keep track of numbers we've already encountered, making the process much faster.
Here's how the algorithm would work step-by-step:
def containsDuplicate(numbers):
seen_numbers = set()
for number in numbers:
# Check if the current number exists in seen_numbers.
if number in seen_numbers:
return True
# Add number to seen_numbers set.
seen_numbers.add(number)
return False
Case | How to Handle |
---|---|
Null or empty input array | Return false immediately since an empty array cannot contain duplicates. |
Array with only one element | Return false because a single element cannot be a duplicate of itself. |
Array with all identical elements | The solution should correctly identify the presence of duplicates and return true. |
Array with a very large number of elements (performance) | Using a hash set provides O(n) time complexity which scales well for large inputs. |
Array containing only negative numbers | The solution should handle negative numbers correctly; a hash set works regardless of number sign. |
Array containing a mix of positive, negative, and zero values | The solution must correctly handle a mix of different number types without issues. |
Array contains integer overflow values (Integer.MAX_VALUE, Integer.MIN_VALUE) | The hash set should be able to store and compare extreme integer values correctly. |
Array contains duplicate entries of Integer.MAX_VALUE or Integer.MIN_VALUE | Hash set handles the duplicates of boundary integers correctly. |