➜ ~

Playing Hacks and Stuffs!


Project maintained by h4ckyou Hosted on GitHub Pages — Theme by mattgraham

Single Element in a Sorted Array

image

Approach

Looking at the problem we can tell we’ll be given an array nums and we’re too basically find that element in the array which only appears once

A good way to start is to try solve this using a brute force approach as it helps to confirm if there’s a solution to this problem

And basically my brute force approach would use Linear Search which basically does this:

Here’s the implementation:

def singleNonDuplicate(array):

    if len(array) == 1:
        return array[0]

    if array[0] != array[1]:
        return array[0]

    for i in range(1, len(array)-1):
        if array[i] != array[i-1] and array[i] != array[i+1]:
            return array[i]

    return array[-1]

nums = [1,1,2,3,3,4,4,8,8]
r = singleNonDuplicate(nums)

print(r)

That works but the problem with it is the complexity:

Time Complexity: O(N)
Space Complexity: O(1)

So now we can optimize the program

The way I’ll do it is using Binary Search

Here’s the explanation:

Complexity

O(log n)
O(1)

Solve Script: link

It works! image