26. Array subset of another array
26. Array subset of another array
Problem link :- click here
package programs;
import java.util.*;
public class Array__26
{
static Boolean arraySubsetOfAnotherArray(int a[], int b[], int n1, int n2)
{
/*we have to check whether 'b' is a subset of 'a'
a is a super set
b can be a subset of a
which means n1 must be greater than b*/
if(n1<n2)
return false;
/*lets push all the elements of 'a' to a hash-set
and we will iterate through 'b' and
if any element of 'b' is not present in 'a'
then 'b' is not a subset of 'a'*/
HashSet<Integer> hash_set = new HashSet<>();
//we don't need to check whether any element is repeated
//as they are giving us set (in set elements don't repeat)
for(int i=0; i<n1; i++)
hash_set.add(a[i]);
//iterating through 'b'
for(int i=0; i<n2; i++)
{
//checking if any element of 'b' is not present in 'a'
if( !hash_set.contains(b[i]) )
return false;
}
return true;
}
public static void main(String[] args)
{
int i, m, n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of the array 1 :");
m = s.nextInt();
int array1[] = new int[m];
System.out.println("Enter the elements of the array 1 :");
for(i=0; i<m; i++)
array1[i] = s.nextInt();
System.out.print("Enter the size of the array 2 :");
n = s.nextInt();
int array2[] = new int[n];
System.out.println("Enter the elements of the array 2 :");
for(i=0; i<n; i++)
array2[i] = s.nextInt();
System.out.println("Array 1 : ");
print_array(array1);
System.out.println("\nArray 2 : ");
print_array(array2);
Boolean ans = arraySubsetOfAnotherArray(array1, array2, m, n);
if(ans)
System.out.println("\n\nYes");
else
System.out.println("\n\nNo");
}
static void print_array(int arr[])
{
for(int i=0; i<arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Time complexity :- O(n)
Space complexity :- O(n)
Comments
Post a Comment