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.
1function containsDuplicate(nums) {
2 let seen = new Set();
3 for (let num of nums) {
4 if (seen.has(num)) {
5 return true;
6 }
7 seen.add(num);
8 }
9 return false;
10}
The JavaScript implementation uses a Set, which offers easy and fast insertion and lookup of numbers. As we loop through the array, we check each number and return true immediately if a duplicate is found.
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.
1function containsDuplicate(nums) {
2 nums.sort((a, b) => a - b);
3 for (let i = 0; i < nums.length - 1; i++) {
4 if (nums[i] === nums[i + 1]) {
5 return true;
6 }
7 }
8 return false;
9}
JavaScript's sort method is used, followed by a check through the sorted array to locate duplicates adjacent to each other.