kdb+

Return the first missing positive integer


There's a list of integer with both positive and negative values. We need to return the first missing positive integer.

Eg.

  1. Input - 3 -1 1 0 4 , Expected Output - 2
  2. Input - -1 -4 -3, Expected Output - 1
  3. Input - 1 3 2, Expected Output - 4

I could come up with below solution which might have a lot of scope for optimization. Just wanted to check if there could be a O(n) solution which does not use sorting logic. If not, then some other optimized solution then below.

q)f: {if[all x<1;:1]; x: asc x where x>0;  b:1+first where not x=1+til count x; $[0N=b;1+last x;b]}
q)f -1 -4 -3
1
q)f 1 3 2
4
q)f 3 -1 1 0 4
2

Solution

  • q)f:{$[all x<1;1;$[null o:first c where not(c:1+til count x)in x;1+max x;o]]}
    q)f -1 -4 -3
    1
    q)f 1 3 2
    4
    q)f 3 -1 1 0 4
    2