This approach leverages the properties of a HashSet (or similar data structures depending on the programming language), which allows for average O(1) time complexity for insertion and lookup operations. As you iterate over the array, you check if the current element is already in the HashSet. If it is, then a duplicate has been found, and you can return true immediately. If it’s not already in the HashSet, you add it. If no duplicates are found by the end of the array, you return false.
Time Complexity: O(n log n), due to the sorting step.
Space Complexity: O(1), no extra space required apart from sorting.
1def containsDuplicate(nums):
2 seen = set()
3 for num in nums:
4 if num in seen:
5 return True
6 seen.add(num)
7 return False
The Python solution also uses a set to efficiently check for duplicates. As we iterate, each element is checked against the set and added to it if it's not already present.
This approach involves sorting the array first, then checking for duplicates by comparing each element with its next neighbor. If duplicates exist, they will appear next to each other after sorting.
Time Complexity: O(n log n), due to sorting.
Space Complexity: O(1), aside from sorting in-place.
1#include <stdbool.h>
2#include <stdlib.h>
3int compare(const void *a, const void *b) {
4 return (*(int*)a - *(int*)b);
5}
6bool containsDuplicate(int* nums, int numsSize) {
7 qsort(nums, numsSize, sizeof(int), compare);
8 for (int i = 0; i < numsSize - 1; i++) {
9 if (nums[i] == nums[i + 1]) {
10 return true;
11 }
12 }
13 return false;
14}
Here, qsort is used to sort the array, which allows for efficient comparison of adjacent elements to find duplicates. This leverages sorting's ability to bring identical elements together.