The Wayback Machine - https://web.archive.org/web/20240818163942/https://www.geeksforgeeks.org/find-element-appears-array-every-element-appears-twice/
Open In App

Find the element that appears once in an array where every other element appears twice

Last Updated : 20 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of integers. All numbers occur twice except one number which occurs once. Find the number in O(n) time & constant extra space.

Example : 

Input:  arr[] = {2, 3, 5, 4, 5, 3, 4}
Output: 2 

Approach (Brute-force): One solution is to check every element if it appears once or not. Once an element with a single occurrence is found, return it. 

Below is the implementation of the approach:

C++




// C++ program to find the array element
// that appears only once
  
#include <iostream>
using namespace std;
  
// Function to find the
int findSingle(int A[], int ar_size)
{
  
    // Iterate over every element
    for (int i = 0; i < ar_size; i++) {
  
        // Initialize count to 0
        int count = 0;
  
        for (int j = 0; j < ar_size; j++) {
  
            // Count the frequency
            // of the element
            if (A[i] == A[j]) {
                count++;
            }
        }
  
        // if the frequency of the
        // element is one
        if (count == 1) {
            return A[i];
        }
    }
  
    // if no element exist at most once
    return -1;
}
  
// Driver code
int main()
{
    int ar[] = { 2, 3, 5, 4, 5, 3, 4 };
    int n = sizeof(ar) / sizeof(ar[0]);
    
      // Function call
    cout << "Element occurring once is "
         << findSingle(ar, n);
    
    return 0;
}
  
// This code is contributed by Arpit Jain


Java




/*package whatever //do not write package name here */
import java.io.*;
class GFG {
  
  // Function to find the
  static int findSingle(int A[], int ar_size)
  {
  
    // Iterate over every element
    for (int i = 0; i < ar_size; i++) {
  
      // Initialize count to 0
      int count = 0;
  
      for (int j = 0; j < ar_size; j++) {
  
        // Count the frequency
        // of the element
        if (A[i] == A[j]) {
          count++;
        }
      }
  
      // if the frequency of the
      // element is one
      if (count == 1) {
        return A[i];
      }
    }
  
    // if no element exist at most once
    return -1;
  }
  
  public static void main (String[] args) {
    int ar[] = { 2, 3, 5, 4, 5, 3, 4 };
    int n = ar.length;
  
    // Function call
    System.out.println("Element occurring once is " + findSingle(ar, n));
  }
}
  
// This code is contributed by aadityaburujwale.


Python3




# Python code to find the array element that appears only once
  
# Function to find the array
# element that appears only once
def findSingle(A, ar_size):
    
    # iterate over every element
    for i in range(ar_size):
        
        # Initialize count to 0
        count = 0
        for j in range(ar_size):
            
            # Count the frequency
            # of the element
            if(A[i] == A[j]):
                count += 1
  
        # If the frequency of
        # the element is one
        if(count == 1):
            return A[i]
            
    # If no element exist
    # at most once
    return -1
  
ar = [2, 3, 5, 4, 5, 3, 4]
n = len(ar)
# Function call
print("Element occurring once is", findSingle(ar, n))
  
# This code is contributed by lokesh


C#




// Include namespace system
using System;
  
public class GFG
{
  
  // Function to find the
  public static int findSingle(int[] A, int ar_size)
  {
  
    // Iterate over every element
    for (int i = 0; i < ar_size; i++)
    {
  
      // Initialize count to 0
      var count = 0;
      for (int j = 0; j < ar_size; j++)
      {
  
        // Count the frequency
        // of the element
        if (A[i] == A[j])
        {
          count++;
        }
      }
  
      // if the frequency of the
      // element is one
      if (count == 1)
      {
        return A[i];
      }
    }
  
    // if no element exist at most once
    return -1;
  }
  public static void Main(String[] args)
  {
    int[] ar = {2, 3, 5, 4, 5, 3, 4};
    var n = ar.Length;
  
    // Function call
    Console.WriteLine("Element occurring once is " + 
                      GFG.findSingle(ar, n).ToString());
  }
}
  
// This code is contributed by aadityaburujwale.


Javascript




// Javascript program to find the array element
// that appears only once
  
    // Function to find the
    function findSingle(A, ar_size)
{
  
    // Iterate over every element
    for (let i = 0; i < ar_size; i++) {
  
        // Initialize count to 0
        let count = 0;
  
        for (let j = 0; j < ar_size; j++) {
  
            // Count the frequency
            // of the element
            if (A[i] == A[j]) {
                count++;
            }
        }
  
        // if the frequency of the
        // element is one
        if (count == 1) {
            return A[i];
        }
    }
  
    // if no element exist at most once
    return -1;
}
  
// Driver code
let ar = [ 2, 3, 5, 4, 5, 3, 4 ];
let n = 7;
  
// Function call
document.write("Element occurring once is "
               + findSingle(ar, n));
  
// This code is contributed by garg28harsh.


Output

Element occurring once is 2

Time complexity of this solution is O(n2)
Auxiliary Space: O(1) as constant space is used.

A better solution is to use hashing. 

  1. Traverse all elements and put them in a hash table. Element is used as key and the count of occurrences is used as the value in the hash table. 
  2. Traverse the array again and print the element with count 1 in the hash table. 

This solution works in O(n) time but requires extra space.

The best solution is to use XOR. XOR of all array elements gives us the number with a single occurrence. The idea is based on the following two facts. 

  1.  XOR of a number with itself is 0. 
  2. XOR of a number with 0 is number itself.
Let us consider the above example.  
Let ^ be xor operator as in C and C++.

res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4

Since XOR is associative and commutative, above 
expression can be written as:
res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)  
    = 7 ^ 0 ^ 0 ^ 0
    = 7 ^ 0
    = 7 

Below are implementations of above algorithm. 

C++




// C++ program to find the array element
// that appears only once
#include <iostream>
using namespace std;
  
int findSingle(int ar[], int ar_size)
{
    // Do XOR of all elements and return
    int res = ar[0];
    for (int i = 1; i < ar_size; i++)
        res = res ^ ar[i];
  
    return res;
}
  
// Driver code
int main()
{
    int ar[] = { 2, 3, 5, 4, 5, 3, 4 };
    int n = sizeof(ar) / sizeof(ar[0]);
    cout << "Element occurring once is "
         << findSingle(ar, n);
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to find the array element that appears only
// once
#include <stdio.h>
  
int findSingle(int ar[], int ar_size)
{
    // Do XOR of all elements and return
    int res = ar[0];
    for (int i = 1; i < ar_size; i++)
        res = res ^ ar[i];
    return res;
}
  
// Driver code
int main()
{
    int ar[] = { 2, 3, 5, 4, 5, 3, 4 };
    int n = sizeof(ar) / sizeof(ar[0]);
    printf("Element occurring once is %d",
           findSingle(ar, n));
    return 0;
}
  
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to find the array 
// element that appears only once
import java.io.*;
class MaxSum
{
    // Return the maximum Sum of difference
    // between consecutive elements.
    static int findSingle(int ar[], int ar_size)
    {
        // Do XOR of all elements and return
        int res = ar[0];
        for (int i = 1; i < ar_size; i++)
            res = res ^ ar[i];
      
        return res;
    }
  
    // Driver code
    public static void main (String[] args)
    {
        int ar[] = {2, 3, 5, 4, 5, 3, 4};
        int n = ar.length;
        System.out.println("Element occurring once is " +
                            findSingle(ar, n) + " ");
    }
}
// This code is contributed by Prakriti Gupta


Python3




# function to find the once 
# appearing element in array
def findSingle( ar, n):
      
    res = ar[0]
      
    # Do XOR of all elements and return
    for i in range(1,n):
        res = res ^ ar[i]
      
    return res
  
# Driver code
ar = [2, 3, 5, 4, 5, 3, 4]
print "Element occurring once is", findSingle(ar, len(ar))
  
# This code is contributed by __Devesh Agrawal__


C#




// C# program to find the array 
// element that appears only once
using System;
  
class GFG
{
    // Return the maximum Sum of difference
    // between consecutive elements.
    static int findSingle(int []ar, int ar_size)
    {
        // Do XOR of all elements and return
        int res = ar[0];
        for (int i = 1; i < ar_size; i++)
            res = res ^ ar[i];
      
        return res;
    }
  
    // Driver code
    public static void Main ()
    {
        int []ar = {2, 3, 5, 4, 5, 3, 4};
        int n = ar.Length;
        Console.Write("Element occurring once is " +
                            findSingle(ar, n) + " ");
    }
}
  
// This code is contributed by nitin mittal.


PHP




<?php
// PHP program to find the array 
// element that appears only once
  
function findSingle($ar, $ar_size)
    {
          
        // Do XOR of all 
        // elements and return
        $res = $ar[0];
        for ($i = 1; $i < $ar_size; $i++)
            $res = $res ^ $ar[$i];
  
        return $res;
    }
  
    // Driver code
    $ar = array(2, 3, 5, 4, 5, 3, 4);
    $n = count($ar);
    echo "Element occurring once is "
         , findSingle($ar, $n);
           
// This code is contributed by anuj_67.
?>


Javascript




<script>
  
// JavaScript program to find the array 
// element that appears only once 
  
function findSingle(ar, ar_size) 
    { 
        // Do XOR of all elements and return 
        let res = ar[0]; 
        for (let i = 1; i < ar_size; i++) 
            res = res ^ ar[i]; 
  
        return res; 
    } 
  
// Driver code  
        let ar = [2, 3, 5, 4, 5, 3, 4]; 
        let n = ar.length; 
        document.write("Element occurring once is "
            + findSingle(ar, n)); 
      
// This code is contributed by Surbhi Tyagi
  
</script>


Output

Element occurring once is 2

Time Complexity: O(n)
Auxiliary Space: O(1)

Another approach: 
This is not an efficient approach but just another way to get the desired results. If we add each number once and multiply the sum by 2, we will get twice the sum of each element of the array. Then we will subtract the sum of the whole array from the twice_sum and get the required number (which appears once in the array).
Array [] : [a, a, b, b, c, c, d] 
Mathematical Equation = 2*(a+b+c+d) – (a + a + b + b + c + c + d) 

In more simple words: 2*(sum_of_array_without_duplicates) – (sum_of_array) 

let arr[] = {7, 3, 5, 4, 5, 3, 4}
Required no = 2*(sum_of_array_without_duplicates) - (sum_of_array)
            = 2*(7 + 3 + 5 + 4) - (7 + 3 + 5 + 4 + 5 + 3 + 4) 
            = 2*     19         -      31 
            = 38 - 31
            = 7 (required answer)

As we know that set does not contain any duplicate element we will be using the set here.

Below is the implementation of above approach: 

C++




// C++ program to find 
// element that appears once
#include <bits/stdc++.h>
  
using namespace std;
  
// function which find number
int singleNumber(int nums[],int n)
{
    map<int,int> m;
    long sum1 = 0,sum2 = 0;
  
    for(int i = 0; i < n; i++)
    {
        if(m[nums[i]] == 0)
        {
            sum1 += nums[i];
            m[nums[i]]++;
        }
        sum2 += nums[i];
    }
      
    // applying the formula.
    return 2 * (sum1) - sum2;
}
  
// Driver code
int main()
{
    int a[] = {2, 3, 5, 4, 5, 3, 4};
    int n = 7;
    cout << singleNumber(a,n) << "\n";
  
    int b[] = {15, 18, 16, 18, 16, 15, 89};
  
    cout << singleNumber(b,n);
    return 0;
}
  
// This code is contributed by mohit kumar 29


Java




// Java program to find 
// element that appears once
import java.io.*;
import java.util.*;
  
class GFG 
{
  
    // function which find number
    static int singleNumber(int[] nums, int n)
    {
        HashMap<Integer, Integer> m = new HashMap<>();
        long sum1 = 0, sum2 = 0;
        for (int i = 0; i < n; i++)
        {
            if (!m.containsKey(nums[i]))
            {
                sum1 += nums[i];
                m.put(nums[i], 1);
            }
            sum2 += nums[i];
        }
  
        // applying the formula.
        return (int)(2 * (sum1) - sum2); 
    }
  
    // Driver code
    public static void main(String args[])
    {
        int[] a = {2, 3, 5, 4, 5, 3, 4};
        int n = 7;
        System.out.println(singleNumber(a,n));
  
        int[] b = {15, 18, 16, 18, 16, 15, 89};
        System.out.println(singleNumber(b,n));
    }
} 
  
// This code is contributed by rachana soma


Python3




# Python3 program to find 
# element that appears once
  
# function which find number
def singleNumber(nums):
  
# applying the formula.
    return 2 * sum(set(nums)) - sum(nums)
  
# driver code
a = [2, 3, 5, 4, 5, 3, 4]
print (int(singleNumber(a)))
  
a = [15, 18, 16, 18, 16, 15, 89]
print (int(singleNumber(a)))
  
# This code is contributed by "Abhishek Sharma 44"


C#




// C# program to find 
// element that appears once
using System;
using System.Collections.Generic;
  
class GFG 
{
  
    // function which find number
    static int singleNumber(int[] nums, int n)
    {
        Dictionary<int,int> m = new Dictionary<int,int>();
        long sum1 = 0, sum2 = 0;
        for (int i = 0; i < n; i++)
        {
            if (!m.ContainsKey(nums[i]))
            {
                sum1 += nums[i];
                m.Add(nums[i], 1);
            }
            sum2 += nums[i];
        }
  
        // applying the formula.
        return (int)(2 * (sum1) - sum2); 
    }
  
    // Driver code
    public static void Main(String []args)
    {
        int[] a = {2, 3, 5, 4, 5, 3, 4};
        int n = 7;
        Console.WriteLine(singleNumber(a,n));
  
        int[] b = {15, 18, 16, 18, 16, 15, 89};
        Console.WriteLine(singleNumber(b,n));
    }
} 
  
/* This code contributed by PrinciRaj1992 */


Javascript




<script>
  
// Javascript program to find
// element that appears once
      
    // function which find number
    function singleNumber(nums,n)
    {
        let m = new Map();
        let sum1 = 0, sum2 = 0;
        for (let i = 0; i < n; i++)
        {
            if (!m.has(nums[i]))
            {
                sum1 += nums[i];
                m.set(nums[i], 1);
            }
            sum2 += nums[i];
        }
   
        // applying the formula.
        return (2 * (sum1) - sum2);
    }
      
    // Driver code
    let a=[2, 3, 5, 4, 5, 3, 4];
    let n = 7;
    document.write(singleNumber(a,n)+"<br>");
      
    let b=[15, 18, 16, 18, 16, 15, 89];
    document.write(singleNumber(b,n));
      
    // This code is contributed by unknown2108
      
</script>


Output

2
89
 

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Another approach:

This is an efficient approach for finding the single element in a list of duplicate elements. In this approach, we are using binary search algorithm to find the single element in the list of duplicates elements. Before that, we need to make sure if the array is sorted. The first step is to sort the array because binary search algorithm wont work if the array is not sorted. 

Now let us move to the binary search implementation:

There are two halves that are created by the only single element present in the array which are left half and right half. Now if there are duplicates present in the left half, then the 1st instance of the duplicate element in the left half is an even index and the 2nd instance is an odd index. The opposite of the left half happens in the right half(1st instance is odd index and the second instance is even index). Now apply binary search algorithm:

  1. The solution is to take two indexes of the array(low and high) where low points to array-index 0 and high points to array-index (array size-2). We take out the mid index from the values by (low+high)/2. 
  2. Now check if the mid index value falls in the left half or the right half. If it falls in the left half then we change the low value to mid+1 and if it falls in the right half, then we change the high index to mid-1. To check it , we used a logic (if(arr[mid]==arr[mid^1]). If mid is an even number then mid^1 will be the next odd index , and if the condition gets satisfied, then we can say that we are in the left index, else we can say we are in the right half. But if mid is an odd index, then mid^1 takes us to mid-1 which is the previous even index , which is gets equal means we are in the right half else left half.
  3. This is done because the aim of this implementation is to find the single element in the list of duplicates. It is only possible if low value is more than high value because at that moment low will be pointing to the index that contains the single element in the array.
  4. After the loop ends, we return the value with low index.

Implementation:

C++




#include <bits/stdc++.h>
using namespace std;
int singleelement(int arr[], int n)
{
    int low = 0, high = n - 2;
    int mid;
    while (low <= high) {
        mid = (low + high) / 2;
        if (arr[mid] == arr[mid ^ 1])
            low = mid + 1;
        else
            high = mid - 1;
    }
    return arr[low];
}
int main()
{
    int arr[] = { 2, 3, 5, 4, 5, 3, 4 };
    int size = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + size);
    cout << singleelement(arr, size);
    return 0;
}
  
// This code is contributed by Sania Kumari Gupta


C




#include <stdio.h>
#include<stdlib.h>
  
// Compare function for qsort
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}
  
int singleelement(int arr[], int n)
{
    int low = 0, high = n - 2;
    int mid;
    while (low <= high) {
        mid = (low + high) / 2;
        if (arr[mid] == arr[mid ^ 1])
            low = mid + 1;
        else
            high = mid - 1;
    }
    return arr[low];
}
  
int main()
{
    int arr[] = { 2, 3, 5, 4, 5, 3, 4 };
    int size = sizeof(arr) / sizeof(arr[0]);
    qsort(arr, size, sizeof(int), cmpfunc);
    printf("%d", singleelement(arr, size));
    return 0;
}
  
// This code is contributed by Sania Kumari Gupta


Java




import java.io.*;
import java.util.Arrays;
  
class GFG{
      
static int singleelement(int arr[], int n)
{
    int low = 0, high = n - 2;
    int mid;
      
    while (low <= high)
    {
        mid = (low + high) / 2;
        if (arr[mid] == arr[mid ^ 1]) 
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
    return arr[low];
}
  
// Driver code
public static void main(String[] args) 
{
    int arr[] = { 2, 3, 5, 4, 5, 3, 4 };
    int size = 7;
    Arrays.sort(arr);
      
    System.out.println(singleelement(arr, size));
}
}
  
// This code is contributed by dassohom5


Python3




def singleelement(arr, n):
    low = 0
    high = n - 2
    mid = 0
    while (low <= high):
        mid = (low + high) // 2
        if (arr[mid] == arr[mid ^ 1]):
            low = mid + 1
        else:
            high = mid - 1
      
    return arr[low]
      
# Driver code
arr = [2, 3, 5, 4, 5, 3, 4]
size = len(arr)
arr.sort()
print(singleelement(arr, size))
  
# This code is contributed by shivanisingh


C#




using System;
using System.Collections;
  
class GFG{
      
static int singleelement(int[] arr, int n)
{
    int low = 0, high = n - 2;
    int mid;
      
    while (low <= high) 
    {
        mid = (low + high) / 2;
          
        if (arr[mid] == arr[mid ^ 1])
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
    return arr[low];
}
  
// Driver code
public static void Main()
{
    int[] arr = { 2, 3, 5, 4, 5, 3, 4 };
    int size = 7;
    Array.Sort(arr);
      
    Console.WriteLine(singleelement(arr, size));
}
}
  
// This code is contributed by dassohom5


Javascript




<script>
  
function singleelement(arr,n)
{
    let low = 0, high = n - 1;
    let mid;
    while (low <= high) {
        mid = (low + high) / 2;
        if (arr[mid] == arr[mid ^ 1]) {
            low = mid + 1;
        }
        else {
            high = mid - 1;
        }
    }
    return arr[low];
}
  
    let arr = [ 2, 3, 5, 4, 5, 3, 4 ];
    let size = arr.length;
    arr = arr.sort(function(a,b){return a-b})
    document.write(singleelement(arr, size));
      
</script>


Output

2

Time Complexity: O(nlogn)
Auxiliary Space: O(1)

Another Approach:-

We can simply use a hashmap to store the frequency of the elements and after that we can iterate the hashmap to find the element with frequency 1.

Code for the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
int singleelement(int arr[], int n)
{
      //hashmap to store frequency
      unordered_map<int,int> mm;
      for(int i=0;i<n;i++)
    {
          //storing frequency
          mm[arr[i]]++;
    }
        
      //iterating over map
      for(auto x:mm)
    {
          //returning element with frequency 1
          if(x.second==1) return x.first;
    }
}
int main()
{
    int arr[] = { 2, 3, 5, 4, 5, 3, 4 };
    int size = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + size);
    cout << singleelement(arr, size);
    return 0;
}


Python3




def singleelement(arr, n):
    #dictionary to store frequency
    mm = {}
    for i in range(n):
        #storing frequency
        if arr[i] in mm:
            mm[arr[i]] += 1
        else:
            mm[arr[i]] = 1
      
    #iterating over dictionary
    for key, value in mm.items():
        #returning element with frequency 1
        if value == 1:
            return key
  
#driver code
arr = [2, 3, 5, 4, 5, 3, 4]
size = len(arr)
arr.sort()
print(singleelement(arr, size))


C#




using System;
using System.Collections.Generic;
  
class Program {
  static int SingleElement(int[] arr, int n)
  {
      
    // hashmap to store frequency
    Dictionary<int, int> mm
      = new Dictionary<int, int>();
    for (int i = 0; i < n; i++)
    {
        
      // storing frequency
      if (!mm.ContainsKey(arr[i])) {
        mm[arr[i]] = 1;
      }
      else {
        mm[arr[i]]++;
      }
    }
  
    // iterating over map
    foreach(KeyValuePair<int, int> x in mm)
    {
      // returning element with frequency 1
      if (x.Value == 1)
        return x.Key;
    }
    return 0;
  }
  
  static void Main(string[] args)
  {
    int[] arr = { 2, 3, 5, 4, 5, 3, 4 };
    int size = arr.Length;
    Array.Sort(arr);
    Console.WriteLine(SingleElement(arr, size));
  }
}
  
// This code is contributed by prajwalkandekar123.


Java




import java.util.*;
  
public class GFG {
    public static int singleElement(int[] arr)
    {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            int freq = map.getOrDefault(arr[i], 0);
            map.put(arr[i], freq + 1);
        }
        for (int i = 0; i < arr.length; i++) {
            if (map.get(arr[i]) == 1) {
                return arr[i];
            }
        }
        return -1; // indicates no unique element found
    }
  
    public static void main(String[] args)
    {
        int[] arr = { 2, 3, 5, 4, 5, 3, 4 };
        Arrays.sort(arr);
        int single = singleElement(arr);
        if (single == -1) {
            System.out.println("No unique element found");
        }
        else {
            System.out.println("Unique element: " + single);
        }
    }
}


Javascript




function singleelement(arr, n)
{
     //hashmap to store frequency
    let mm = new Map();
    
    for (let i=0;i<n;i++) {
        if (mm.has(arr[i])) {
  
            // If number is present in mm,
            // incrementing it's count by 1
            mm.set(arr[i], mm.get(arr[i]) + 1);
        }
        else {
  
            // If integer is not present in mm,
            // putting this integer to mm with 1 as it's value
            mm.set(arr[i], 1);
        }
    }
  
        
      //iterating over map
    for (let [key, value] of mm.entries()) 
    {
          //returning element with frequency 1
          if(value==1) 
            return key;
    }
}
  
let arr = [2, 3, 5, 4, 5, 3, 4 ];
let size = arr.length;
arr.sort();
document.write(singleelement(arr, size));


Output

2

Time Complexity:- O(N)
Auxiliary Space:- O(N)



Previous Article
Next Article

Similar Reads

Combinations where every element appears twice and distance between appearances is equal to the value
Given a positive number n, we need to find all the combinations of 2*n elements such that every element from 1 to n appears exactly twice and distance between its appearances is exactly equal to value of the element. Examples: Input : n = 3 Output : 3 1 2 1 3 2 2 3 1 2 1 3 All elements from 1 to 3 appear twice and distance between two appearances i
7 min read
Find the element that appears once in a sorted array
Given a sorted array in which all elements appear twice and one element appears only once, the task is to find the element that appears once. Examples: Input: arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8}Output: 4Explanation: All numbers except 4 occur twice in the array. Input: arr[] = {1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8}Output: 8Explanation: All numbers
12 min read
Find the element that appears once
Given an array where every element occurs three times, except one element which occurs only once. Find the element that occurs once. Note: Expected time complexity is O(n) and O(1) extra space. Examples: Input: arr[] = {12, 1, 12, 3, 12, 1, 1, 2, 3, 3} Output: 2 In the given array all element appear three times except 2 which appears once. Input: a
15+ min read
Maximum in array which is at-least twice of other elements
Given an array of integers of length n. Our task is to return the index of the max element if the it is at least twice as much as every other number in the array. If the max element does not satisfy the condition return -1. Examples: Input : arr = {3, 6, 1, 0} Output : 1 Here, 6 is the largest integer, and for every other number in the array x, 6 i
7 min read
Sequences of given length where every element is more than or equal to twice of previous
Given two integers m &amp; n, find the number of possible sequences of length n such that each of the next element is greater than or equal to twice of the previous element but less than or equal to m. Examples : Input : m = 10, n = 4 Output : 4 There should be n elements and value of last element should be at-most m. The sequences are {1, 2, 4, 8}
13 min read
Maximize sum by shifting from one Array to other at most once
Given two arrays X[] and Y[] of length N each. You can shift from X[] to Y[] at most once. The task is to output the maximum sum possible sum. Examples: Input: N = 4, X[] = {7, 5, 3, 4}, Y[] = {2, 3, 1, 3}Output: 19Explanation: It is optimal to not shift from X[] to Y[]. The total maximum possible sum will be 7 + 5 + 3 + 4 = 19. Input: N = 2, X[] =
7 min read
Minimize replacements to make every element in an array exceed every element in another given array
Given two arrays A[] and B[] of size N and M respectively, where each element is in the range [0, 9], the task is to make each element of the array A[] strictly greater than or smaller than every element in the array B[] by changing any element from either array to any number in the range [0, 9], minimum number of times. Examples: Input: A[] = [0,
10 min read
Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times
Given an array arr[] consisting of N integers and a positive integer K, the task is to find the last element present in the array obtained by repeatedly removing the first element of the array and appending it twice to the end of the array K times. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 5Output: 5Explanation:Initially, the array is {1, 2, 3,
7 min read
Check if max occurring character of one string appears same no. of times in other
Given two strings, we need to take the character which has the maximum occurrence in the first string, and then we have to check if that particular character is present in the second string the same number of times as it is present in the first string.Examples: Input : s1 = "sssgeek", s2 = "geeksss" Output : Yes Max occurring character in s1 is 's'
7 min read
Maximum difference between a pair of adjacent elements by excluding every element once
Given an array arr[] consisting of positive integers, the task for every array element is to find the maximum difference between any two adjacent arrays excluding that element. Examples: Input: arr[] = {1, 3, 4, 7, 8}Output: 3, 4, 4Explanation:Excluding i = 2, arr[] = {1, 4, 7, 8}. Therefore, the maximum adjacent element difference is 3.Excluding i
10 min read
Construct array B as last element left of every suffix array obtained by performing given operations on every suffix of given array
Given an array arr[] of N integers, the task is to print the last element left of every suffix array obtained by performing the following operation on every suffix of the array, arr[]: Copy the elements of the suffix array into an array suff[].Update ith suffix element as suff[i] = (suff[i] OR suff[i+1]) - (suff[i] XOR suff[i+1]) reducing the size
9 min read
Find if possible to visit every nodes in given Graph exactly once based on given conditions
Given a Graph having N+1 nodes with 2*N-1 edges and a boolean array arr[ ], the task is to find if one can visit every nodes exactly once and print any one possible path. It's also known that N-1 edges go i-th to (i+1)-th node and rest edges go i-th to (n+1)-th node if arr[i] is 0 otherwise (n+1)-th to i-th. Examples: Input: N = 3, arr = {0, 1, 0}O
7 min read
Check whether one root of the Quadratic Equation is twice of other or not
Given three numbers A, B, C which represents the coefficients(constants) of a quadratic equation [Tex]Ax^{2} + Bx + C = 0 [/Tex], the task is to check whether one root of the equation represented by these constants is twice of other or not.Examples: Input: A = 1, B = -3, C = 2 Output: Yes Explanation: The given quadratic equation is [Tex]x^{2} - 3x
4 min read
Check if minimum element in array is less than or equals half of every other element
Given an array arr[], the task is to check if the minimum element in the array is less than or equal to half of every other element. If it is then print "yes" otherwise print "no".Note: The minimum number in the given array is always unique. Examples: Input: arr = {2, 1, 4, 5} Output: Yes Explanation: 1 is the minimum element in the array arr[] and
11 min read
Longest subsequence where every character appears at-least k times
Given a string and a number k, find the longest subsequence of a string where every character appears at-least k times. Examples: Input: str = "geeksforgeeks", k = 2Output: geeksgeeksExplanation: Every character in the output subsequence appears at-least 2 times. Input : str = "aabbaabacabb", k = 5Output : aabbaabaabb Method 1 (Brute force): We can
12 min read
Divide every element of one array by other array elements
Given two arrays and the operation to be performed is that the every element of a[] should be divided by all the element of b[] and their floor value has to be calculated. Examples : Input : a[] = {5, 100, 8}, b[] = {2, 3} Output : 0 16 1 Explanation : Size of a[] is 3. Size of b[] is 2. Now 5 has to be divided by the elements of array b[] i.e. 5 i
6 min read
Sum of Bitwise OR of every array element paired with all other array elements
Given an array arr[] consisting of non-negative integers, the task for each array element arr[i] is to print the sum of Bitwise OR of all pairs (arr[i], arr[j]) ( 0 â‰Ī j â‰Ī N ). Examples: Input: arr[] = {1, 2, 3, 4}Output: 12 14 16 22Explanation:For i = 0 the required sum will be (1 | 1) + (1 | 2) + (1 | 3) + (1 | 4) = 12For i = 1 the required sum wi
11 min read
Maximize product of two closest numbers of other array for every element in given array
Given arrays arr1[] of size M and arr2[] of size N having length at least 2, the task is for every element in arr1[], maximize the product of two elements in arr2[] which are closest to the element in arr1[]. The closest elements must be present on distinct indices. Example: Input: arr1 = [5, 10, 17, 22, -1], arr2 = [-1, 26, 5, 20, 14, 17, -7]Outpu
15 min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Count N-digit numbers that contains every possible digit atleast once
Given a positive integer N, the task is to count the number of N-digit numbers such that every digit from [0-9] occurs at least once. Examples : Input: N = 10Output : 3265920 Input: N = 5Output: 0Explanation: Since the number of digits is less than the minimum number of digits required [0-9], the answer is 0. Naive Approach: The simplest approach t
15 min read
Unique paths covering every non-obstacle block exactly once in a grid
Given a grid grid[][] with 4 types of blocks: 1 represents the starting block. There is exactly one starting block.2 represents the ending block. There is exactly one ending block.0 represents an empty block we can walk over.-1 represents obstacles that we cannot walk over.The task is to count the number of paths from the starting block to the endi
11 min read
Replace every element of the array with BitWise XOR of all other
Given an array of integers. The task is to replace every element by the bitwise xor of all other elements of the array. Examples: Input: arr[] = { 2, 3, 3, 5, 5 } Output: 0 1 1 7 7 Bitwise Xor of 3, 3, 5, 5 = 0 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 5, 5 = 1 Bitwise Xor of 2, 3, 3, 5 = 7 Bitwise Xor of 2, 3, 3, 5 = 7 Input : arr[] = { 1
5 min read
Replace every element of the array by sum of all other elements
Given an array of size N, the task is to find the encrypted array. The encrypted array is obtained by replacing each element of the original array with the sum of the remaining array elements i.e. For every i, arr[i] = sumOfArrayElements - arr[i] Examples: Input: arr[] = {5, 1, 3, 2, 4} Output: 10 14 12 13 11 Original array {5, 1, 3, 2, 4} Encrypte
5 min read
Replace every element of the array by product of all other elements
Given an array of positive integers. Replace every element by the product of all other elements of the array. Examples: Input : arr[] = { 2, 3, 3, 5, 7 } Output : 315 210 210 126 90 Approach : First, take the product of all the element of the array.Now replace each element by the product divided by that element.Print the modified array. Below is th
5 min read
Replace every element with the smallest of all other array elements
Given an array arr[] which consist of N integers, the task is to replace every element by the smallest of all other elements present in the array. Examples: Input: arr[] = {1, 1, 1, 2} Output: 1 1 1 1 Input: arr[] = {4, 2, 1, 3} Output: 1 1 2 1 Naive Approach: The simplest approach is to find the smallest of all remaining elements for every element
12 min read
Maximum Difference between Two Elements such that Larger Element Appears after the Smaller Element
Given an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number. Examples : Input : arr = {2, 3, 10, 6, 4, 8, 1}Output : 8Explanation : The maximum difference is between 10 and 2. Input : arr = {7, 9, 5, 6, 3, 2}Output : 2Explanation : The maximum difference is bet
15+ min read
Count of elements in first Array greater than second Array with each element considered only once
Given two sorted array of size N. The task is to find the maximum number of elements in the first array which are strictly greater than the elements of the second array such that an element can be considered only once. Examples: Input: arr1[] = { 20, 30, 50 }, arr2[] = { 25, 40, 60 } Output: 2 Explanation: Maximum 2 elements 30 (30 &gt; 25) and 50
5 min read
Count ways to split array into two equal sum subarrays by replacing each array element to 0 once
Given an array arr[] consisting of N integers, the task is to count the number of ways to split the array into two subarrays of equal sum after changing a single array element to 0. Examples: Input: arr[] = {1, 2, -1, 3}Output: 4Explanation: Replacing arr[0] by 0, arr[] is modified to {0, 2, -1, 3}. Only 1 possible split is {0, 2} and {-1, 3}. Repl
11 min read
Find the only element that appears b times
Given an array where every element occurs 'a' times, except one element which occurs b (a&gt;b) times. Find the element that occurs b times. Examples: Input : arr[] = [1, 1, 2, 2, 2, 3, 3, 3] a = 3, b = 2 Output : 1 Add each number once and multiply the sum by a, we will get a times the sum of each element of the array. Store it as a_sum. Subtract
11 min read
Reduce the array such that each element appears at most K times
Given a sorted array arr of size N, the task is to reduce the array such that each element can appear at most K times.Examples: Input: arr[] = {1, 2, 2, 2, 3}, K = 2 Output: {1, 2, 2, 3} Explanation: Remove 2 once, as it occurs more than 2 times.Input: arr[] = {3, 3, 3}, K = 1 Output: {3} Explanation: Remove 3 twice, as it occurs more than 1 times.
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg