Search Single Element in a sorted array

[Question]: You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
Return the single element that appears only once.
Your solution must run in O(log n) time and O(1) space.

Example 1:

Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
// Approach #1 using reduce
func singleNonDuplicate(_ nums: [Int]) -> Int {
    nums.reduce(0, ^)
}
// Approach #2
// TC: O(logN)
// SC: O(1)
func singleNonDup(_ nums: [Int]) ->Int {
    if nums.isEmpty { return -1 }
    var left = 0
    var right = nums.count - 1
    
    while left < right {
        var mid = (left + right)/2
        if (mid % 2 == 0 && nums[mid] == nums[mid + 1]) || (mid % 2 == 1 && nums[mid] == nums[mid - 1]) {
            // If mid is even & so dup will be next number
            // If mid is Odd & so dup will be prev number
            left = mid + 1
        } else {
            right = mid
        }
    }
    return nums[left]
}
let dupArray = [3,3,7,7,10,11,11]
let singleEl = singleNonDuplicate(dupArray)
print("singleEl is --- ", singleEl) //singleEl 10

let uniqueEl = singleNonDup(dupArray)
print("singleEl is --- ", uniqueEl) //singleEl 10

Leave a Comment

Your email address will not be published. Required fields are marked *