Find relative complement of two sorted arrays
Last Updated :
02 Dec, 2023
Given two sorted arrays arr1 and arr2 of size m and n respectively. We need to find relative complement of two array i.e, arr1 - arr2 which means that we need to find all those elements which are present in arr1 but not in arr2.
Examples:
Input : arr1[] = {3, 6, 10, 12, 15}
arr2[] = {1, 3, 5, 10, 16}
Output : 6 12 15
The elements 6, 12 and 15 are present
in arr[], but not present in arr2[]
Input : arr1[] = {10, 20, 36, 59}
arr2[] = {5, 10, 15, 59}
Output : 20 36
- Take two pointers i and j which traverse through arr1 and arr2 respectively.
- If arr1[i] element is smaller than arr2[j] element print this element and increment i.
- If arr1 element is greater than arr2[j] element then increment j.
- otherwise increment i and j.
Implementation:
C++
// CPP program to find all those
// elements of arr1[] that are not
// present in arr2[]
#include <iostream>
using namespace std;
void relativeComplement(int arr1[], int arr2[],
int n, int m) {
int i = 0, j = 0;
while (i < n && j < m) {
// If current element in arr2[] is
// greater, then arr1[i] can't be
// present in arr2[j..m-1]
if (arr1[i] < arr2[j]) {
cout << arr1[i] << " ";
i++;
// Skipping smaller elements of
// arr2[]
} else if (arr1[i] > arr2[j]) {
j++;
// Equal elements found (skipping
// in both arrays)
} else if (arr1[i] == arr2[j]) {
i++;
j++;
}
}
// Printing remaining elements of
// arr1[]
while (i < n)
cout << arr1[i] << " ";
}
// Driver code
int main() {
int arr1[] = {3, 6, 10, 12, 15};
int arr2[] = {1, 3, 5, 10, 16};
int n = sizeof(arr1) / sizeof(arr1[0]);
int m = sizeof(arr2) / sizeof(arr2[0]);
relativeComplement(arr1, arr2, n, m);
return 0;
}
Java
// Java program to find all those
// elements of arr1[] that are not
// present in arr2[]
class GFG
{
static void relativeComplement(int arr1[], int arr2[],
int n, int m)
{
int i = 0, j = 0;
while (i < n && j < m)
{
// If current element in arr2[] is
// greater, then arr1[i] can't be
// present in arr2[j..m-1]
if (arr1[i] < arr2[j])
{
System.out.print(arr1[i] + " ");
i++;
// Skipping smaller elements of
// arr2[]
} else if (arr1[i] > arr2[j])
{
j++;
// Equal elements found (skipping
// in both arrays)
}
else if (arr1[i] == arr2[j])
{
i++;
j++;
}
}
// Printing remaining elements of
// arr1[]
while (i < n){
System.out.print(arr1[i] + " ");
i++;
}
}
// Driver code
public static void main (String[] args)
{
int arr1[] = {3, 6, 10, 12, 15};
int arr2[] = {1, 3, 5, 10, 16};
int n = arr1.length;
int m = arr2.length;
relativeComplement(arr1, arr2, n, m);
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to find all those
# elements of arr1[] that are not
# present in arr2[]
def relativeComplement(arr1, arr2, n, m):
i = 0
j = 0
while (i < n and j < m):
# If current element in arr2[] is
# greater, then arr1[i] can't be
# present in arr2[j..m-1]
if (arr1[i] < arr2[j]):
print(arr1[i] , " ", end="")
i += 1
# Skipping smaller elements of
# arr2[]
elif (arr1[i] > arr2[j]):
j += 1
# Equal elements found (skipping
# in both arrays)
elif (arr1[i] == arr2[j]):
i += 1
j += 1
# Printing remaining elements of
# arr1[]
while (i < n):
print(arr1[i] , " ", end="")
# Driver code
arr1= [3, 6, 10, 12, 15]
arr2 = [1, 3, 5, 10, 16]
n = len(arr1)
m = len(arr2)
relativeComplement(arr1, arr2, n, m)
# This code is contributed
# by Anant Agarwal.
C#
// C# program to find all those
// elements of arr1[] that are not
// present in arr2[]
using System;
namespace Complement
{
public class GFG
{
static void relativeComplement(int []arr1, int []arr2,
int n, int m)
{
int i = 0, j = 0;
while (i < n && j < m)
{
// If current element in arr2[] is
// greater, then arr1[i] can't be
// present in arr2[j..m-1]
if (arr1[i] < arr2[j])
{
Console.Write(arr1[i] + " ");
i++;
// Skipping smaller elements of
// arr2[]
} else if (arr1[i] > arr2[j])
{
j++;
// Equal elements found (skipping
// in both arrays)
}
else if (arr1[i] == arr2[j])
{
i++;
j++;
}
}
// Printing remaining elements of
// arr1[]
while (i < n)
Console.Write(arr1[i] + " ");
}
// Driver code
public static void Main()
{
int []arr1 = {3, 6, 10, 12, 15};
int []arr2 = {1, 3, 5, 10, 16};
int n = arr1.Length;
int m = arr2.Length;
relativeComplement(arr1,arr2, n, m);
}
}
}
// This code is contributed by Sam007
JavaScript
<script>
// JavaScript program to find all those
// elements of arr1[] that are not
// present in arr2[]
function relativeComplement(arr1, arr2,
n, m)
{
let i = 0, j = 0;
while (i < n && j < m)
{
// If current element in arr2[] is
// greater, then arr1[i] can't be
// present in arr2[j..m-1]
if (arr1[i] < arr2[j])
{
document.write(arr1[i] + " ");
i++;
// Skipping smaller elements of
// arr2[]
} else if (arr1[i] > arr2[j])
{
j++;
// Equal elements found (skipping
// in both arrays)
}
else if (arr1[i] == arr2[j])
{
i++;
j++;
}
}
// Printing remaining elements of
// arr1[]
while (i < n)
document.write(arr1[i] + " ");
}
// Driver Code
let arr1 = [3, 6, 10, 12, 15];
let arr2 = [1, 3, 5, 10, 16];
let n = arr1.length;
let m = arr2.length;
relativeComplement(arr1, arr2, n, m);
// This code is contributed by splevel62.
</script>
PHP
<?php
// PHP program to find all those
// elements of arr1[] that are not
// present in arr2[]
function relativeComplement($arr1, $arr2,
$n, $m)
{
$i = 0; $j = 0;
while ($i < $n && $j < $m)
{
// If current element in arr2[] is
// greater, then arr1[i] can't be
// present in arr2[j..m-1]
if ($arr1[$i] < $arr2[$j])
{
echo $arr1[$i] , " ";
$i++;
// Skipping smaller elements of
// arr2[]
}
else if ($arr1[$i] > $arr2[$j])
{
$j++;
// Equal elements found (skipping
// in both arrays)
}
else if ($arr1[$i] == $arr2[$j])
{
$i++;
$j++;
}
}
// Printing remaining elements of
// arr1[]
while ($i < $n)
echo $arr1[$i] , " ";
}
// Driver code
{
$arr1 = array(3, 6, 10, 12, 15);
$arr2 = array(1, 3, 5, 10, 16);
$n = sizeof($arr1) / sizeof($arr1[0]);
$m = sizeof($arr2) / sizeof($arr2[0]);
relativeComplement($arr1, $arr2, $n, $m);
return 0;
}
// This code is contributed by nitin mittal
?>
Time Complexity : O(m + n)
Auxiliary Space: O(1)
Another Approach:
Using an unordered_set we can do the same by following these steps.
- store all the elements of the second array in the set.
- Now traverse the second array and for each element check whether it is present in the set or not
- If the element is not present in the map we add it to our answer array.
Below is the implementation for the same
C++
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
void relativeComplement(int arr1[], int arr2[], int n,
int m)
{
// initializing our set
unordered_set<int> s;
// initialixing our ans vector
vector<int> ans;
// storing elements of the second array in the set
for (int i = 0; i < m; i++)
s.insert(arr2[i]);
// traversing the second array
for (int i = 0; i < n; i++) {
// if the element is not found in the set add it to
// the ans vector
if (s.find(arr1[i]) == s.end())
ans.push_back(arr1[i]);
}
// printing the answer vector.
for (auto x : ans)
cout << x << " ";
}
int main()
{
int arr1[] = { 3, 6, 10, 12, 15 };
int arr2[] = { 1, 3, 5, 10, 16 };
int n = sizeof(arr1) / sizeof(arr1[0]);
int m = sizeof(arr2) / sizeof(arr2[0]);
relativeComplement(arr1, arr2, n, m);
return 0;
}
Java
import java.io.*;
import java.util.*;
public class GFG {
public static void relativeComplement(int[] arr1, int[] arr2, int n, int m) {
// Initializing our set
HashSet<Integer> set = new HashSet<>();
// Initializing our answer ArrayList
ArrayList<Integer> ans = new ArrayList<>();
// Storing elements of the second array in the set
for (int i = 0; i < m; i++) {
set.add(arr2[i]);
}
// Traversing the first array
for (int i = 0; i < n; i++) {
// If the element is not found in the set, add it to the answer ArrayList
if (!set.contains(arr1[i])) {
ans.add(arr1[i]);
}
}
// Printing the answer ArrayList.
for (int x : ans) {
System.out.print(x + " ");
}
}
public static void main(String[] args) {
int[] arr1 = { 3, 6, 10, 12, 15 };
int[] arr2 = { 1, 3, 5, 10, 16 };
int n = arr1.length;
int m = arr2.length;
relativeComplement(arr1, arr2, n, m);
}
}
Python3
def relative_complement(arr1, arr2):
# initializing our set
s = set()
# initializing our ans list
ans = []
# storing elements of the second array in the set
for num in arr2:
s.add(num)
# traversing the first array
for num in arr1:
# if the element is not found in the set, add it to the ans list
if num not in s:
ans.append(num)
# printing the answer list
for x in ans:
print(x, end=" ")
if __name__ == "__main__":
arr1 = [3, 6, 10, 12, 15]
arr2 = [1, 3, 5, 10, 16]
relative_complement(arr1, arr2)
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to find the relative complement of two integer arrays
static void RelativeComplement(int[] arr1, int[] arr2)
{
// Initializing a HashSet to store elements of the second array
HashSet<int> set = new HashSet<int>();
// Initializing a List to store the result
List<int> result = new List<int>();
// Storing elements of the second array in the HashSet
foreach (int num in arr2)
{
set.Add(num);
}
// Traversing the first array
foreach (int num in arr1)
{
// If the element is not found in the HashSet, add it to the result list
if (!set.Contains(num))
{
result.Add(num);
}
}
// Printing the result
foreach (int num in result)
{
Console.Write(num + " ");
}
}
static void Main()
{
int[] arr1 = { 3, 6, 10, 12, 15 };
int[] arr2 = { 1, 3, 5, 10, 16 };
// Call the function to find the relative complement
RelativeComplement(arr1, arr2);
}
}
JavaScript
function relativeComplement(arr1, arr2) {
// initializing our set
let s = new Set();
// initializing our ans array
let ans = [];
// storing elements of the second array in the set
for (let i = 0; i < arr2.length; i++) {
s.add(arr2[i]);
}
// traversing the first array
for (let i = 0; i < arr1.length; i++) {
// if the element is not found in the set, add it to the ans array
if (!s.has(arr1[i])) {
ans.push(arr1[i]);
}
}
// printing the answer array.
console.log(ans.join(' '));
}
// Driver Code
let arr1 = [3, 6, 10, 12, 15];
let arr2 = [1, 3, 5, 10, 16];
relativeComplement(arr1, arr2);
Output:
6 12 15
Time Complexity: O(G) where G is the size of the bigger array.
Auxiliary Space: O(m), we are storing elements of the second array in the set.
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