Single Element in a Sorted Array#

Problem statement#

[1]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(logn) time and O(1) space.

Example 1#

Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2

Example 2#

Input: nums = [3,3,7,7,10,11,11]
Output: 10

Constraints#

  • 1 <= nums.length <= 10^5.

  • 0 <= nums[i] <= 10^5.

Solution 1: Bruteforce#

Code#

#include <vector>
#include <iostream>
using namespace std;
int singleNonDuplicate(vector<int>& nums) {
    for (int i = 0; i < nums.size() - 1; i += 2) {
        if (nums[i] != nums[i + 1]) {
            return nums[i];
        }
    }
    return nums[0];
}
int  main() {
    vector<int> nums{1,1,2,3,3,4,4,8,8};
    cout << singleNonDuplicate(nums) << endl;
    nums = {3,3,7,7,10,11,11};
    cout << singleNonDuplicate(nums) << endl;
    nums = {3};
    cout << singleNonDuplicate(nums) << endl;
}
Output:
2
10
3

Code explanation#

  1. The code uses a simple loop to iterate through the array nums.

  2. Inside the loop, it checks if the current element nums[i] is equal to the next element nums[i + 1].

  3. If the current element and the next element are not equal, it means that nums[i] is the single element because all other elements in the sorted array appear twice. In this case, the code immediately returns nums[i] as the result.

  4. If the current element and the next element are equal, it means that the single element has not been found yet, and the loop continues to the next pair of elements.

  5. The loop continues until i reaches the second-to-last element in the array. This is because the code compares elements in pairs, and there’s no “next element” to compare with the last element.

  6. If the loop completes without finding the single element, it means that the single element is the first element in the array (since it hasn’t been found in any pair). Therefore, the code returns nums[0] as the result.

In summary, this code takes advantage of the sorted nature of the array to find the single element efficiently. It iterates through the array by comparing elements in pairs, and as soon as it finds a pair of elements that are not equal, it returns the first element of that pair as the result. If no such pair is found, it returns the first element as the single element.

Complexity#

  • Runtime O(n), where n = nums.length.

  • Memory O(1).