First Missing Positive, Sort Colors

First Missing Positive

Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.

Solution

First solution I thought of is simply sort the array, then find the fist missing positive by comparing each positive element with index. However, even though this passed the OJ, it’s still O(logn) time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int firstMissingPositive(int A[]) {
int n= A.length;
int i=0;
int index=0;
if(n==0) return 1;
Arrays.sort(A);
while(i<n && A[i]<=0) i++;
for(;i<n;i++){
if(i>0&&A[i]==A[i-1]) continue;
else if(A[i]-index!=1) return index+1;
else index=A[i];
}
return index+1;
}

Second solution sorts every number corresponding with index, index i holds number i+1, if i+1 is not in the array then we return the smallest mismatch. The runtime is O(n).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public int firstMissingPositive(int A[]) {
int n= A.length;
int i=0;
int tmp=0;
while(i<n){
if(A[i]>0 && A[i]<n && A[i]!=A[A[i]-1])
{
tmp=A[A[i]-1];
A[A[i]-1]=A[i];
A[i]=tmp;
}
else i++;
}
for(i=0;i<n;i++){
if(A[i]!=i+1) return i+1;
}
return n+1;
}

Sort Colors

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library’s sort function for this problem.

Solution

First solution is counting sort, two pass algorithm.

1
2
3
4
5
6
7
8
9
10
11
12
13
public void sortColors(int[] A) {
int n=A.length;
int[] B=new int[3];
for (int i=0;i<n;i++){
B[A[i]]++;
}
int p=0;
for(int j=0;j<B.length;j++){
for (int k=0;k<B[j];k++)
A[p++]=j;
}
}

Second Solution is one pass three way partition, using three pointers: pr for the first not red, pb for first not blue and i for current.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void sortColors(int[] A) {
int n=A.length;
int pr=0,pb=n-1,i=0;
while(pr<n&&A[pr]==0) pr++;
while(pb>0&&A[pb]==2) pb--;
i=pr;
while(i<=pb){
if(A[i]==0) {swap(A,i,pr); pr++;}
if(A[i]==2) {swap(A,i,pb); pb--;}
else i++;
}
}
void swap(int[] A,int a, int b){
int tmp=A[a];
A[a]=A[b];
A[b]=tmp;
}