{"id":3314,"date":"2023-06-26T12:01:36","date_gmt":"2023-06-26T06:31:36","guid":{"rendered":"https:\/\/www.interviewbit.com\/blog\/?p=3314"},"modified":"2023-06-26T12:01:38","modified_gmt":"2023-06-26T06:31:38","slug":"remove-duplicates-from-array","status":"publish","type":"post","link":"https:\/\/www.interviewbit.com\/blog\/remove-duplicates-from-array\/","title":{"rendered":"Remove Duplicates from Array"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"gutentoc tocactive nostyle\"><div class=\"gutentoc-toc-wrap\"><div class=\"gutentoc-toc-title-wrap\"><div class=\"gutentoc-toc-title\">Table Of Contents<\/div><div id=\"open\" class=\"text_open\">show<\/div><\/div><div id=\"toclist\"><div class=\"gutentoc-toc__list-wrap\"><ul class=\"gutentoc-toc__list\"><li><a href=\"#problem-statement\">Problem Statement<\/a><\/li><li><a href=\"#method---1-using-sorting\">Method &#8211; 1 (Using Sorting)<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#solution-1-using-extra-space\">Solution 1 (Using extra space)<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#cc-code\">C\/C++ Code<\/a><\/li><li><a href=\"#java-code\">Java Code<\/a><\/li><li><a href=\"#python-code\">Python Code<\/a><\/li><\/ul><li><a href=\"#solution-2-without-using-extra-space\">Solution 2 (Without using extra space)<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#cc-implementation\">C\/C++ Implementation<\/a><\/li><li><a href=\"#java-implementation\">Java Implementation<\/a><\/li><li><a href=\"#python-implementation\">Python Implementation<\/a><\/li><\/ul><\/ul><li><a href=\"#method---2-use-of-hashmaps\">Method &#8211; 2 (Use of HashMaps)<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#cc-code-for-hashmaps\">C\/C++ Code For HashMaps<\/a><\/li><li><a href=\"#java-code-for-hashmaps\">Java Code For HashMaps<\/a><\/li><li><a href=\"#python-code-for-hashmaps\">Python Code For HashMaps<\/a><\/li><\/ul><li><a href=\"#faqs\">FAQs<\/a><\/li><ul class=\"gutentoc-toc__list\"><li><a href=\"#q1-how-do-you-find-duplicates-in-an-array\">Q.1: How do you find duplicates in an array?<\/a><\/li><li><a href=\"#q2-how-do-you-remove-duplicates-from-an-unsorted-array-in-place\">Q.2: How do you remove duplicates from an unsorted array in place?<\/a><\/li><\/ul><\/ul><\/div><\/div><\/div><\/div>\n\n\n\n<h2 id=\"problem-statement\">Problem Statement<\/h2>\n\n\n\n<p>Given an array of integers, the task is to remove the duplicates from the array.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img  loading=\"lazy\"  width=\"1024\"  height=\"471\"  src=\"data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAP+KeNJXAAAAAXRSTlMAQObYZgAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=\"  alt=\"\"  class=\"wp-image-3319 pk-lazyload\"  data-pk-sizes=\"auto\"  data-ls-sizes=\"(max-width: 1024px) 100vw, 1024px\"  data-pk-src=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-15.png\"  data-pk-srcset=\"https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-15.png 1024w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-15-300x138.png 300w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-15-768x353.png 768w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-15-380x175.png 380w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-15-550x253.png 550w, https:\/\/www.interviewbit.com\/blog\/wp-content\/uploads\/2021\/10\/Image-1-15-800x368.png 800w\" ><\/figure><\/div>\n\n\n\n<h2 id=\"method---1-using-sorting\"><span id=\"method-1-using-sorting\">Method &#8211; 1 (Using Sorting)<\/span><\/h2>\n\n\n\n<p><strong>Intuition:<\/strong><\/p>\n\n\n\n<p>Sorting will help in grouping duplicate elements together.<\/p>\n\n\n\n<p>Input array: 1 2 3 2 2 3 4<br>Sorted array: 1 2 2 2 3 3 4 (all 2\u2019s and 3\u2019s are grouped together).\u00a0<\/p>\n\n\n\n<p>Now the problem is to remove duplicates from the sorted array.<\/p>\n\n\n\n<h3 id=\"solution-1-using-extra-space\">Solution 1 (Using extra space)<\/h3>\n\n\n\n<ul><li>Sort the given array.<\/li><li>Create an auxiliary array to store the unique elements and also maintain the count of unique elements.(here we will iterate over the sorted array and will put the first occurrence of each element in the auxiliary array and also maintain an integer to get the count of these unique elements which will also tell us about the index where the next element should be placed).<\/li><li>Copy elements from auxiliary array to given array.<\/li><\/ul>\n\n\n\n<h4 id=\"cc-code\"><span id=\"c-c-code\">C\/C++ Code<\/span><\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int removeDuplicates(int arr[], int n) {\n    if(n == 0 || n == 1)\n        return n;\n    sort(arr, arr+n);\n    int temp[n];       \n    int i = 0, j = 0;      \n    temp[j++] = arr[i++];\n    for( ; i&lt;n; i++){\n        if(arr[i] != arr[i-1]){\n            temp[j++] = arr[i];\n        }\n    }\n    for(i=0; i&lt;j; i++){\n            arr[i] = temp[j];\n    }\n    return j;\n}<\/pre>\n\n\n\n<h4 id=\"java-code\">Java Code<\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static int removeduplicates(int arr[], int n){\n    if (n == 0 || n == 1) {\n        return n;\n    }\n    Arrays.sort(arr);  \n    int[] temp = new int[n];\n    int i = 0, j = 0;\n    temp[j++] = arr[i++];\n    for ( ; i &lt; n - 1; i++) {\n        if (arr[i] != arr[i-1]) {\n            temp[j++] = arr[i];\n        }\n    }\n    for (i = 0; i &lt; j; i++) {\n        arr[i] = temp[i];\n    }\n    return j;\n}<\/pre>\n\n\n\n<h4 id=\"python-code\">Python Code<\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def removeDuplicates(arr, n):\n    if n == 0 or n == 1:\n        return n\n    arr.sort();\n    temp = list(range(n))\n    j = 0\n    temp[j] = arr[0]    j+=1\n    for i in range(1, n):\n        if arr[i] != arr[i-1]:\n            temp[j] = arr[i]\n            j += 1\n           \n    for i in range(0, j):\n        arr[i] = temp[i]\n\n    return j<\/pre>\n\n\n\n<ul><li><strong>Time complexity<\/strong> will be O(NlogN) because we have used sorting.<\/li><li><strong>Space complexity<\/strong> will be O(N) using an extra array.<\/li><\/ul>\n\n\n\n<h3 id=\"solution-2-without-using-extra-space\">Solution 2 (Without using extra space)<\/h3>\n\n\n\n<p>The approach is the same as the above solution: just don\u2019t use the extra array instead do in-place swaps.<\/p>\n\n\n\n<p>We are using an integer to have the count of unique elements which will also tell us about the position where the new element should be placed in the same array.<\/p>\n\n\n\n<p>So starting from j = 0 indicates no unique elements are there and as we will iterate if we encounter any new element we put that element in jth position and will increase j.<\/p>\n\n\n\n<h4 id=\"cc-implementation\"><span id=\"c-c-implementation\">C\/C++ Implementation<\/span><\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int removeDuplicates(int arr[], int n) {\n    if(n == 0 || n == 1)\n        return n;\n    sort(arr, arr+n);       \n    int j = 0;      \n    for(int i=1; i&lt;n; i++){\n        if(arr[i] != arr[i-1]){\n          arr[++j]=arr[i];\n        }\n    }\n    return j;\n}<\/pre>\n\n\n\n<h4 id=\"java-implementation\">Java Implementation<\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static int removeduplicates(int arr[], int n){\n    if (n == 0 || n == 1) {\n        return n;\n    }\n    Arrays.sort(arr);  \n    int j = 0;\n    for ( int i = 0; i &lt; n ; i++) {\n        if (arr[i] != arr[i-1]) {\n            arr[++j] = arr[i];\n        }\n    }\n    return j;\n}<\/pre>\n\n\n\n<h4 id=\"python-implementation\">Python Implementation<\/h4>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def removeDuplicates(arr, n):\n    if n == 0 or n == 1:\n        return n\n    arr.sort();\n    j = 1\n    for i in range(1, n):\n        if arr[i] != arr[i-1]:\n            arr[j] = arr[i]\n            j += 1\n    return j<\/pre>\n\n\n\n<ul><li><strong>Time complexity<\/strong> will be O(NlogN) because we have used sorting.<\/li><li><strong>Space complexity<\/strong> will be O(N) using an extra array.<\/li><\/ul>\n\n\n\n<h2 id=\"method---2-use-of-hashmaps\"><span id=\"method-2-use-of-hashmaps\">Method &#8211; 2 (Use of HashMaps)<\/span><\/h2>\n\n\n\n<p>We know we can use hashmaps when we need to know whether some element is present in it in O(1).<\/p>\n\n\n\n<p>So while traversing the array we will store the elements in a hashmap.<\/p>\n\n\n\n<p>And like approaches explained above we will place unique elements by checking whether the current element is already present in the hashmap or not.<\/p>\n\n\n\n<h3 id=\"cc-code-for-hashmaps\"><span id=\"c-c-code-for-hashmaps\">C\/C++ Code For HashMaps<\/span><\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"cpp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">int removeDuplicates(int arr[], int n) {\n    if(n == 0 || n == 1)\n        return n;       \n    int j = 0;       unordered_map&lt;int,int> mp;   \n    for(int i=0; i&lt;n; i++){\n        if(mp.find(arr[i])==mp.end()){            arr[j++] = arr[i];        }\n    }\n    return j;\n}<\/pre>\n\n\n\n<h3 id=\"java-code-for-hashmaps\">Java Code For HashMaps<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static int removeduplicates(int arr[], int n){\n    if (n == 0 || n == 1) {\n        return n;\n    }\n    HashMap&lt;Integer,Integer> map = new HashMap&lt;Integer,Integer>();\n    int j = 0;\n    for (int i=0; i &lt; n; i++) {\n        if (map.containsKey(arr[i])==0) {\n            map.put(arr[i], 1);             arr[j++] = arr[i];\n        }\n    }\n    return j;\n}<\/pre>\n\n\n\n<h3 id=\"python-code-for-hashmaps\">Python Code For HashMaps<\/h3>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def removeDuplicates(arr, n):\n    if n == 0 or n == 1:\n        return n    mp = {i : 0 for i in arr}\n    j = 0\n    for i in range(0, n):\n        if mp[arr[i]]==0:\n            arr[j] = arr[i]\n            j += 1            mp[arr[i]] = 1\n    return j<\/pre>\n\n\n\n<ul><li><strong>Time complexity<\/strong> will be O(N) because of the use of hashmaps.<\/li><li><strong>Space complexity<\/strong> will be O(N) using a hashmap.<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-black-background-color has-black-color is-style-wide\"\/>\n\n\n\n<p><strong>Practice Problems<\/strong><\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.interviewbit.com\/problems\/remove-duplicates-from-sorted-array\/\" target=\"_blank\">Remove Duplicates From Sorted Arrays<\/a><br><a href=\"https:\/\/www.interviewbit.com\/problems\/remove-element-from-array\/\" target=\"_blank\" rel=\"noreferrer noopener\">Remove Element From An Array<\/a><\/p>\n\n\n\n<h2 id=\"faqs\">FAQs<\/h2>\n\n\n\n<h3 id=\"q1-how-do-you-find-duplicates-in-an-array\"><span id=\"q-1-how-do-you-find-duplicates-in-an-array\">Q.1: How do you find duplicates in an array?<\/span><\/h3>\n\n\n\n<p>Ans: For finding duplicates we can use our hashmaps, and we can also find duplicates by sorting the array.<\/p>\n\n\n\n<h3 id=\"q2-how-do-you-remove-duplicates-from-an-unsorted-array-in-place\"><span id=\"q-2-how-do-you-remove-duplicates-from-an-unsorted-array-in-place\">Q.2: How do you remove duplicates from an unsorted array in place?<\/span><\/h3>\n\n\n\n<p>Ans: We can use hashmaps to maintain the frequency of each element and then we can remove the duplicates from the array.<\/p>\n","protected":false},"excerpt":{"rendered":"Problem Statement Given an array of integers, the task is to remove the duplicates from the array. Method&hellip;\n","protected":false},"author":5,"featured_media":3318,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_daextam_enable_autolinks":"1","csco_singular_sidebar":"","csco_page_header_type":"","csco_appearance_grid":"","csco_page_load_nextpost":"","csco_post_video_location":[],"csco_post_video_location_hash":"","csco_post_video_url":"","csco_post_video_bg_start_time":0,"csco_post_video_bg_end_time":0},"categories":[145],"tags":[144,521],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3314"}],"collection":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/comments?post=3314"}],"version-history":[{"count":3,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3314\/revisions"}],"predecessor-version":[{"id":20737,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/posts\/3314\/revisions\/20737"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media\/3318"}],"wp:attachment":[{"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/media?parent=3314"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/categories?post=3314"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.interviewbit.com\/blog\/wp-json\/wp\/v2\/tags?post=3314"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}