Find the element that appears once in a sorted array

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++
// 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
// 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-1; 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
# 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#
// 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 |
Javascript
<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)
Auxiliary Space: O(1), Â since no extra space has been taken.
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++
// 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
// 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
# 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#
// 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 |
Javascript
<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)
Auxiliary Space: 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.Â
- Find the middle index, say ‘mid’.
- 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.
- 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++ 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
// 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
// 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 |
Python
# 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#
// 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. |
Javascript
<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> |
PHP
<?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?> |
The required element is 2
Time Complexity: O(Log n)
Auxiliary Space: O(1)Â
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++
#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 |
Java
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 |
Python3
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 |
C#
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 |
Javascript
<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.
Another Approach:-
We can simply use hashmap to store the frequency of the elements and after that we can just traverse the hashmap to find the element with frequency 1.
Implementation:
C++
// C++ program to find the element that// appears only once#include <bits/stdc++.h>using namespace std;Â
// function to find element using hashmapvoid search(int arr[], int n){    // taking hashmap to store frequency    unordered_map<int, int> mm;Â
    // iterating over array    for (int i = 0; i < n; i++) {        // storing frequency        mm[arr[i]]++;    }Â
    // iterating over map    for (auto x : mm) {        // if element found        if (x.second == 1) {            // printing element            cout << x.first << endl;            break;        }    }}Â
// 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 shubhamrajput6156 |
Java
// Java program to find the element that// appears only onceimport java.util.*;class GFG {Â
  // function to find element using hashmap  static void search(int arr[], int n)  {    // taking hashmap to store frequency    HashMap<Integer,Integer> mm=new HashMap<Integer,Integer>();Â
    // iterating over array    for(int i = 0; i < arr.length; i++) {      if (mm.containsKey(arr[i])) {        int count = mm.get(arr[i]) +1;        mm.put(arr[i], count);      } else{        mm.put(arr[i],1);      }    }Â
    // iterating over map    for(Map.Entry<Integer,Integer> x : mm.entrySet()){         int c= x.getValue();      // if element found      if(c == 1){        // printing element        System.out.println(x.getKey());        break;      }       }  }Â
  // Driver Code  public static void main(String[] args) {    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };    int len = arr.length;Â
    // function calling    search(arr, len);Â
    return ;  }}Â
// This code is contributed by bhardwajji |
Python3
# Python3 program to find the element that# appears only onceÂ
# function to find element using dictionaryÂ
Â
def search(arr):    # taking dictionary to store frequency    freq = {}Â
    # iterating over array    for i in arr:        # storing frequency        if i in freq:            freq[i] += 1        else:            freq[i] = 1Â
    # iterating over dictionary    for key, value in freq.items():        # if element found        if value == 1:            # printing element            print(key)            breakÂ
Â
# Driver codeif __name__ == '__main__':Â Â Â Â arr = [1, 1, 2, 4, 4, 5, 5, 6, 6]Â
    search(arr) |
C#
using System;using System.Collections.Generic;Â
class GFG {Â
  // function to find element using Dictionary  static void Search(int[] arr, int n) {    // taking Dictionary to store frequency    Dictionary<int,int> mm = new Dictionary<int,int>();Â
    // iterating over array    for(int i = 0; i < arr.Length; i++) {      if (mm.ContainsKey(arr[i])) {        int count = mm[arr[i]] + 1;        mm[arr[i]] = count;      } else{        mm.Add(arr[i], 1);      }    }Â
    // iterating over Dictionary    foreach(KeyValuePair<int,int> x in mm) {         int c = x.Value;      // if element found      if(c == 1){        // printing element        Console.WriteLine(x.Key);        break;      }       }  }Â
  // Driver Code  public static void Main(string[] args) {    int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };    int len = arr.Length;Â
    // function calling    Search(arr, len);Â
    return ;  }} |
Javascript
// Javascript equivalent of above codeÂ
// function to find element using dictionaryfunction search(arr){    // taking dictionary to store frequency    let freq = {};Â
    // iterating over array    for (let i of arr){        // storing frequency        if (i in freq){             freq[i] += 1;        }        else{            freq[i] = 1;        }    }Â
    // iterating over dictionary    for (let [key, value] of Object.entries(freq)){        // if element found        if (value == 1){            // printing element            console.log(key);            break;        }    }}Â
// Driver codeÂ
    arr = [1, 1, 2, 4, 4, 5, 5, 6, 6];Â
    search(arr); |
2
Time Complexity:- O(N)
Auxiliary Space:- O(N)
Another Approach Using Stacks:
We know that the given array is sorted in non-decreasing (ascending) order, and that every element occurs twice except for 1 element. The approach involves using a stack while iterating through the entire array. While pushing in elements, we may push this singular element on to the stack. By the end of the iteration we will have that singular element on the top of the stack which is returned.
While iterating through the array, if we have no element in the stack, or the consective element is not equal to the top most element in the stack, we can push that element to the stack. Else we can pop the top element from the stack. Finally, we can return the top most element, which is the singular element in the array.
C++
// C++ program to find the element that// appears only once#include <bits/stdc++.h>using namespace std;Â
// function to find element using stackint singleNonDuplicate(vector<int>& nums) {         //declaring the stack for stroing elements        stack<int> stk;          //traversing linearly over the entire array        for (int i = 0; i < nums.size(); i++) {              /*checking if element is presnt in the stack           or the current array element equal to stack's top element*/            if (stk.empty() or nums[i] != stk.top()) {              //pushing the element in the stack if conditions satisfied                stk.push(nums[i]);            } else {              //If condition doesn't match pop elements from the stack                stk.pop();            }        }          //return the topmost element from the stack        return stk.top();    }Â
// Driver codeint main(){  //declaring a vector    vector<int> arr{ 1, 1, 2, 4, 4, 5, 5, 6, 6 };    //calling function    cout<<singleNonDuplicate(arr)<<endl;Â
    return 0;}Â
// This code is contributed by shubhamrajput6156 |
Java
// Java program to find the element that// appears only onceÂ
import java.util.Stack;Â
public class GFG {Â
    // function to find element using stack    public static int singleNonDuplicate(int[] nums) {        // declaring the stack for storing elements        Stack<Integer> stk = new Stack<>();Â
        // traversing linearly over the entire array        for (int i = 0; i < nums.length; i++) {            /* checking if the stack is empty or the current array element is not equal to                stack's top element */            if (stk.isEmpty() || nums[i] != stk.peek()) {                // pushing the element into the stack if the conditions are satisfied                stk.push(nums[i]);            } else {                // If condition doesn't match, pop elements from the stack                stk.pop();            }        }Â
        // return the topmost element from the stack which is the single non-duplicate element        return stk.peek();    }Â
    // Driver code    public static void main(String[] args) {        // declaring an array        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };                 // calling function        System.out.println(singleNonDuplicate(arr));    }} |
Python3
# Python3 program to find the element that# appears only once  # function to find element using stackdef singleNonDuplicate(nums):    # Declaring an empty list to act as a stack for storing elements    stack = []Â
    # Traversing linearly over the entire array    for num in nums:        # Checking if the stack is empty or if the current array element is not equal to the stack's top element        if not stack or num != stack[-1]:            # Pushing the element into the stack if the conditions are satisfied            stack.append(num)        else:            # If the condition doesn't match, it means the current element is a duplicate of the top element in the stack            # So, popping the top element from the stack effectively removes the pair from the stack            stack.pop()Â
    # The remaining element in the stack is the element that appears only once    return stack[-1]Â
# Driver codeif __name__ == "__main__":    # Declaring a list    arr = [1, 1, 2, 4, 4, 5, 5, 6, 6]Â
    # Calling the function    print(singleNonDuplicate(arr)) |
C#
using System;using System.Collections.Generic;Â
namespace SingleNonDuplicate{    class Program    {        static int SingleNonDuplicate(List<int> nums)        {            // declaring the stack for storing elements            Stack<int> stk = new Stack<int>();Â
            // traversing linearly over the entire array            foreach (int num in nums)            {                // checking if element is present in the stack                 // or the current array element equal to stack's top element                if (stk.Count == 0 || num != stk.Peek())                {                    // pushing the element in the stack if conditions satisfied                    stk.Push(num);                }                else                {                    // if condition doesn't match, pop elements from the stack                    stk.Pop();                }            }Â
            // return the topmost element from the stack            return stk.Peek();        }Â
        static void Main(string[] args)        {            // declaring a list            List<int> arr = new List<int> { 1, 1, 2, 4, 4, 5, 5, 6, 6 };Â
            // calling function            Console.WriteLine(SingleNonDuplicate(arr));        }    }}Â
// This code is contributed by rambabuguphka |
Javascript
function singleNonDuplicate(nums) {    // Initialize an empty stack    const stack = [];Â
    // Traverse the array linearly    for (let i = 0; i < nums.length; i++) {        // Check if the stack is empty or the current         // array element is not equal to the stack's top element        if (stack.length === 0 || nums[i] !== stack[stack.length - 1]) {            // Push the element onto the stack if the conditions are satisfied            stack.push(nums[i]);        } else {            // If the condition doesn't match, pop elements from the stack            stack.pop();        }    }Â
    // Return the topmost element from the stack    return stack[0];}Â
// Driver codeconst arr = [1, 1, 2, 4, 4, 5, 5, 6, 6];console.log(singleNonDuplicate(arr)); // Output: 2 |
Output:
2
Time Complexity:- O(N) for traversing through entire array linearly.
Auxiliary Space:- O(N) for stroing the elements in stack.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



