Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the minimum unique number in an array

Tags:

algorithm

The minimum unique number in an array is defined as min{v|v occurs only once in the array} For example, the minimum unique number of {1, 4, 1, 2, 3} is 2. Is there any way better than sorting?

like image 973
shilk Avatar asked Aug 14 '12 01:08

shilk


1 Answers

I believe this is an O(N) solution in both time and space:

HashSet seenOnce;     // sufficiently large that access is O(1)
HashSet seenMultiple; // sufficiently large that access is O(1)

for each in input // O(N)
    if item in seenMultiple
        next
    if item in seenOnce
        remove item from seenOnce
        add to item seenMultiple
    else
        add to item seeOnce

smallest = SENTINEL
for each in seenOnce // worst case, O(N)
    if item < smallest
        smallest = item

If you have a limited range of integral values, you can replace the HashSets with BitArrays indexed by the value.

like image 83
walrii Avatar answered Sep 22 '22 21:09

walrii