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.
1#include <vector>
2#include <unordered_set>
3bool containsDuplicate(std::vector<int>& nums) {
4 std::unordered_set<int> seen;
5 for (int num : nums) {
6 if (seen.find(num) != seen.end()) {
7 return true;
8 }
9 seen.insert(num);
10 }
11 return false;
12}
In the C++ solution, we make use of an unordered_set for efficient lookup. We iterate over the vector, check if the current number is in the set, and if not, insert it into the set. This allows for average O(1) performance for each operation.
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.
1import java.util.Arrays;
2public boolean containsDuplicate(int[] nums) {
3 Arrays.sort(nums);
4 for (int i = 0; i < nums.length - 1; i++) {
5 if (nums[i] == nums[i + 1]) {
6 return true;
7 }
8 }
9 return false;
10}
In this solution, Java's Arrays.sort() is used to sort the input array, lending itself to a linear scan strategy for duplicate detection.