title: Leetcode Question - First Missing Positive
body: <p>Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.</p>
  <p>For example, the input <code>[3, 4, -1, 1]</code> should give <code>2</code>. The input <code>[1, 2, 0]</code> should give <code>3</code>.</p>
  <p>I did this but not able to find what is the error in my logic when taking input as <a href="https://i.stack.imgur.com/Mx3BB.png" rel="nofollow noreferrer">1</a>. it is giving output as <code>undefined</code> instead of <code>2</code>.</p>
  <pre class="lang-js prettyprint-override"><code>var firstMissingPositive = function(nums) {
  
    nums.sort(compare);
    var arr = [];
  
    for (let i = 0; i &lt; nums.length; i++) {
      if (nums[i] &gt; 0)
        arr.push(nums[i]);
    }
  
    if (arr.length == 0)
      return 1;
    else {
      for (let i = 0; i &lt; arr.length; i++) {
        if (!(arr[0] == 1))
          return 1;
        else if (i &gt; 0)
          if (!(arr[i - 1] + 1 == arr[i]))
            return i + 1;
          else if ((i + 1) == arr.length)
          return arr[i] + 1;
        else if ((arr[i] == i + 1)) // &amp;&amp; (arr[i+1] == arr[i]+1 ))
          continue;
        else
          return i + 1;
      }
    }
  };
  
  function compare(a, b) {
    return a - b;
  }
  </code></pre>
  <p>Output:<br>
  <img src="https://i.stack.imgur.com/Mx3BB.png" alt="https://i.stack.imgur.com/Mx3BB.png" /></p>