Find whether an array is subset of another array in Java

Hi! in this tutorial we are going to develop a Java code that will find if an array is a subset of another array or not. So, let’s start with the code-

import java.util.Scanner;
class subset
 public static void main(String ar[])
   int n,m; 
   Scanner sc=new Scanner(;   
   System.out.println("Enter Main Array size:");
   System.out.println("Enter size of array to check");
   int a[]=new int[n];
   int b[]=new int[m];
   System.out.println("Enter main array elements:");
   for(int i=0;i<n;i++)
   int j=0;
   System.out.println("Enter array to check");
   int x=0; 
   for(int i=0;i<m;i++)
      System.out.println("Given array is not a subset");
    System.out.println("Given array is a subset of the main array");

Java program to find whether an array is a subset of another array

First, we take input as the size of both the arrays. And store the value of the main array size in the variable named and the value of another array in the variable named m. Now, take the input as values of both the arrays and store the values of the main array in the array named as a. And store the values of another array in the array named as b.

We will also be using a variable named x which is going to be used as a signal which indicates whether the given array b is a subset of the array a or not. Initially, it is initialized to 0.

Then, we will be using two for loops. Outer for loop will iterate through the array whereas the inner loop will iterate through the array a. And will check whether the current element is also present in the array a or not. If the inner loop exits after completing the full iteration up to then it means that a particular element of array b is not present in the array a. And we then check if j==n and if true, we set x=1 and will come out of the loop using break printing that the given array b is not a subset of array a.

Also, if the given array is a subset of array then variable will never be equal to 1. Hence, reaching the end, we check whether the variable is changed or not.


Enter Main Array size:
Enter size of array to check
Enter main array elements:
1 2 3 4 5
Enter array to check
1 2 3
Given array is a subset of the main array

Leave a Reply

Your email address will not be published. Required fields are marked *