Find the element that appears once in a sorted array - GeeksforGeeks

17 Nov, 2021
Given a sorted array in which all elements appear twice (one after one) and one element appears only once. Find that element in O(log n) complexity.
Example: 
Input:   arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8}
Output:  4

Input:   arr[] = {1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8}
Output:  8
A Simple Solution is to traverse the array from left to right. Since the array is sorted, we can easily figure out the required element.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find the element that// appears only once#include <bits/stdc++.h>using namespace std; // A Linear Search based function to find// the element that appears only oncevoid search(int arr[], int n){    int ans = -1;    for (int i = 0; i < n; i += 2) {        if (arr[i] != arr[i + 1]) {            ans = arr[i];            break;        }    }       if (arr[n - 2] != arr[n - 1])            ans = arr[n-1];       // ans = -1 if no such element is present.    cout << "The required element is " << ans << "\n";} // Driver codeint main(){    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };    int len = sizeof(arr) / sizeof(arr[0]);     search(arr, len);     return 0;} // This code is contributed by yashbeersingh42
// Java program to find the element that// appears only onceimport java.io.*; class GFG {    // A Linear Search based function to find    // the element that appears only once    static void search(int arr[], int n)    {        int ans = -1;        for (int i = 0; i < n; i += 2) {            if (arr[i] != arr[i + 1]) {                ans = arr[i];                break;            }        }               if (arr[n - 2] != arr[n - 1])            ans = arr[n-1];              // ans = -1 if no such element is present.        System.out.println("The required element is "                           + ans);    }    public static void main(String[] args)    {        int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };        int len = arr.length;         search(arr, len);    }}
# Python3 program to find the element that# appears only once # A Linear Search based function to find# the element that appears only once  def search(arr, n):     ans = -1    for i in range(0, n, 2):        if (arr[i] != arr[i + 1]):            ans = arr[i]            break    if(arr[n-2] != arr[n-1]):        ans = arr[n-1]     # ans = -1 if no such element is present.    print("The required element is", ans)  # Driver codearr = [1, 1, 2, 4, 4, 5, 5, 6, 6]Len = len(arr) search(arr, Len) # This code is contributed by divyesh072019
// C# program to find the element that// appears only onceusing System; class GFG {    // A Linear Search based function to find    // the element that appears only once    static void search(int[] arr, int n)    {        int ans = -1;        for (int i = 0; i < n; i += 2) {            if (arr[i] != arr[i + 1]) {                ans = arr[i];                break;            }        }         if (arr[n - 2] != arr[n - 1])            ans = arr[n-1];               // ans = -1 if no such element is present.        Console.Write("The required element is "                        + ans);    }    public static void Main(String[] args)    {        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };        int len = arr.Length;         search(arr, len);    }} // This code is contributed by shivanisinghss2110
<script> // JavaScript program to find the element that// appears only once // A Linear Search based function to find// the element that appears only oncefunction search(arr, n){    let ans = -1;    for (let i = 0; i < n; i += 2) {        if (arr[i] != arr[i + 1]) {            ans = arr[i];            break;        }    }     if (arr[n - 2] != arr[n - 1])            ans = arr[n-1];     // ans = -1 if no such element is present.    document.write("The required element is " + ans + "<br>");} // Driver code    let arr = [ 1, 1, 2, 4, 4, 5, 5, 6, 6 ];    let len = arr.length;     search(arr, len);      // This code is contributed by Surbhi Tyagi </script>
The required element is 2
Time Complexity: O(n)Space Complexity: O(1) 
Another Simple Solution is to use the properties of XOR (a ^ a = 0 & a ^ 0 = a). The idea is to find the XOR of the complete array. The XOR of the array is the required answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find the element that// appears only once#include <bits/stdc++.h>using namespace std; // A XOR based function to find// the element that appears only oncevoid search(int arr[], int n){    int XOR = 0;    for (int i = 0; i < n; i++) {        XOR = XOR ^ arr[i];    }    cout << "The required element is " << XOR << "\n";} // Driver codeint main(){    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };    int len = sizeof(arr) / sizeof(arr[0]);     search(arr, len);     return 0;} // This code is contributed by yashbeersingh42
// Java program to find the element that// appears only onceimport java.io.*; class GFG {    // A XOR based function to find    // the element that appears only once    static void search(int arr[], int n)    {        int XOR = 0;        for (int i = 0; i < n; i++) {            XOR = XOR ^ arr[i];        }        System.out.println("The required element is "                           + XOR);    }    // Driver Code    public static void main(String[] args)    {        int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };        int len = arr.length;         search(arr, len);    }} // This code is contributed by yashbeersingh42
# Python3 program to find the element that# appears only once # A XOR based function to find# the element that appears only oncedef search(arr, n) :     XOR = 0    for i in range(n) :        XOR = XOR ^ arr[i]     print("The required element is", XOR) # Driver codearr = [ 1, 1, 2, 4, 4, 5, 5, 6, 6 ]Len = len(arr) search(arr, Len) # This code is contributed by divyesh072019
// C# program to find the element that// appears only onceusing System; class GFG{     // A XOR based function to find// the element that appears only oncestatic void search(int []arr, int n){    int XOR = 0;         for(int i = 0; i < n; i++)    {        XOR = XOR ^ arr[i];    }    Console.Write("The required element is " + XOR);} // Driver Codepublic static void Main(String[] args){    int []arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };    int len = arr.Length;         search(arr, len);}} // This code is contributed by shivanisinghss2110
<script>// JavaScript program to find the element that// appears only once // A XOR based function to find// the element that appears only oncefunction search(arr, n){    let XOR = 0;    for (let i = 0; i < n; i++) {        XOR = XOR ^ arr[i];    }    document.write("The required element is " + XOR + "<br>");} // Driver code    let arr = [ 1, 1, 2, 4, 4, 5, 5, 6, 6 ];    let len = arr.length;     search(arr, len);    // This code is contributed by Surbhi Tyagi.</script>
The required element is 2
Time Complexity: O(n)Space Complexity: O(1) 
An Efficient Solution can find the required element in O(Log n) time. The idea is to use Binary Search. Below is an observation on the input array. All elements before the required have the first occurrence at even index (0, 2, ..) and the next occurrence at odd index (1, 3, ...). And all elements after the required elements have the first occurrence at an odd index and the next occurrence at an even index. 1) Find the middle index, say ‘mid’.2) If ‘mid’ is even, then compare arr[mid] and arr[mid + 1]. If both are the same, then the required element after ‘mid’ and else before mid.3) If ‘mid’ is odd, then compare arr[mid] and arr[mid – 1]. If both are the same, then the required element after ‘mid’ and else before mid.
Below is the implementation based on the above idea: 
C++
C
Java
Python
C#
PHP
Javascript
// C++ program to find the element that// appears only once#include <iostream>using namespace std; // A Binary Search based function to find// the element that appears only oncevoid search(int arr[], int low, int high){     // Base cases    if (low > high)        return;     if (low == high) {        cout << "The required element is " << arr[low];        return;    }     // Find the middle point    int mid = (low + high) / 2;     // If mid is even and element next to mid is    // same as mid, then output element lies on    // right side, else on left side    if (mid % 2 == 0) {        if (arr[mid] == arr[mid + 1])            search(arr, mid + 2, high);        else            search(arr, low, mid);    }     // If mid is odd    else {        if (arr[mid] == arr[mid - 1])            search(arr, mid + 1, high);        else            search(arr, low, mid - 1);    }} // Driver codeint main(){    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };    int len = sizeof(arr) / sizeof(arr[0]);     search(arr, 0, len - 1);     return 0;} // This code is contributed by ShubhamCoder
// C program to find the element that appears only once#include <stdio.h> // A Binary Search based function to find the element// that appears only oncevoid search(int* arr, int low, int high){    // Base cases    if (low > high)        return;     if (low == high) {        printf("The required element is %d ", arr[low]);        return;    }     // Find the middle point    int mid = (low + high) / 2;     // If mid is even and element next to mid is    // same as mid, then output element lies on    // right side, else on left side    if (mid % 2 == 0) {        if (arr[mid] == arr[mid + 1])            search(arr, mid + 2, high);        else            search(arr, low, mid);    }    else // If mid is odd    {        if (arr[mid] == arr[mid - 1])            search(arr, mid + 1, high);        else            search(arr, low, mid - 1);    }} // Driver codeint main(){    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };    int len = sizeof(arr) / sizeof(arr[0]);    search(arr, 0, len - 1);    return 0;}
// Java program to find the element that appears only once public class Main {    // A Binary Search based method to find the element    // that appears only once    public static void search(int[] arr, int low, int high)    {        if (low > high)            return;        if (low == high) {            System.out.println("The required element is "                               + arr[low]);            return;        }         // Find the middle point        int mid = (low + high) / 2;         // If mid is even and element next to mid is        // same as mid, then output element lies on        // right side, else on left side        if (mid % 2 == 0) {            if (arr[mid] == arr[mid + 1])                search(arr, mid + 2, high);            else                search(arr, low, mid);        }        // If mid is odd        else if (mid % 2 == 1) {            if (arr[mid] == arr[mid - 1])                search(arr, mid + 1, high);            else                search(arr, low, mid - 1);        }    }     // Driver Code    public static void main(String[] args)    {        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };        search(arr, 0, arr.length - 1);    }}// This code is contributed by Tanisha Mittal
# A Binary search based function to find# the element that appears only once  def search(arr, low, high):     # Base cases    if low > high:        return None     if low == high:        return arr[low]     # Find the middle point    mid = low + (high - low)/2     # If mid is even and element next to mid is    # same as mid, then output element lies on    # right side, else on left side    if mid % 2 == 0:         if arr[mid] == arr[mid+1]:            return search(arr, mid+2, high)        else:            return search(arr, low, mid)     else:        # if mid is odd        if arr[mid] == arr[mid-1]:            return search(arr, mid+1, high)        else:            return search(arr, low, mid-1) # Driver Code# Test Arrayarr = [1, 1, 2, 4, 4, 5, 5, 6, 6] # Function callresult = search(arr, 0, len(arr)-1) if result is not None:    print "The required element is %d" % resultelse:    print "Invalid Array"
// C# program to find the element// that appears only onceusing System; class GFG {     // A Binary Search based    // method to find the element    // that appears only once    public static void search(int[] arr, int low, int high)    {         if (low > high)            return;        if (low == high) {            Console.WriteLine("The required element is "                              + arr[low]);            return;        }         // Find the middle point        int mid = (low + high) / 2;         // If mid is even and element        // next to mid is same as mid        // then output element lies on        // right side, else on left side        if (mid % 2 == 0) {            if (arr[mid] == arr[mid + 1])                search(arr, mid + 2, high);            else                search(arr, low, mid);        }         // If mid is odd        else if (mid % 2 == 1) {            if (arr[mid] == arr[mid - 1])                search(arr, mid + 1, high);            else                search(arr, low, mid - 1);        }    }     // Driver Code    public static void Main(String[] args)    {        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };        search(arr, 0, arr.Length - 1);    }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find the element// that appears only once // A Binary Search based function// to find the element that// appears only oncefunction search($arr, $low, $high){         // Base cases    if ($low > $high)        return;     if ($low==$high)    {        echo("The required element is " );        echo $arr[$low] ;        return;    }     // Find the middle point    $mid = ($low + $high) / 2;     // If mid is even and element    // next to mid is same as mid,    // then output element lies on    // right side, else on left side    if ($mid % 2 == 0)    {        if ($arr[$mid] == $arr[$mid + 1])            search($arr, $mid + 2, $high);        else            search($arr, $low, $mid);    }         // If mid is odd    else    {        if ($arr[$mid] == $arr[$mid - 1])            search($arr, $mid + 1, $high);        else            search($arr, $low, $mid - 1);    }}     // Driver Code    $arr = array(1, 1, 2, 4, 4, 5, 5, 6, 6);    $len = sizeof($arr);    search($arr, 0, $len - 1); // This code is contributed by nitin mittal?>
<script>// Javascript implementation // A Binary Search based function to find// the element that appears only oncefunction search( arr, low, high){      // Base cases    if (low > high)        return;      if (low == high) {        document.write("The required element is " + arr[low]);        return;    }      // Find the middle point    var mid = Math.floor((low + high) / 2);      // If mid is even and element next to mid is    // same as mid, then output element lies on    // right side, else on left side    if (mid % 2 == 0) {        if (arr[mid] == arr[mid + 1])            search(arr, mid + 2, high);        else            search(arr, low, mid);    }      // If mid is odd    else {        if (arr[mid] == arr[mid - 1])            search(arr, mid + 1, high);        else            search(arr, low, mid - 1);    }}  // Driver Codevar arr = [1, 1, 2, 4, 4, 5, 5, 6, 6];var len = arr.length; search(arr, 0, len - 1) // This is code is contributed// by shubhamsingh10</script>
The required element is 2
Time Complexity: O(Log n)Note: Other Solutions to the question are slight variations of the approaches discussed in this post.
Another Approach: An Efficient Solution can find the required element in O(Log n) time. The idea is to use Binary Search without recursion. All elements before the required have the first occurrence at even index (0, 2, ..and so on) and the next occurrence at odd index (1, 3, ..and so on). 
The approach will be as follows:
Find the middle index assuming mid using start pointer and end pointer. And check the mid element in the following cases
Case 1) If mid element is not equal to mid+1 element  and mid-1 element. This case returns the answer.
Case 2) When mid element is even and equal to mid+1 element this means number is not present in the left side of the array. In this case start pointer will change to mid+1.
Case 3) When mid element is odd and equal to mid-1 element this means number is not present in the left side of the array. In this case start pointer will change to mid+1.
Case 4) When mid element is odd and equal to mid+1 element this means number is not present in the right side of the array. In this case end pointer will change to mid-1.
Case 5) When mid element is even and equal to mid-1 element this means number is not present in the right side of the array. In this case end pointer will change to mid-1. 
Check for all case for possible values of mid till start<=end..
If all checks fail there is no such element.
This solution requires extra checks for edge cases.
Edge Case 1) If only one element is present in the array. Therefore return the only element of the array.
Edge Case 2) If last element of the array is the required element. Therefore return the last element of the array.
Edge Case 3) If first element of the array is the required element. Therefore return the first element of the array.
Below is the implementation based on the above idea: 
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std;int search(int nums[], int n){       // A Binary Search based method to find the element    // that appears only once    int start = 0, end = n - 1, mid;     // For Edge Cases    if (n == 1) // If only one element is in the array        return nums[0];     if (nums[start]        != nums[start + 1]) // If the first element                            // is the element that                            // appears only once        return nums[start];     if (nums[end]        != nums[end - 1]) // If Last element is the element                          // that appears only once        return nums[end];     // Binary Search    while (start <= end)    {        mid = start + (end - start) / 2;               // CASE 1        if (nums[mid] != nums[mid - 1]            && nums[mid] != nums[mid + 1])            return nums[mid];               // CASE 2 and CASE 3        else if ((nums[mid] == nums[mid + 1]                  && mid % 2 == 0)                 || (nums[mid] == nums[mid - 1]                     && mid % 2 != 0))            start = mid + 1;               // CASE 4 and CASE 5        else            end = mid - 1;    }       // If no such element found    return -1;} // Driver codeint main(){    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    int element = search(arr, n);     if (element != -1)        cout << "The required element is " << element;    else        cout << "There is no such element";} // This code is contributed by umadevi9616
class GFG {    public static int search(int[] nums)    {        // A Binary Search based method to find the element        // that appears only once        int start = 0, end = nums.length - 1, mid;         // For Edge Cases        if (nums.length            == 1) // If only one element is in the array            return nums[0];         if (nums[start]            != nums[start + 1]) // If the first element                                // is the element that                                // appears only once            return nums[start];         if (nums[end]            != nums[end                    - 1]) // If Last element is the element                          // that appears only once            return nums[end];         // Binary Search        while (start <= end) {            mid = start + (end - start) / 2;            // CASE 1            if (nums[mid] != nums[mid - 1]                && nums[mid] != nums[mid + 1])                return nums[mid];            // CASE 2 and CASE 3            else if ((nums[mid] == nums[mid + 1]                      && mid % 2 == 0)                     || (nums[mid] == nums[mid - 1]                         && mid % 2 != 0))                start = mid + 1;            // CASE 4 and CASE 5            else                end = mid - 1;        }        // If no such element found        return -1;    }    public static void main(String[] args)    {        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };         int element = search(arr);         if (element != -1)            System.out.println("The required element is "                               + element);        else            System.out.println("There is no such element");    }} // Code Contributed by Arnav Sharma
def search(nums):    # A Binary Search based method to find the element    # that appears only once    start = 0;    end = len(nums)-1;    mid = 0;     # For Edge Cases    if (len(nums) == 1): # If only one element is in the array        return nums[0];     if (nums[start] != nums[start + 1]): # If the first element                                        # is the element that                                        # appears only once        return nums[start];     if (nums[end] != nums[end - 1]): # If Last element is the element                                    # that appears only once        return nums[end];     # Binary Search    while (start <= end):        mid = start + (end - start) // 2;                 # CASE 1        if (nums[mid] != nums[mid - 1] and nums[mid] != nums[mid + 1]):                       return nums[mid];        # CASE 2 and CASE 3        elif((nums[mid] == nums[mid + 1] and mid % 2 == 0) or (nums[mid] == nums[mid - 1] and mid % 2 != 0)):            start = mid + 1;                     # CASE 4 and CASE 5        else:            end = mid - 1;         # If no such element found    return -1; # Driver codeif __name__ == '__main__':    arr = [ 1, 1, 2, 4, 4, 5, 5, 6, 6 ];     element = search(arr);     if (element != -1):        print("The required element is " , element);    else:        print("There is no such element"); # This code is contributed by umadevi9616
using System;public class GFG {    public static int search(int[] nums)    {               // A Binary Search based method to find the element        // that appears only once        int start = 0, end = nums.Length - 1, mid;         // For Edge Cases        if (nums.Length            == 1) // If only one element is in the array            return nums[0];         if (nums[start]            != nums[start + 1]) // If the first element                                // is the element that                                // appears only once            return nums[start];         if (nums[end]            != nums[end                    - 1]) // If Last element is the element                          // that appears only once            return nums[end];         // Binary Search        while (start <= end)        {            mid = start + (end - start) / 2;                       // CASE 1            if (nums[mid] != nums[mid - 1]                && nums[mid] != nums[mid + 1])                return nums[mid];                       // CASE 2 and CASE 3            else if ((nums[mid] == nums[mid + 1]                      && mid % 2 == 0)                     || (nums[mid] == nums[mid - 1]                         && mid % 2 != 0))                start = mid + 1;                       // CASE 4 and CASE 5            else                end = mid - 1;        }               // If no such element found        return -1;    }    public static void Main(String[] args)    {        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };         int element = search(arr);         if (element != -1)            Console.WriteLine("The required element is "                               + element);        else            Console.WriteLine("There is no such element");    }} // This code is contributed by gauravrajput1
<script>   function search(nums)    {             // A Binary Search based method to find the element        // that appears only once        var start = 0, end = nums.length - 1, mid;         // For Edge Cases        if (nums.length            == 1) // If only one element is in the array            return nums[0];         if (nums[start]            != nums[start + 1]) // If the first element                                // is the element that                                // appears only once            return nums[start];         if (nums[end]            != nums[end                    - 1]) // If Last element is the element                          // that appears only once            return nums[end];         // Binary Search        while (start <= end)        {            mid = start + (end - start) / 2;                         // CASE 1            if (nums[mid] != nums[mid - 1]                && nums[mid] != nums[mid + 1])                return nums[mid];                             // CASE 2 and CASE 3            else if ((nums[mid] == nums[mid + 1]                      && mid % 2 == 0)                     || (nums[mid] == nums[mid - 1]                         && mid % 2 != 0))                start = mid + 1;                             // CASE 4 and CASE 5            else                end = mid - 1;        }                 // If no such element found        return -1;    }             var arr = [ 1, 1, 2, 4, 4, 5, 5, 6, 6 ];        var element = search(arr);        if (element = 2)            document.write("The required element is "                               + element);        else            document.write("There is no such element"); // This code is contributed by shivanisinghss2110</script>
The required element is 2
This solution is contributed by Arnav Sharma. 
Time Complexity: O(logn)Auxiliary Space: O(1)
 This article is contributed by Mehboob Elahi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Aalaa Abdel Mawla
nitin mittal
AntonyCherepanov
Hanny_1012
shubhamsingh84100
yashbeersingh42
shivanisinghss2110
divyeshrabadiya07
divyesh072019
kathahemanthreddy2001
surbhityagi15
arnavsharma2711
GauravRajput1
umadevi9616
Amazon
Binary Search
D-E-Shaw
Ola Cabs
Arrays
Divide and Conquer
Searching
Amazon
D-E-Shaw
Ola Cabs
Arrays
Searching
Divide and Conquer
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Queue | Set 1 (Introduction and Array Implementation)
Linked List vs Array
Subset Sum Problem | DP-25
Merge Sort
QuickSort
Binary Search
Program for Tower of Hanoi
Divide and Conquer Algorithm | Introduction