Taro Logo

Single Element in a Sorted Array

#47 Most AskedMedium
Topics:
ArraysBinary Search

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array is empty or has a length of zero?
  2. Can the array contain negative integers, or are the numbers strictly positive?
  3. Is the input array guaranteed to be non-empty and always contain a valid single element according to the problem description?
  4. Can I assume the array is always of odd length, given that all other elements appear exactly twice and one appears once?
  5. Should we handle cases where the input pointer is null or invalid?

Brute Force Solution

Approach

Imagine you have a long row of items where almost every item appears in an exact pair next to each other, except for one single item that appears alone. The brute force approach involves inspecting the items one by one from the very beginning to find the odd one out.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first item at the beginning of the row.
  2. Check if its immediate neighbor is identical to it, which means they form a valid pair.
  3. If the neighbor is different, you have successfully found your single item, so you can stop right there.
  4. If the neighbor matches, skip past both of them to move on to the next pair.
  5. Repeat this process of checking pairs one by one as you move down the line.
  6. Eventually, you will reach the single item that does not have a matching neighbor and identify it as the answer.

Code Implementation

def single_non_duplicate(nums):
    current_index = 0

    # We stop before the last element to prevent looking out of bounds
    while current_index < len(nums) - 1:
        
        if nums[current_index] != nums[current_index + 1]:
            # If neighbors do not match, this is the single element
            return nums[current_index]
        
        current_index += 2

    # If no mismatch was found earlier, the final element is unique
    return nums[-1]

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by sequentially scanning through the array to inspect elements in pairs from the beginning to the end. For an input of size n, we examine at most n elements by moving past valid pairs one by one until the single element is found. This linear traversal results in approximately n operations in the worst-case scenario. Therefore, the total operations approximate n, which simplifies to Big O of n.
Space Complexity
O(1) – The provided algorithm executes purely iteratively by checking adjacent items in the original row one by one from the very beginning. It does not allocate any temporary lists, hash maps, or recursive call stacks, relying only on a few primitive loop variables to track the current position. Because the extra memory consumed remains constant regardless of how many items are in the row, the auxiliary space complexity is O(1).

Optimal Solution

Approach

Instead of checking every single item one by one, we can use a smart elimination strategy to find the unique item quickly. By looking at the middle of our ordered collection, we can rule out half of the items in a single step.

Here's how the algorithm would work step-by-step:

  1. Look at the exact middle of the entire sorted line of items.
  2. Check if your current position is the unique item by seeing if its immediate neighbors match it.
  3. If your current item does not match either neighbor, you have successfully found the unique item.
  4. If the item matches the one immediately to its right, check the total count of items on the left side to see if it is even or odd.
  5. If the left side has an even count of items, you know the unique item must be hiding further to the right, so completely ignore everything to the left.
  6. If the left side has an odd count, the unique item must be hiding somewhere to the left, so completely ignore everything to the right.
  7. Repeat this process of checking the middle and throwing away half of the remaining items until you isolate the unique item.

Code Implementation

def single_non_duplicate(sorted_array):
    left_pointer = 0
    right_pointer = len(sorted_array) - 1

    while left_pointer < right_pointer:
        middle_index = left_pointer + (right_pointer - left_pointer) // 2

        # Ensure middle_index is even so we can check pairs correctly aligned in the sorted array.
        if middle_index % 2 == 1:
            middle_index -= 1

        # If the pair matches, the single element must be located further to the right side.
        if sorted_array[middle_index] == sorted_array[middle_index + 1]:
            left_pointer = middle_index + 2

        # If the pair does not match, the single element is located somewhere on the left side.
        else:
            right_pointer = middle_index

    return sorted_array[left_pointer]

Big(O) Analysis

Time Complexity
O(log n) – Since the algorithm uses a binary search strategy to examine the middle element and eliminate half of the remaining items in each step, the search space is divided by two repeatedly. For an input of size n, this halving process continues until only one element remains. This approach requires approximately log base 2 of n operations, which simplifies to O(log n).
Space Complexity
O(1) – To find the unique item using the smart elimination strategy, the algorithm only relies on a few primitive pointer variables such as left and right indices. These variables store fixed integer values regardless of the input size, meaning no extra data structures like temporary lists or hash maps are created. Since the number of recursive calls or iteration variables remains constant as the input size N grows, the extra memory used does not scale. Consequently, the auxiliary space complexity is constant, denoted in Big O notation as O(1).

Edge Cases

Array with a single element
How to Handle:
Binary search boundaries immediately evaluate the lone element without entering the loop, returning it correctly.
Single element located at the very beginning of the array
How to Handle:
The binary search correctly shifts the search window to the right half once the initial duplicate pairing invariant fails.
Single element located at the very end of the array
How to Handle:
The algorithm exhausts the left partitions and converges on the final index as the low and high pointers meet.
Arrays with negative numbers and mixed zero values
How to Handle:
The approach relies on relative index parity and value comparisons rather than absolute magnitudes, working seamlessly with negatives.
Extremely large arrays approaching memory or performance limits
How to Handle:
Operating in logarithmic time complexity and constant space complexity prevents stack overflow and timeout issues.
Even-length array violating the problem constraints
How to Handle:
The problem statement guarantees a valid configuration with an odd length, so index out of bounds is prevented by design.
0/245 completed