Open In App

Find extra element in the second array

Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays A[] and B[]. The second array B[] contains all the elements of A[] except for 1 extra element. The task is to find that extra element.
Examples: 

Input: A[] = { 1, 2, 3 }, B[] = {1, 2, 3, 4} 
Output:
Element 4 is not present in array
Input: A[] = {10, 15, 5}, B[] = {10, 100, 15, 5} 
Output: 100 

Naive approach: Run nested loops and find the element in B[] which is not present in A[]. The time complexity of this approach will be O(n2).
Efficient approach: If all the elements of the A[] and B[] are XORed together then every element of A[] will give 0 with its occurrence in B[] and the extra element say X when XORed with 0 will give (X XOR 0) = X which is the result.
Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the extra
// element in B[]
int extraElement(int A[], int B[], int n)
{
 
    // To store the result
    int ans = 0;
 
    // Find the XOR of all the element
    // of array A[] and array B[]
    for (int i = 0; i < n; i++)
        ans ^= A[i];
    for (int i = 0; i < n + 1; i++)
        ans ^= B[i];
 
    return ans;
}
 
// Driver code
int main()
{
    int A[] = { 10, 15, 5 };
    int B[] = { 10, 100, 15, 5 };
    int n = sizeof(A) / sizeof(int);
 
    cout << extraElement(A, B, n);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
     
    // Function to return the extra
    // element in B[]
    static int extraElement(int A[], int B[], int n)
    {
     
        // To store the result
        int ans = 0;
     
        // Find the XOR of all the element
        // of array A[] and array B[]
        for (int i = 0; i < n; i++)
            ans ^= A[i];
        for (int i = 0; i < n + 1; i++)
            ans ^= B[i];
     
        return ans;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int A[] = { 10, 15, 5 };
        int B[] = { 10, 100, 15, 5 };
        int n = A.length;
     
        System.out.println(extraElement(A, B, n));
    }
}
 
// This code is contributed by kanugargng


Python3




# Python3 implementation of the approach
# Function to return the extra
# element in B[]
def extraElement(A, B, n):
 
    # To store the result
    ans = 0;
 
    # Find the XOR of all the element
    # of array A[] and array B[]
    for i in range(n):
        ans ^= A[i];
    for i in range(n + 1):
        ans ^= B[i];
 
    return ans;
 
# Driver code
A = [ 10, 15, 5 ];
B = [ 10, 100, 15, 5 ];
n = len(A);
 
print(extraElement(A, B, n));
 
# This code is contributed by 29AjayKumar


C#




// C# implementation of the approach
using System;
     
class GFG
{
     
    // Function to return the extra
    // element in B[]
    static int extraElement(int []A,
                            int []B, int n)
    {
     
        // To store the result
        int ans = 0;
     
        // Find the XOR of all the element
        // of array A[] and array B[]
        for (int i = 0; i < n; i++)
            ans ^= A[i];
        for (int i = 0; i < n + 1; i++)
            ans ^= B[i];
     
        return ans;
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int []A = { 10, 15, 5 };
        int []B = { 10, 100, 15, 5 };
        int n = A.Length;
     
        Console.WriteLine(extraElement(A, B, n));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// Javascript implementation of the approach
 
// Function to return the extra
// element in B[]
function extraElement(A, B, n)
{
 
    // To store the result
    let ans = 0;
 
    // Find the XOR of all the element
    // of array A[] and array B[]
    for (let i = 0; i < n; i++)
        ans ^= A[i];
    for (let i = 0; i < n + 1; i++)
        ans ^= B[i];
 
    return ans;
}
 
// Driver code
    let A = [ 10, 15, 5 ];
    let B = [ 10, 100, 15, 5 ];
    let n = A.length;
 
    document.write(extraElement(A, B, n));
 
// This code is contributed by subhammahato348.
</script>


Output: 

100

 

Time Complexity: O(N) 
Space Complexity: O(1)

Approach 2: Using binary search

  •  Initialize two pointers low and high to the first and last index of the second array respectively.
  • While low is less than or equal to high, repeat steps 3-5:
  • Find the middle index mid of the search space by taking the average of low and high.
  • Compare the element at index mid of the second array with the element at the same index in the first array. 
    • If they are equal, then the extra element is on the right side of the middle index. So, set low to mid + 1.
    • If the elements at index mid are not equal, then the extra element is on the left side of the middle index. So, set high to mid-1.
  • After the loop, return the element at the low index of the second array, as this is the extra element.

C++




#include <iostream>
using namespace std;
 
int binarySearch(int arr[], int low, int high, int x) {
    if (high >= low) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == x) {
            return mid;
        }
        if (arr[mid] > x) {
            return binarySearch(arr, low, mid - 1, x);
        }
        return binarySearch(arr, mid + 1, high, x);
    }
    return -1;
}
 
int findExtra(int arr1[], int arr2[], int n) {
    int low = 0, high = n - 2;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (arr2[mid] == arr1[mid]) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return arr2[low];
}
 
int main() {
    int arr1[] = { 10, 15, 5 };
    int arr2[] = { 10, 100,15, 5 };
    int n = sizeof(arr2) / sizeof(arr2[0]);
    cout << findExtra(arr1, arr2, n) << endl;
    return 0;
}


Java




public class FindExtraElement {
    public static int binarySearch(int[] arr, int low, int high, int x) {
        if (high >= low) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x) {
                return mid;
            }
            if (arr[mid] > x) {
                return binarySearch(arr, low, mid - 1, x);
            }
            return binarySearch(arr, mid + 1, high, x);
        }
        return -1;
    }
 
    public static int findExtra(int[] arr1, int[] arr2, int n) {
        int low = 0, high = n - 2;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (arr2[mid] == arr1[mid]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return arr2[low];
    }
 
    public static void main(String[] args) {
        int[] arr1 = { 10, 15, 5 };
        int[] arr2 = { 10, 100, 15, 5 };
        int n = arr2.length;
        System.out.println(findExtra(arr1, arr2, n));
    }
}


Python3




def binarySearch(arr, low, high, x):
    if high >= low:
        mid = low + (high - low) // 2
        if arr[mid] == x:
            return mid
        if arr[mid] > x:
            return binarySearch(arr, low, mid - 1, x)
        return binarySearch(arr, mid + 1, high, x)
    return -1
 
def findExtra(arr1, arr2, n):
    low, high = 0, n - 2
    while low <= high:
        mid = (low + high) // 2
        if arr2[mid] == arr1[mid]:
            low = mid + 1
        else:
            high = mid - 1
    return arr2[low]
 
arr1 = [10, 15, 5]
arr2 = [10, 100, 15, 5]
n = len(arr2)
print(findExtra(arr1, arr2, n))


C#




using System;
 
class Program
{
    static int BinarySearch(int[] arr, int low, int high, int x)
    {
        if (high >= low)
        {
            int mid = low + (high - low) / 2;
            if (arr[mid] == x)
            {
                return mid;
            }
            if (arr[mid] > x)
            {
                return BinarySearch(arr, low, mid - 1, x);
            }
            return BinarySearch(arr, mid + 1, high, x);
        }
        return -1;
    }
 
    static int FindExtra(int[] arr1, int[] arr2, int n)
    {
        int low = 0, high = n - 2;
        while (low <= high)
        {
            int mid = (low + high) / 2;
            if (arr2[mid] == arr1[mid])
            {
                low = mid + 1;
            }
            else
            {
                high = mid - 1;
            }
        }
        return arr2[low];
    }
 
    static void Main()
    {
        int[] arr1 = { 10, 15, 5 };
        int[] arr2 = { 10, 100, 15, 5 };
        int n = arr2.Length;
        Console.WriteLine(FindExtra(arr1, arr2, n));
    }
}


Javascript




function binarySearch(arr, low, high, x) {
    if (high >= low) {
        let mid = low + Math.floor((high - low) / 2);
        if (arr[mid] === x) {
            return mid;
        }
        if (arr[mid] > x) {
            return binarySearch(arr, low, mid - 1, x);
        }
        return binarySearch(arr, mid + 1, high, x);
    }
    return -1;
}
 
function findExtra(arr1, arr2, n) {
    let low = 0, high = n - 2;
    while (low <= high) {
        let mid = Math.floor((low + high) / 2);
        if (arr2[mid] === arr1[mid]) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return arr2[low];
}
 
let arr1 = [ 10, 15, 5 ];
let arr2 = [ 10, 100, 15, 5 ];
let n = arr2.length;
console.log(findExtra(arr1, arr2, n));


Output

100

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

Approach 3: Function to Find the Extra Element in Two Arrays by Calculating the Sum Difference.

  • Calculate the sum of all elements in array A.
  • Calculate the sum of all elements in array B.
  • Return the difference between sum_A and sum_B as the missing element.

Here is the implementation of above approach:-

C++




#include <iostream>
#include <vector>
using namespace std;
 
int extraElement(vector<int> A, vector<int> B) {
    int sum_A = 0, sum_B = 0;
    for (int i = 0; i < A.size(); i++) {
        sum_A += A[i];
    }
    for (int i = 0; i < B.size(); i++) {
        sum_B += B[i];
    }
    return sum_B - sum_A;
}
 
int main() {
    vector<int> A = {10, 15, 5};
    vector<int> B = {10, 100, 15, 5};
    cout << extraElement(A, B) << endl;
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static int extraElement(int[] A, int[] B) {
        int sum_A = 0, sum_B = 0;
        for (int i = 0; i < A.length; i++) {
            sum_A += A[i];
        }
        for (int i = 0; i < B.length; i++) {
            sum_B += B[i];
        }
        return sum_B - sum_A;
    }
 
    public static void main(String[] args) {
        int[] A = {10, 15, 5};
        int[] B = {10, 100, 15, 5};
        System.out.println(extraElement(A, B));
    }
}


Python3




def extraElement(A, B):
    sum_A = sum(A)
    sum_B = sum(B)
    return sum_B - sum_A
 
A = [10, 15, 5]
B = [10, 100, 15, 5]
print(extraElement(A, B))


C#




using System;
 
public class Program
{
    public static int extraElement(int[] A, int[] B)
    {
        int sum_A = 0, sum_B = 0;
        for (int i = 0; i < A.Length; i++)
        {
            sum_A += A[i];
        }
        for (int i = 0; i < B.Length; i++)
        {
            sum_B += B[i];
        }
        return sum_B - sum_A;
    }
 
    public static void Main()
    {
        int[] A = {10, 15, 5};
        int[] B = {10, 100, 15, 5};
        int n = A.Length;
        Console.WriteLine(extraElement(A, B));
    }
}


Javascript




function extraElement(A, B) {
    let sum_A = 0, sum_B = 0;
    for (let i = 0; i < A.length; i++) {
        sum_A += A[i];
    }
    for (let i = 0; i < B.length; i++) {
        sum_B += B[i];
    }
    return sum_B - sum_A;
}
 
let A = [10, 15, 5];
let B = [10, 100, 15, 5];
let n = A.length;
console.log(extraElement(A, B));


Output

100

The time complexity of the function is O(N) because it needs to iterate over each element in both arrays to calculate their sums.

The space complexity of the function is O(1) because it only requires a constant amount of extra space to store the two sum variables.



Last Updated : 26 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads