The problem
We are given an array nums. The array contains integers and we are asked to return true if the array contains duplicate integers. If the array contains only unique integers, we should return false.
For example, [1, 2, 3, 1] → true, because 1 appears twice, and [1, 2, 3, 4] → false, because every number is unique.
My first idea
We can approach this problem by looping through every pair of integers in the array and checking if they are equal. If they are equal, it means that there is at least one number that appears twice in the array. Then we can return true.
However, if we reach the end of the loops without finding a pair of numbers that are equal to each other, then we are sure that the array contains only unique integers and we can return false.
class Solution {
public boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
return true;
}
}
}
return false;
}
}
Below, I will leave some questions about this code. I encourage you to read them and try to answer them, as they will help you understand why this algorithm works.
- In the inner loop, why did we set the variable
jto bei + 1? Why notj = iorj = 0? - In the outer loop, what happens when
ireaches the end of the array (i = nums.length - 1)? Will the indexjgo out of bounds and make the program throwArrayIndexOutOfBoundsException?
Why it wasn’t enough
The above solution works. But the problem is that it becomes very slow as the size of the array becomes larger. Let’s try to analyze how many times the loops run for an array of size 3. For the first element, the inner loop runs 2 times, for the second element it runs once, and for the last element the inner loop doesn’t run. So in total, 2 + 1 = 3. Now let’s see what happens for an array of size 4. For the first element, the inner loop runs 3 times, for the second one 2 times, for the third one once, and for the last one the inner loop doesn’t run. So in total, 3 + 2 + 1 = 6. Now, do it for an array of size 5. Do you see the pattern? For an array of size n, the loops run (n-1) + (n-2) + … + 2 + 1 times in total.
There is a mathematical formula that gives the sum of such an expression: n(n-1)/2. After a bit of algebraic manipulation, we see that the sum is 0.5n² - 0.5n. If we put this expression into Big O notation, it becomes O(n²), because in Big O notation we always keep the highest power and discard the constants and the lower powers. So we are left with n² in this case. It means that our solution gets much slower as the array size grows.
Key insight 1: sort the array
I had the idea of sorting the whole array into ascending order. Actually, descending order also works fine. Why would I sort the array, and how would this help me solve this problem? Well, after sorting, all the duplicate values will be placed next to each other, so I will simply check if two adjacent elements are equal. If so, then we are sure that the array contains at least one duplicate and we return true.
Solution
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums); // this will sort the array into ascending order
for (int i = 1; i < nums.length; i++) {
if (nums[i - 1] == nums[i]) {
return true;
}
}
return false;
}
}
Complexity
- Time: O(n log n)
- Space: O(log n), or O(1) extra if you ignore the stack space the sort uses
Why is this solution better than the brute force approach we took above? Sorting takes O(n log n), because comparison sorts can’t do better than that. Then finding equal adjacent integers takes O(n). So the expression will be O(n log n + n). As I said above, we only keep the highest order term, which in this case is O(n log n). This complexity is better than O(n²).
What about space? In Java, Arrays.sort on an int[] uses Dual-Pivot Quicksort, which sorts in place but needs O(log n) space on the call stack for its recursion. So the space is O(log n), not quite O(1).
One more thing to keep in mind: Arrays.sort(nums) sorts the caller’s array. After our method returns, whoever passed nums in gets it back in a different order. On LeetCode this doesn’t matter, but in real code, changing an input you were only asked to inspect can surprise the caller. You can sort a copy instead (int[] copy = nums.clone();), at the cost of O(n) extra space.
Key insight 2: use a set
I could do even better by using the Set data structure. A set doesn’t keep duplicates, so it fits our problem perfectly. If I put every number from the array into a set, the duplicates get dropped. So if the set ends up with fewer elements than the array, some number must have appeared more than once.
Solution
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num);
}
return set.size() < nums.length;
}
}
My first version of this solution added every number to the set and then looped over the array again, checking set.contains(num). Can you see why that’s wrong? Every number was already added in the first loop, so contains is always true and the method returns true for any array that isn’t empty. Comparing the sizes is what actually tells us whether something was dropped.
Complexity
- Time: O(n)
- Space: O(n)
Let’s analyze the time and space complexity of this solution. The loop runs n times to populate the set, and each add takes O(1) on average. Calling size() takes O(1). So the runtime is O(n). Since we need to store the integer elements in the set, the space complexity is also O(n).
Key insight 3: stop at the first duplicate
Actually, I don’t have to put all the integer elements into the set first. The solution above always looks at the whole array, even if the duplicate is in the first two positions. I can finish the job early with a single loop. In that loop, I will first check if the integer is already present in the set. If it is, then we found a duplicate. If not, I will put it into the set.
Solution
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
if (set.contains(num)) {
return true;
}
set.add(num);
}
return false;
}
}
A small trick: set.add(num) returns false when the number is already in the set. So the check and the insert can be done in one step:
for (int num : nums) {
if (!set.add(num)) {
return true;
}
}
Complexity
- Time: O(n)
- Space: O(n)
The worst case is still O(n), when there is no duplicate at all, but now we can stop as soon as we find one.
What I learned
My take-away from this problem is to use the set data structure when I need to quickly check whether I have already seen an element. Adding to a HashSet and checking contains take O(1) on average. In the worst case, when many elements land in the same bucket, they can be slower, but for everyday inputs they are fast.
