Статья пока доступна только на английском.
Problem Description
You are given an integer array.
Write a function that takes the array and returns true if any value appears in it more than once.
If every value in the array is unique, the function should return false.
Constraints
- The array contains from 1 to 105 elements
- Each value is in the range from -109 to 109
Examples
Input: [1, 2, 3, 1]
Answer: true
Hash Map approach
With this approach it's enough to iterate over all elements of the array once.
On each iteration we keep track of the values we have already seen.
A Hash Map works well for this:
- if the map doesn't contain the value yet, we add it and move on to the next iteration;
- if the map already contains the value, we stop and return
true.
export const containsDuplicateWithMap = (nums: number[]): boolean => {
const frequency: Map<number, boolean> = new Map();
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (frequency.has(num)) {
return true;
}
frequency.set(num, true);
}
return false;
};Complexity Analysis
Time Complexity
O(n), where n is the number of elements in the array, since in the worst case we loop over all of them.
Space Complexity
O(n), since we allocate a map to store the values.
Sorting approach
With this approach we first sort the array in any order.
Since equal values always end up next to each other in a sorted array, we just need to walk through the array and return true as soon as we see two equal neighbouring values.
export const containsDuplicateWithSort = (nums: number[]): boolean => {
nums.sort();
for (let i = 0; i < nums.length - 1; i++) {
if (nums[i] === nums[i + 1]) {
return true;
}
}
return false;
};Complexity Analysis
Time Complexity
The complexity of the algorithm equals the complexity of sorting, since it is higher than linear: O(n * log n).
Space Complexity
O(1), since we don't allocate additional memory.