[{"content":"The problem Problem on LeetCode ↗ Easy 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.\nFor example, [1, 2, 3, 1] → true, because 1 appears twice, and [1, 2, 3, 4] → false, because every number is unique.\nMy 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.\nHowever, 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.\nclass Solution { public boolean containsDuplicate(int[] nums) { for (int i = 0; i \u0026lt; nums.length; i++) { for (int j = i + 1; j \u0026lt; 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.\nIn the inner loop, why did we set the variable j to be i + 1? Why not j = i or j = 0? In the outer loop, what happens when i reaches the end of the array (i = nums.length - 1)? Will the index j go out of bounds and make the program throw ArrayIndexOutOfBoundsException? Why it wasn\u0026rsquo;t enough The above solution works. But the problem is that it becomes very slow as the size of the array becomes larger. Let\u0026rsquo;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\u0026rsquo;t run. So in total, 2 + 1 = 3. Now let\u0026rsquo;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\u0026rsquo;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) + \u0026hellip; + 2 + 1 times in total.\nThere 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.\nKey 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.\nSolution class Solution { public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); // this will sort the array into ascending order for (int i = 1; i \u0026lt; 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\u0026rsquo;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²).\nWhat 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).\nOne more thing to keep in mind: Arrays.sort(nums) sorts the caller\u0026rsquo;s array. After our method returns, whoever passed nums in gets it back in a different order. On LeetCode this doesn\u0026rsquo;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.\nKey insight 2: use a set I could do even better by using the Set data structure. A set doesn\u0026rsquo;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.\nSolution class Solution { public boolean containsDuplicate(int[] nums) { HashSet\u0026lt;Integer\u0026gt; set = new HashSet\u0026lt;\u0026gt;(); for (int num : nums) { set.add(num); } return set.size() \u0026lt; 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\u0026rsquo;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\u0026rsquo;t empty. Comparing the sizes is what actually tells us whether something was dropped.\nComplexity Time: O(n) Space: O(n) Let\u0026rsquo;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).\nKey insight 3: stop at the first duplicate Actually, I don\u0026rsquo;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.\nSolution class Solution { public boolean containsDuplicate(int[] nums) { HashSet\u0026lt;Integer\u0026gt; set = new HashSet\u0026lt;\u0026gt;(); 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:\nfor (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.\nWhat 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.\n","permalink":"https://shermuhammad.dev/posts/neetcode-contains-duplicate/","summary":"Three ways to check an array for duplicates in Java: brute force in O(n²), sorting in O(n log n), and a HashSet in O(n).","title":"Contains Duplicate"},{"content":"Hi, I\u0026rsquo;m Shermuhammad, a student at Inha University in Tashkent, Uzbekistan.\nI\u0026rsquo;m learning backend development with Java and Spring, and I practise algorithms on LeetCode. This blog is where I write down what I learn along the way: how things work under the hood, bugs I\u0026rsquo;ve chased down, and problems I\u0026rsquo;ve solved.\nYou can find me on GitHub, LinkedIn and LeetCode.\n","permalink":"https://shermuhammad.dev/about/","summary":"\u003cp\u003eHi, I\u0026rsquo;m Shermuhammad, a student at Inha University in Tashkent, Uzbekistan.\u003c/p\u003e\n\u003cp\u003eI\u0026rsquo;m learning backend development with Java and Spring, and I practise algorithms on LeetCode. This blog is where I write down what I learn along the way: how things work under the hood, bugs I\u0026rsquo;ve chased down, and problems I\u0026rsquo;ve solved.\u003c/p\u003e\n\u003cp\u003eYou can find me on \u003ca href=\"https://github.com/BigOtron\"\u003eGitHub\u003c/a\u003e, \u003ca href=\"https://www.linkedin.com/in/karimov-shermukhammad/\"\u003eLinkedIn\u003c/a\u003e and \u003ca href=\"https://leetcode.com/u/karimov_shermuhammad/\"\u003eLeetCode\u003c/a\u003e.\u003c/p\u003e","title":"About"}]