1

I am trying to find out lowest unique element from list. I have been able to generate O(n^2) and O(n) solutions. But I don't find them optimized. Kindly help me understand,if there is a possible O(n) solution for it. No one liner solutions please. Below are my codes:

Main function:

if __name__ =="__main__":
    print uniqueMinimum([6, 2, 6, -6, 45, -6, 6])
    print lowestUnique([5, 10, 6, -6, 3, -6, 16])

O(n^2) Solution:

def lowestUnique(arr):
     num = max(arr)
     for i in range(len(arr)):
         check  = False
         for j in range(len(arr)):
             if arr[i]==arr[j] and i!=j:
                 check =True
             if check==False:
                 if num > arr[i]: 
                      num = arr[i]
     return num

I would like to avoid using max(array) in above solution.

O(n) Solution:

def uniqueMinimum(array):
     d ={}
     a =[]
     num = max(array)
     for i in range(len(array)):
         k =d.get(array[i])
         if k is None:
             d[array[i]] = 1
             a.append(array[i])

         else:
             d[array[i]] = k+1
             if array[i] in a:
                 a.remove(array[i])

     a.sort()
     return a[0]
6
  • So you can't use min()? Commented Dec 26, 2016 at 2:02
  • 1
    We have to get lowest unique number. Using min, we will get -6,but its not unique. Commented Dec 26, 2016 at 2:04
  • Can you try sorting the list and then comparing each number to the next one? Or would that be considered a linear solution? Commented Dec 26, 2016 at 2:16
  • 1
    @Pikaroo: If we sort, array will be, Commented Dec 26, 2016 at 2:23
  • 1
    If we sort, array will be, [-6, -6, 2, 6, 6, 6, 45]. if we compare if a[i] == a[i+1] and i !=j, result will be -6 only as a[1] =-6 and a[2]=2. Commented Dec 26, 2016 at 2:26

1 Answer 1

1

I can't really comment on the big-O since it depends on the implementation of the built-in python functions which I've never looked into. Here's a more reasonable implementation though:

def lowestUnique(array):
    for element in sorted(list(set(array))):
        if array.count(element) == 1:
            return element
    raise Exception('No unique elements found.')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.