Smallest positive number missing in an unsorted array

0
974
Smallest positive number missing in an unsorted array

In the given unsorted array find the smallest missing positive integer. Positive integer doesn`t include 0. We can modify the original array if needed.

Array may contain positive and negative numbers.

Example

a. Input array : [3, 4, -1, 0, -2, 2, 1, 7, -8]

Output : 5.
In the given array 1,2,3,4 are present but 5 is absent, which is the smallest positive number missin in the given array.

b. Input array : [2, 3, 7, 8, -1, -2 ,0]

Output : 1.
In the given array 1 is absent, which is the smallest positive number missing in the given array.

c. Input array : [2, 3, 7, 8, -1, -2 ,0]

Output : 1.
In the given array 1 is absent, which is the smallest positive number missing in the given array.

Algorithm

a. We need to find the smallest missing positive number, so we don’t need negative numbers. So, we create a function to move all the positive numbers to the end of the array and we find missing number in the positive array.

b. In positive_array function,

1. We traverse the array with two pointers, if we find a negative number we swap it with the start pointer and move it forward.

2. We continue this until it reaches the end of the array and we return the start index of the positive array. Which is the start pointer position, when we reach the end of the array.

c. We create a FindMissingPostive function which takes the array and size of the array and gives the smallest missing number.

d. In this function,

1. In the input array, if we find a positive integer, we mark it visited my making the value at its index position to negative. Example: If given array is array[]. In this array, if we find 2 we make array[1]  = -2 and so on till the end of array only if array[i] – 1< size and array[array[i] – 1]> 0.

2. After modifying the array. If index at which we find the first positive number is k. Then k+1 is the smallest missing number. If we didn’t find a positive number then, size of the array + 1 is the smallest missing number.

e. For the given input array, we first apply positive_arrayfunction(let it return j)and we apply the  FindMissingPostive on (array+j).

Algorithm Working