Thursday, April 12, 2012

Smallest positive number.


You are given an unsorted array with both positive and negative elements. You have to find the smallest positive number missing from the array in O(n) time using constant extra space.
Eg: 
Input = {2, 3, 7, 6, 8, -1, -10, 15}
Output = 1


Input = { 2, 3, -7, 6, 8, 1, -10, 15 }
Output = 4


Approach:
Put all the numbers from array in the hashmap, and then starting from 1, check all the natural numbers in the map, the first number not there is the answer.

1 comment: