Check if an array is subset of another array
Given two arrays a[] and b[] of size m and n respectively, the task is to determine whether b[] is a subset of a[]. Both arrays are not sorted, and elements are distinct.
Examples:
Input: a[] = [11, 1, 13, 21, 3, 7], b[] = [11, 3, 7, 1]
Output: trueInput: a[]= [1, 2, 3, 4, 5, 6], b = [1, 2, 4]
Output: trueInput: a[] = [10, 5, 2, 23, 19], b = [19, 5, 3]
Output: false
Table of Content
[Naive approach] Using Nested Loops – O(m*n) Time and O(1) Space
The very basic approach is to use two nested loops: the outer loop picks each element from b[], and the inner loop searches for this element in a[] and check for all elements in b[].
#include<bits/stdc++.h>
using namespace std;
bool isSubset(vector<int> & a, vector<int> & b) {
// Iterate over each element in the second array
int m=a.size(),n=b.size();
for (int i = 0; i < n; i++) {
bool found = false;
// Check if the element exists in the first array
for (int j = 0; j < m; j++) {
if (b[i] == a[j]) {
found = true;
break;
}
}
// If any element is not found, return false
if (!found) return false;
}
// If all elements are found, return true
return true;
}
int main() {
vector<int> a = {11, 1, 13, 21, 3, 7};
vector<int> b = {11, 3, 7, 1};
if (isSubset(a, b)) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
#include <stdio.h>
#include <stdbool.h>
bool isSubset(int a[], int m, int b[], int n) {
// Iterate over each element in the second array
for (int i = 0; i < n; i++) {
bool found = false;
// Check if the element exists in the first array
for (int j = 0; j < m; j++) {
if (b[i] == a[j]) {
found = true;
break;
}
}
// If any element is not found, return false
if (!found) return false;
}
// If all elements are found, return true
return true;
}
int main() {
int a[] = {11, 1, 13, 21, 3, 7};
int b[] = {11, 3, 7, 1};
int m = sizeof(a) / sizeof(a[0]);
int n = sizeof(b) / sizeof(b[0]);
if (isSubset(a, m, b, n)) {
printf("true\n");
} else {
printf("false\n");
}
return 0;
}
class GfG {
static boolean isSubset(int[] a, int[] b) {
// Iterate over each element in the second array
int m = a.length;
int n = b.length;
for (int i = 0; i < n; i++) {
boolean found = false;
// Check if the element exists in the first array
for (int j = 0; j < m; j++) {
if (b[i] == a[j]) {
found = true;
break;
}
}
// If any element is not found, return false
if (!found) return false;
}
// If all elements are found, return true
return true;
}
public static void main(String[] args) {
int[] a = {11, 1, 13, 21, 3, 7};
int[] b = {11, 3, 7, 1};
if (isSubset(a, b)) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
def isSubset(a, b):
m = len(a)
n = len(b)
# Iterate over each element in the second array
for i in range(n):
found = False
# Check if the element exists in the first array
for j in range(m):
if b[i] == a[j]:
found = True
break
# If any element is not found, return false
if not found:
return False
# If all elements are found, return true
return True
if __name__ == "__main__":
a = [11, 1, 13, 21, 3, 7]
b = [11, 3, 7, 1]
if isSubset(a, b):
print("true")
else:
print("false")
using System;
class GfG {
static bool IsSubset(int[] a, int[] b) {
int m = a.Length;
int n = b.Length;
// Iterate over each element in the second array
for (int i = 0; i < n; i++) {
bool found = false;
// Check if the element exists in the first array
for (int j = 0; j < m; j++) {
if (b[i] == a[j]) {
found = true;
break;
}
}
// If any element is not found, return false
if (!found) return false;
}
// If all elements are found, return true
return true;
}
static void Main() {
int[] a = {11, 1, 13, 21, 3, 7};
int[] b = {11, 3, 7, 1};
if (IsSubset(a, b)) {
Console.WriteLine("true");
} else {
Console.WriteLine("false");
}
}
}
function isSubset(a, b) {
const m = a.length;
const n = b.length;
// Iterate over each element in the second array
for (let i = 0; i < n; i++) {
let found = false;
// Check if the element exists in the first array
for (let j = 0; j < m; j++) {
if (b[i] === a[j]) {
found = true;
break;
}
}
// If any element is not found, return false
if (!found) return false;
}
// If all elements are found, return true
return true;
}
//Driver Code
const a = [11, 1, 13, 21, 3, 7];
const b = [11, 3, 7, 1];
if (isSubset(a, b)) {
console.log("true");
} else {
console.log("false");
}
Output
true
Time Complexity: O(m*n)
Auxiliary Space: O(1)
[Better Approach] Using Sorting and Two Pointer
Sort both arrays and use two pointers to traverse them. Move the pointer in b[] if a[]’s element is smaller. If a[]’s element is larger, b’s element isn’t in a[], so return false.
#include <bits/stdc++.h>
using namespace std;
bool isSubset(vector<int>& a, vector<int>& b) {
// Sort both arrays
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int i = 0, j = 0;
// Traverse both arrays using two pointers
while (i < a.size() && j < b.size()) {
if (a[i] < b[j]) {
i++;
}
else if (a[i] == b[j]) {
i++;
j++;
}
else {
// If element in b is not found in a
return false;
}
}
// If we have traversed all elements in b, it is a
// subset
return (j == b.size());
}
int main() {
vector<int> a = { 11, 1, 13, 21, 3, 7 };
vector<int> b = { 11, 3, 7, 1 };
if (isSubset(a, b)) {
cout << "true" << endl;
}
else {
cout << "false" << endl;
}
return 0;
}
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
bool isSubset(int a[], int aSize, int b[], int bSize) {
qsort(a, aSize, sizeof(int), compare);
qsort(b, bSize, sizeof(int), compare);
int i = 0, j = 0;
// Traverse both arrays using two pointers
while (i < aSize && j < bSize) {
if (a[i] < b[j]) {
// Element in a is smaller, move to the next element in a
i++;
} else if (a[i] == b[j]) {
// Element found in both arrays, move to the next element in both arrays
i++;
j++;
} else {
// Element in b not found in a, not a subset
return false;
}
}
// If we have traversed all elements in b, it is a subset
return j == bSize;
}
int main() {
int a[] = {11, 1, 13, 21, 3, 7};
int b[] = {11, 3, 7, 1};
int aSize = sizeof(a) / sizeof(a[0]);
int bSize = sizeof(b) / sizeof(b[0]);
if (isSubset(a, aSize, b, bSize)) {
printf("true\n");
} else {
printf("false\n");
}
return 0;
}
import java.util.Arrays;
class GfG {
static boolean isSubset(int[] a, int[] b) {
Arrays.sort(a);
Arrays.sort(b);
int i = 0;
int j = 0;
// Traverse both arrays using two pointers
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
// Element in a is smaller, move to the next element in a
i++;
} else if (a[i] == b[j]) {
// Element found in both arrays, move to the next element in both arrays
i++;
j++;
} else {
// Element in b not found in a, not a subset
return false;
}
}
// If we have traversed all elements in b, it is a subset
return j == b.length;
}
public static void main(String[] args) {
int[] a = {11, 1, 13, 21, 3, 7};
int[] b = {11, 3, 7, 1};
if (isSubset(a, b)) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
def isSubset(a, b):
# Sort both arrays in ascending order
a.sort()
b.sort()
i = 0
j = 0
# Traverse both arrays using two pointers
while i < len(a) and j < len(b):
if a[i] < b[j]:
# Element in arr1 is smaller, move to the next element in a
i += 1
elif a[i] == b[j]:
# Element found in both arrays, move to the next element in both arrays
i += 1
j += 1
else:
# Element in arr2 not found in a, not a subset
return False
# If we have traversed all elements in b, it is a subset
return j == len(b)
if __name__ == "__main__":
a = [11, 1, 13, 21, 3, 7]
b = [11, 3, 7, 1]
if isSubset(a, b):
print("true")
else:
print("false")
using System;
using System.Collections.Generic;
using System.Linq;
class GfG {
public static bool IsSubset(List<int> a, List<int> b) {
// Sort both arrays in ascending order
a.Sort();
b.Sort();
int i = 0;
int j = 0;
// Traverse both arrays using two pointers
while (i < a.Count && j < b.Count) {
if (a[i] < b[j]) {
// Element in arr1 is smaller, move to the
// next element in arr1
i++;
}
else if (a[i] == b[j]) {
// Element found in both arrays, move to the
// next element in both arrays
i++;
j++;
}
else {
// Element in arr2 not found in arr1, not a
// subset
return false;
}
}
// If we have traversed all elements in arr2, it is
// a subset
return j == b.Count;
}
public static void Main(string[] args) {
List<int> a
= new List<int>() { 11, 1, 13, 21, 3, 7 };
List<int> b = new List<int>() { 11, 3, 7, 1 };
if (IsSubset(a, b)) {
Console.WriteLine("true");
}
else {
Console.WriteLine("false");
}
}
}
function isSubset(a, b) {
a.sort((a, b) => a - b);
b.sort((a, b) => a - b);
let i = 0;
let j = 0;
// Traverse both arrays using two pointers
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
// Element in a is smaller, move to the next element in a
i++;
} else if (a[i] === b[j]) {
// Element found in both arrays, move to the next element in both arrays
i++;
j++;
} else {
// Element in b not found in a, not a subset
return false;
}
}
// If we have traversed all elements in b, it is a subset
return j === b.length;
}
//Driver code
const a = [11, 1, 13, 21, 3, 7];
const b = [11, 3, 7, 1];
if (isSubset(a, b)) {
console.log("true");
} else {
console.log("false");
}
Output
true
Time Complexity: O(m log m + n log n)
Auxiliary Space: O(1)
[Expected Approach] Using Hashing- O(m + n) Time and O(m) Space
We can use a hash set to store elements of a[], this will help us in constant time complexity searching. We first insert all elements of a[] into a hash set. Then, for each element in b[], we check if it exists in the hash set.
#include <bits/stdc++.h>
using namespace std;
bool isSubset( vector<int>& a, vector<int>& b) {
// Create a hash set and insert all elements of a
unordered_set<int> hashSet(a.begin(), a.end());
// Check each element of b in the hash set
for (int num : b) {
if (hashSet.find(num) == hashSet.end()) {
return false;
}
}
// If all elements of b are found in the hash set
return true;
}
int main() {
vector<int> a = {1, 2, 3, 4, 5, 6, 7, 8};
vector<int> b = {1, 2, 3, 1};
if (isSubset(a, b)) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
import java.util.HashSet;
import java.util.Set;
class GfG {
static boolean isSubset(int[] a,int[] b) {
// Create a hash set and insert all elements of a
Set<Integer> hashSet = new HashSet<>();
for (int num : a) {
hashSet.add(num);
}
// Check each element of b in the hash set
for (int num : b) {
if (!hashSet.contains(num)) {
return false;
}
}
// If all elements of b are found in the hash set
return true;
}
public static void main(String[] args){
int[] a = { 11, 1, 13, 21, 3, 7 };
int[] b = { 11, 3, 7, 1 };
if (isSubset(a, b)) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
}
def isSubset(a, b):
# Create a hash set and insert all elements of arr1
hash_set = set(a)
# Check each element of arr2 in the hash set
for num in b:
if num not in hash_set:
return False
# If all elements of arr2 are found in the hash set
return True
if __name__ == "__main__":
a = [11, 1, 13, 21, 3, 7]
b = [11, 3, 7, 1]
if isSubset(a, b):
print("true")
else:
print("false")
using System;
using System.Collections.Generic;
class GfG{
static bool isSubset(List<int> a, List<int> b) {
// Create a hash set and insert all elements of arr1
HashSet<int> hashSet = new HashSet<int>(a);
// Check each element of arr2 in the hash set
foreach (int num in b){
if (!hashSet.Contains(num)){
return false;
}
}
// If all elements of arr2 are found in the hash set
return true;
}
public static void Main(string[] args) {
List<int> a = new List<int>() { 11, 1, 13, 21, 3, 7 };
List<int> b = new List<int>() { 11, 3, 7, 1 };
if (isSubset(a, b)) {
Console.WriteLine("true");
}
else{
Console.WriteLine("false");
}
}
}
function isSubset(a, b) {
// Create a hash set and insert all elements of a
const hashSet = new Set(a);
// Check each element of b in the hash set
for (const num of b) {
if (!hashSet.has(num)) {
return false;
}
}
// If all elements of b are found in the hash set
return true;
}
// Driver code
const a = [11, 1, 13, 21, 3, 7];
const b = [11, 3, 7, 1];
if (isSubset(a, b)) {
console.log("true");
} else {
console.log("false");
}
Output
true
Time Complexity: O(m + n), where m and n are the size of a and b respectively.
Auxiliary Space: O(m)