Find elements which are present in first array and not in second
Last Updated :
23 Jul, 2025
Given two arrays, the task is that we find numbers which are present in first array, but not present in the second array.
Examples :
Input : a[] = {1, 2, 3, 4, 5, 10};
b[] = {2, 3, 1, 0, 5};
Output : 4 10
4 and 10 are present in first array, but
not in second array.
Input : a[] = {4, 3, 5, 9, 11};
b[] = {4, 9, 3, 11, 10};
Output : 5
Method 1 (Simple): A Naive Approach is to use two loops and check element which not present in second array.
Implementation:
C++
// C++ simple program to
// find elements which are
// not present in second array
#include<bits/stdc++.h>
using namespace std;
// Function for finding
// elements which are there
// in a[] but not in b[].
void findMissing(int a[], int b[],
int n, int m)
{
for (int i = 0; i < n; i++)
{
int j;
for (j = 0; j < m; j++)
if (a[i] == b[j])
break;
if (j == m)
cout << a[i] << " ";
}
}
// Driver code
int main()
{
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[1]);
findMissing(a, b, n, m);
return 0;
}
Java
// Java simple program to
// find elements which are
// not present in second array
class GFG
{
// Function for finding elements
// which are there in a[] but not
// in b[].
static void findMissing(int a[], int b[],
int n, int m)
{
for (int i = 0; i < n; i++)
{
int j;
for (j = 0; j < m; j++)
if (a[i] == b[j])
break;
if (j == m)
System.out.print(a[i] + " ");
}
}
// Driver Code
public static void main(String[] args)
{
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = a.length;
int m = b.length;
findMissing(a, b, n, m);
}
}
// This code is contributed
// by Anant Agarwal.
Python 3
# Python 3 simple program to find elements
# which are not present in second array
# Function for finding elements which
# are there in a[] but not in b[].
def findMissing(a, b, n, m):
for i in range(n):
for j in range(m):
if (a[i] == b[j]):
break
if (j == m - 1):
print(a[i], end = " ")
# Driver code
if __name__ == "__main__":
a = [ 1, 2, 6, 3, 4, 5 ]
b = [ 2, 4, 3, 1, 0 ]
n = len(a)
m = len(b)
findMissing(a, b, n, m)
# This code is contributed
# by ChitraNayal
C#
// C# simple program to find elements
// which are not present in second array
using System;
class GFG {
// Function for finding elements
// which are there in a[] but not
// in b[].
static void findMissing(int []a, int []b,
int n, int m)
{
for (int i = 0; i < n; i++)
{
int j;
for (j = 0; j < m; j++)
if (a[i] == b[j])
break;
if (j == m)
Console.Write(a[i] + " ");
}
}
// Driver code
public static void Main()
{
int []a = {1, 2, 6, 3, 4, 5};
int []b = {2, 4, 3, 1, 0};
int n = a.Length;
int m = b.Length;
findMissing(a, b, n, m);
}
}
// This code is contributed by vt_m.
JavaScript
<script>
// Javascript simple program to
// find elements which are
// not present in second array
// Function for finding elements
// which are there in a[] but not
// in b[].
function findMissing(a,b,n,m)
{
for (let i = 0; i < n; i++)
{
let j;
for (j = 0; j < m; j++)
if (a[i] == b[j])
break;
if (j == m)
document.write(a[i] + " ");
}
}
// Driver Code
let a=[ 1, 2, 6, 3, 4, 5 ];
let b=[2, 4, 3, 1, 0];
let n = a.length;
let m = b.length;
findMissing(a, b, n, m);
// This code is contributed by avanitrachhadiya2155
</script>
PHP
<?php
// PHP simple program to find
// elements which are not
// present in second array
// Function for finding
// elements which are there
// in a[] but not in b[].
function findMissing( $a, $b, $n, $m)
{
for ( $i = 0; $i < $n; $i++)
{
$j;
for ($j = 0; $j < $m; $j++)
if ($a[$i] == $b[$j])
break;
if ($j == $m)
echo $a[$i] , " ";
}
}
// Driver code
$a = array( 1, 2, 6, 3, 4, 5 );
$b = array( 2, 4, 3, 1, 0 );
$n = count($a);
$m = count($b);
findMissing($a, $b, $n, $m);
// This code is contributed by anuj_67.
?>
Time complexity: O(n*m) since using inner and outer loops
Auxiliary Space : O(1)
Method 2 (Use Hashing): In this method, we store all elements of second array in a hash table (unordered_set). One by one check all elements of first array and print all those elements which are not present in the hash table.
Implementation:
C++
// C++ efficient program to
// find elements which are not
// present in second array
#include<bits/stdc++.h>
using namespace std;
// Function for finding
// elements which are there
// in a[] but not in b[].
void findMissing(int a[], int b[],
int n, int m)
{
// Store all elements of
// second array in a hash table
unordered_set <int> s;
for (int i = 0; i < m; i++)
s.insert(b[i]);
// Print all elements of
// first array that are not
// present in hash table
for (int i = 0; i < n; i++)
if (s.find(a[i]) == s.end())
cout << a[i] << " ";
}
// Driver code
int main()
{
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[1]);
findMissing(a, b, n, m);
return 0;
}
Java
// Java efficient program to find elements
// which are not present in second array
import java.util.HashSet;
import java.util.Set;
public class GfG{
// Function for finding elements which
// are there in a[] but not in b[].
static void findMissing(int a[], int b[],
int n, int m)
{
// Store all elements of
// second array in a hash table
HashSet<Integer> s = new HashSet<>();
for (int i = 0; i < m; i++)
s.add(b[i]);
// Print all elements of first array
// that are not present in hash table
for (int i = 0; i < n; i++)
if (!s.contains(a[i]))
System.out.print(a[i] + " ");
}
public static void main(String []args){
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = a.length;
int m = b.length;
findMissing(a, b, n, m);
}
}
// This code is contributed by Rituraj Jain
Python3
# Python3 efficient program to find elements
# which are not present in second array
# Function for finding elements which
# are there in a[] but not in b[].
def findMissing(a, b, n, m):
# Store all elements of second
# array in a hash table
s = dict()
for i in range(m):
s[b[i]] = 1
# Print all elements of first array
# that are not present in hash table
for i in range(n):
if a[i] not in s.keys():
print(a[i], end = " ")
# Driver code
a = [ 1, 2, 6, 3, 4, 5 ]
b = [ 2, 4, 3, 1, 0 ]
n = len(a)
m = len(b)
findMissing(a, b, n, m)
# This code is contributed by mohit kumar
C#
// C# efficient program to find elements
// which are not present in second array
using System;
using System.Collections.Generic;
class GfG
{
// Function for finding elements which
// are there in a[] but not in b[].
static void findMissing(int []a, int []b,
int n, int m)
{
// Store all elements of
// second array in a hash table
HashSet<int> s = new HashSet<int>();
for (int i = 0; i < m; i++)
s.Add(b[i]);
// Print all elements of first array
// that are not present in hash table
for (int i = 0; i < n; i++)
if (!s.Contains(a[i]))
Console.Write(a[i] + " ");
}
// Driver code
public static void Main(String []args)
{
int []a = { 1, 2, 6, 3, 4, 5 };
int []b = { 2, 4, 3, 1, 0 };
int n = a.Length;
int m = b.Length;
findMissing(a, b, n, m);
}
}
/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
// Javascript efficient program to find elements
// which are not present in second array
// Function for finding elements which
// are there in a[] but not in b[].
function findMissing(a,b,n,m)
{
// Store all elements of
// second array in a hash table
let s = new Set();
for (let i = 0; i < m; i++)
s.add(b[i]);
// Print all elements of first array
// that are not present in hash table
for (let i = 0; i < n; i++)
if (!s.has(a[i]))
document.write(a[i] + " ");
}
let a=[1, 2, 6, 3, 4, 5 ];
let b=[2, 4, 3, 1, 0];
let n = a.length;
let m = b.length;
findMissing(a, b, n, m);
// This code is contributed by patel2127
</script>
Time complexity : O(n+m)
Auxiliary Space : O(n)
Approach 3: Recursion
Algorithm:
- "findMissing" function takes four parameters, array "a" of size "n" and array "b" of size "m".
- Base case : If n==0 , then there are no more elements left to check, so return from the function.
- Recursive case : Check if the first element of array "a" is present in array "b". For this, use a for loop and iterate over all elements of array "b".
- If first element of array "a" is not in array "b", print it.
- Recursively call the "findMissing" function with the remaining elements of array "a" and array "b". For this, increment the pointer of array "a" and decrease it's size "n" by 1.
- Call the recursive function "findMissing" in main() with array "a" and array "b", and their respective sizes "n" and "m".
Here's the implementation:
C++
#include <iostream>
using namespace std;
void findMissing(int a[], int b[], int n, int m) {
// Base case: if n is zero, then there are no more elements to check
if (n == 0) {
return;
}
// Recursive case: check if the first element of a[] is in b[]
int i;
for (i = 0; i < m; i++) {
if (a[0] == b[i]) {
break;
}
}
// If the first element of a[] is not in b[], print it
if (i == m) {
cout << a[0] << " ";
}
// Recursively call findMissing with the remaining elements of a[] and b[]
findMissing(a+1, b, n-1, m);
}
int main() {
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[1]);
findMissing(a, b, n, m);
cout << endl;
return 0;
}
// This code is contributed by Vaibhav Saroj
C
#include <stdio.h>
void findMissing(int a[], int b[], int n, int m) {
// Base case: if n is zero, then there are no more elements to check
if (n == 0) {
return;
}
// Recursive case: check if the first element of a[] is in b[]
int i;
for (i = 0; i < m; i++) {
if (a[0] == b[i]) {
break;
}
}
// If the first element of a[] is not in b[], print it
if (i == m) {
printf("%d ", a[0]);
}
// Recursively call findMissing with the remaining elements of a[] and b[]
findMissing(a+1, b, n-1, m);
}
int main() {
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
findMissing(a, b, n, m);
printf("\n");
return 0;
}
// This code is contributed by Vaibhav Saroj
Java
import java.util.*;
class Main {
public static void findMissing(int[] a, int[] b, int n, int m) {
// Base case: if n is zero, then there are no more elements to check
if (n == 0) {
return;
}
// Recursive case: check if the first element of a[] is in b[]
int i;
for (i = 0; i < m; i++) {
if (a[0] == b[i]) {
break;
}
}
// If the first element of a[] is not in b[], print it
if (i == m) {
System.out.print(a[0] + " ");
}
// Recursively call findMissing with the remaining elements of a[] and b[]
findMissing(Arrays.copyOfRange(a, 1, n), b, n-1, m);
}
public static void main(String[] args) {
int[] a = { 1, 2, 6, 3, 4, 5 };
int[] b = { 2, 4, 3, 1, 0 };
int n = a.length;
int m = b.length;
findMissing(a, b, n, m);
System.out.println();
}
}
// This code is contributed by Vaibhav Saroj
Python3
# code
def find_missing(a, b, n, m):
# Base case: if n is zero, then there are no more elements to check
if n == 0:
return
# Recursive case: check if the first element of a[] is in b[]
i = 0
while i < m:
if a[0] == b[i]:
break
i += 1
# If the first element of a[] is not in b[], print it
if i == m:
print(a[0], end=" ")
# Recursively call find_missing with the remaining elements of a[] and b[]
find_missing(a[1:], b, n - 1, m)
def main():
a = [1, 2, 6, 3, 4, 5]
b = [2, 4, 3, 1, 0]
n = len(a)
m = len(b)
find_missing(a, b, n, m)
print()
if __name__ == "__main__":
main()
#This code is contributed by aeroabrar_31
C#
using System;
public class Program
{
public static void FindMissing(int[] a, int[] b, int n, int m)
{
// Base case: if n is zero, then there are no more elements to check
if (n == 0)
{
return;
}
// Recursive case: check if the first element of a[] is in b[]
int i;
for (i = 0; i < m; i++)
{
if (a[0] == b[i])
{
break;
}
}
// If the first element of a[] is not in b[], print it
if (i == m)
{
Console.Write(a[0] + " ");
}
// Recursively call FindMissing with the remaining elements of a[] and b[]
FindMissing(new ArraySegment<int>(a, 1, n - 1).ToArray(), b, n - 1, m);
}
public static void Main(string[] args)
{
int[] a = { 1, 2, 6, 3, 4, 5 };
int[] b = { 2, 4, 3, 1, 0 };
int n = a.Length;
int m = b.Length;
FindMissing(a, b, n, m);
Console.WriteLine();
}
}
//This code is contributed by aeroabrar_31
JavaScript
function findMissing(a, b, n, m) {
// Base case: if n is zero, then there are no more elements to check
if (n === 0) {
return;
}
// Recursive case: check if the first element of a[] is in b[]
let i;
for (i = 0; i < m; i++) {
if (a[0] === b[i]) {
break;
}
}
// If the first element of a[] is not in b[], print it
if (i === m) {
console.log(a[0] + " ");
}
// Recursively call findMissing with the remaining elements of a[] and b[]
findMissing(a.slice(1), b, n - 1, m);
}
const a = [1, 2, 6, 3, 4, 5];
const b = [2, 4, 3, 1, 0];
const n = a.length;
const m = b.length;
findMissing(a, b, n, m);
console.log(); // add a newline at the end
// This code is contributed by Vaibhav Saroj
This Recursive approach and code is contributed by Vaibhav Saroj .
The time and space complexity:
Time complexity : O(nm) .
Space complexity : O(1) .
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem