{"id":1559,"date":"2024-02-01T13:00:00","date_gmt":"2024-02-01T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1559"},"modified":"2024-02-03T07:21:00","modified_gmt":"2024-02-03T07:21:00","slug":"first-missing-positive-problem","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/first-missing-positive-problem\/","title":{"rendered":"First Missing Positive Problem (C++, Java, Python)"},"content":{"rendered":"\n<p>Finding missing numbers can easily be found by iterating over the array or through a binary search. But there is also a question of finding a duplicate which is the same as the missing number in a sorted array but if we make the array unsorted it becomes a difficult version of it. So in this article, we will discuss the First Missing Positive problem and try to solve it using different approaches.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the First Missing Positive problem?<\/strong><\/h2>\n\n\n\n<p><strong>In the First Mission Positive problem, you are given an array, and you must find the first positive integer missing from that array.<\/strong><\/p>\n\n\n\n<p>This is important to note that if you are not given that the array is sorted always consider it unsorted and as it was not specified in the question the values of the array are only positive so we have to consider that it may contain negative values also.&nbsp;<\/p>\n\n\n\n<p>For example, you are given array arr= [2, 1, -1, -3] in this case the ans is 3 as 1 and 2 are already present so the first missing positive number is 3. We are not returning 0 as 0 is neither positive nor negative.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/8hQsb7pO2IyFlo7mRqoAC7TUCVLhC9MwdYbxpZrRcawHspJKhNldwFL8kQO-XDYTxYt1WnMOJjHx50QOvswcmA7tkqWdo8uQtNuGvO2OLWy9ofZCx5eyDKmpmjoDN6l-I-vMma4Zz9mlpp1_OhBzXpw\" alt=\"Example for First Missing Positive Problem\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Naive Approach<\/strong><\/h3>\n\n\n\n<p>The basic solution is to check for each positive number in the given array and if it is not present then that number will be the first missing positive number. Let&#8217;s understand by an example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Given array:<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/x0qbytpFxJOR-ZU1JgM6s78lsEpCfltkcZU0ccDH5v_IS_vXWTvXxs5tj6kqIXFmRzR-M5qSVWMD6JyIsnHe4xE2r9WEcAKhs2Zani7PlYPmbTnXBVrMtpkVlvnUTZH8e6_jnsqK6uaYgHDeFEJgdWY\" alt=\"Given Array\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First check for 1 in the array as 1 is present, and then we move to the next number:<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/6-H0rhUEWw1586CfWZDp0tHCTWSazRAQ2NjItaRuxULpGcLQ2UzXFHKHybPUPgYGSLOBUP6IuJ3GFd6bfWL0gQgY5AhmnBpLAO3-Hp30TKnDp2A9JGg3IPg_KL-z_Y16mLApSpzB-c3oU473uFNtQ_0\" alt=\"Check for 1\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Check for number 2 as 2 is also present, check for next:<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/sjBVAO0UIEJR_TM6dmfT7fMLFkTtvcueFihIYM480UO6cqZQdtWOAPw1hybpwS3uUceEyIH8YNVYT-FFc-3FdK1zTDP1nMptAC__kjM5cWYWlSB-9Qnipi1lwqQ5ezRjszPGLvWBsll4Cn6aBsOUa-w\" alt=\"Check for 2\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Check for number 3 as 3 is not present in the array so 3 will be the answer.<\/li>\n<\/ul>\n\n\n\n<p>As we are checking for each number in the array, the maximum we need to check is the size of the array let&#8217;s say of array is n so<em> the <\/em>time complexity is O(n^2).&nbsp; Space Complexity will be O(1) as we are not using any extra space.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Sorting to Find the First Missing Positive<\/strong><\/h3>\n\n\n\n<p>As in the above approach, we see that the time complexity is around O(n^2) which is huge and we know we can easily find the first missing number in the sorted array just by iterating over that array. <\/p>\n\n\n\n<p><strong>To find the first missing positive in an array, we will first sort the array by sorting function and then make an int variable x=1 whose initial value will be 1 and keep on updating if it encounters the same value.<\/strong><\/p>\n\n\n\n<p>For example, let&#8217;s take an array:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/x0qbytpFxJOR-ZU1JgM6s78lsEpCfltkcZU0ccDH5v_IS_vXWTvXxs5tj6kqIXFmRzR-M5qSVWMD6JyIsnHe4xE2r9WEcAKhs2Zani7PlYPmbTnXBVrMtpkVlvnUTZH8e6_jnsqK6uaYgHDeFEJgdWY\" alt=\"Input Array\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>After sorting array would be like this:<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/2a2rLO71SzsfQrG7AFmjF-rvVn5pRngq6l7ACaR5DHGDN1dzZn6p8R3zbnr_96VFvfYuZtvnLTL43dUAQq0V-Xs9JW6pqjUyhcSSjVHMRNKtIzmA8E3rMHNNCe4AucLINwGHptjptIzWqVbEbDPwngw\" alt=\"After sorting\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Let&#8217;s take a variable x=1, now iterate over the array, and increment the array value if it is the same as the variable and if the variable value is less than the current value of the array return the variable value.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/SyvIhYyTkKQNWUjtnDoQ7sGFBuSpHboI-sEYj8HLQwvvtAykxK4kJbNYpvpMis_g7E68HxDkWF007X7RM_PZLQBOwcZgLxFAu_vMGC8N9Zk0M_2JfB4ya8TeePugkYQQTzPgZpi8mH0OkzSHh1TPe1U\" alt=\"Checking for each index\"\/><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In this case, the value it returns will be 3.<\/li>\n<\/ul>\n\n\n\n<p>As we are <a href=\"https:\/\/favtutor.com\/blogs\/sorting-algorithms-java\">sorting the array<\/a> and iterating the array for once the time complexity would become (n+ log (n)) which is approx O(nlog(n)). Here n is the size of the array. Space Complexity will be O(1) as we are not using any extra space.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimized Sorting with Swap Approach<\/strong><\/h2>\n\n\n\n<p>As in the sorting approach time complexity is around O(log (n)) which is still too much. We can reduce this to O(n) by just observing the pattern as we know we have to find the first positive missing number. <\/p>\n\n\n\n<p>We just keep on putting the positive value to its correct place if possible (as sometimes the positive value is larger than the size of the array in that case we cannot put this to its correct index) whenever we find they are not at the right position.&nbsp;<\/p>\n\n\n\n<p>Let&#8217;s take an example:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>First, iterate over the array and check if the value at the current index is more than 0 and less than the index+1 or not.&nbsp;<\/li>\n\n\n\n<li>If not then move to the next index.<\/li>\n\n\n\n<li>Else check arr[arr[i]-1] &lt;= arr[i] i.e. if the value present at the index, which is the same as the value of the current index is less than the current index value or not. If it is then change the value of arr[arr[i]-1]= -1. We are doing this as some values might be the same for example in arr[1, 2, 2, 4] when we are at index 3 we find out the value is 2, and at the 2nd index is also value 2 so we will change the 2nd index value to -1 and then <a href=\"https:\/\/favtutor.com\/blogs\/swap-cpp\">swap<\/a> 2nd and 3rd index.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ program to solve the First Missing Positive problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nint main(){\n\n    vector&lt;int&gt; arr= {1,2,4,2,-1,0,5};\n    int i=0;\n    \/\/ n is the size of the array\n    int n= arr.size();\n\n    \/\/ iterating over the array\n    while(i&lt;n){\n        \/\/checking if value at that index is less than that index or not \n        if((i+1)&gt;arr[i] &amp;&amp; arr[i]&gt;0){\n            \/\/ if value present at the index which is equal to the value of the current index is less than or equal to the value of the current index update the previous value to -1.\n            if(arr[arr[i]-1]&lt;=arr[i]) arr[arr[i]-1]=-1; \n            \/\/ now swap the value at the current index and the value at the index where the index is the same as the value of current index\n            swap(arr[arr[i]-1], arr[i]);\n        }\n        else i++;\n    }\n\n    \/\/checking for the first missing +ve number  \n    for(i=0; i&lt;n;i++){\n        if(arr[i]&lt;=0 || arr[i]!=i+1) {\n            cout&lt;&lt;i+1&lt;&lt;endl;\n            goto he;\n        }\n    }\n\n    cout&lt;&lt;n+1&lt;&lt;endl;\n    he:;\n    \n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Here is the Java program to solve it:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.*;\n\nclass Main {\n    public static void main(String[] args) {\n        List&lt;Integer&gt; arr = new ArrayList&lt;&gt;(Arrays.asList(1, 2, 4, 2, -1, 0, 5));\n        int i = 0;\n        int n = arr.size();\n\n        while (i &lt; n) {\n            if ((i + 1) &gt; arr.get(i) &amp;&amp; arr.get(i) &gt; 0) {\n                if (arr.get(arr.get(i) - 1) &lt;= arr.get(i)) {\n                    arr.set(arr.get(i) - 1, -1);\n                }\n                int temp1 = arr.get(i);\n                int temp2 = arr.get(arr.get(i)-1);\n                arr.set(temp1-1, temp1);\n                arr.set(i, temp2);\n            } else {\n                i++;\n            }\n        }\n\n        boolean flag=false;\n        for (i = 0; i &lt; n; i++) {\n            if (arr.get(i) &lt;= 0 || arr.get(i) != i + 1) {\n                System.out.println(i + 1);\n                flag=true;\n                break;\n            }\n        }\n\n        if(flag==false) System.out.println(n + 1);\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>You can implement it in Python with the following code:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def main():\n    arr = [1, 2, 4, 2, -1, 0, 5]\n    i = 0\n    n = len(arr)\n\n    while i &lt; n:\n        if 0 &lt; arr[i] &lt; i + 1:\n            if arr[arr[i] - 1] &lt;= arr[i]:\n                arr[arr[i] - 1] = -1\n            arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1]\n        else:\n            i += 1\n\n    for i in range(n):\n        if arr[i] &lt;= 0 or arr[i] != i + 1:\n            print(i + 1)\n            break\n    else:\n        print(n + 1)\n\n\nif __name__ == &quot;__main__&quot;:\n    main()<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-b4a34b2b19b7e50b8a9af62acab121a4\" style=\"background-color:#fedcba\"><code>3<\/code><\/pre>\n\n\n\n<p>As we are just moving once in the loop the time complexity is <strong>O(n). <\/strong>Space Complexity will be<strong>&nbsp; O(1)<\/strong> as we are not using any extra space.<\/p>\n\n\n\n<p>Finally, here is a small comparison of the three methods:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th><strong>Approach<\/strong><\/th><th><strong>Time Complexity<\/strong><\/th><th><strong>Space Complexity<\/strong><\/th><th><strong>Description<\/strong><\/th><\/tr><\/thead><tbody><tr><td>Naive Approach<\/td><td>O(N^2)<\/td><td>O(1)<\/td><td>Check for each positive number in the given array and if it is not present then that number will be the first missing positive number.<\/td><\/tr><tr><td>Sorting Approach<\/td><td>O(N*logN)<\/td><td>O(1)<\/td><td>First sort the array by sorting function and then make an int variable x=1 whose initial value will be 1 and keep on updating if it encounters the same value.<\/td><\/tr><tr><td>Swapping Approach&nbsp;<\/td><td>O(N)<\/td><td>O(1)<\/td><td>Keep on putting the positive value to its correct place if possible whenever we find they are not at the right position.&nbsp;<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion&nbsp;<\/strong><\/h2>\n\n\n\n<p>We have seen various approaches to solving the First Missing Positive <a href=\"https:\/\/leetcode.com\/problems\/first-missing-positive\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/leetcode.com\/problems\/first-missing-positive\/\" rel=\"noreferrer noopener nofollow\">leetcode<\/a> problem which helps to understand how can we reduce the time complexity from O(n^2) to O(n). This problem might be solved with other approaches too by making a temporary array or with the use of a <a href=\"https:\/\/favtutor.com\/blogs\/hashing-in-data-structure\">hash map<\/a> all these can either increase the time or space complexity.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand what is the First Missing Positive Problem from leetcode and how to solve it using sorting with swapping.<\/p>\n","protected":false},"author":14,"featured_media":1564,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1559","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1559","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1559"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1559\/revisions"}],"predecessor-version":[{"id":1642,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1559\/revisions\/1642"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1564"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1559"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1559"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1559"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}