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
Find the closest pair from two sorted arrays Given two arrays arr1[0...m-1] and arr2[0..n-1], and a number x, the task is to find the pair arr1[i] + arr2[j] such that absolute value of (arr1[i] + arr2[j] - x) is minimum. Example: Input: arr1[] = {1, 4, 5, 7}; arr2[] = {10, 20, 30, 40}; x = 32Output: 1 and 30Input: arr1[] = {1, 4, 5, 7}; arr2[]
15+ min read
K-th Element of Merged Two Sorted Arrays Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays.Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1,
15+ min read
Intersection of Two Sorted Arrays Given two sorted arrays a[] and b[], the task is to return intersection. Intersection of two arrays is said to be elements that are common in both arrays. The intersection should not count duplicate elements and the result should contain items in sorted order.Examples:Input: a[] = {1, 1, 2, 2, 2, 4}
12 min read
Print uncommon elements from two sorted arrays Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements ar
6 min read
Intersection of Two Sorted Arrays with Distinct Elements Given two sorted arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We need to return the intersection in sorted order.Note: Intersection of two arrays can be defined as a set containing distinct common ele
13 min read
Check if the relative ordering of elements in given two Arrays is same or not Given two arrays A[] and B[] each of size N, the task is to check if the sequencing of both the arrays is the same or not. If the sequencing of both the arrays is same, the print Yes otherwise print No.Examples:Input: A[] = { 10, 12, 9, 11 }, B[] = { 2, 7, -3, 5 };Output: YesExplanation: In both the
7 min read