Array Subset of another array Java

PROGRAM TO FIND WHETHER AN ARRAY IS SUBSET OF ANOTHER ARRAY USING MAP



import java.util.*;
  
class MAIN
{
  
    // Function to check if an array is
    // subset of another array
    static int isSubset(int a[], int b[], int m, int n) 
    {
  
        // map to store the values of array a[]
        HashMap<Integer, Integer> mp1 = new
                HashMap<Integer, Integer>();
  
        for (int i = 0; i < m; i++)
            if (mp1.containsKey(a[i])) 
            {
                mp1.put(a[i], mp1.get(a[i]) + 1);
            
            else
            {
                mp1.put(a[i], 1);
            }
  
        // flag value
        int f = 0;
  
        for (int i = 0; i < n; i++) 
        {
            // if b[i] is not present in map
            // then array b[] can not be a
            // subset of array a[]
            if (!mp1.containsKey(b[i])) 
            {
                f = 1;
                break;
            }
  
            // if if b[i] is present in map
            // decrement by one
            else 
            {
                mp1.put(b[i], mp1.get(b[i]) - 1);
  
                if (mp1.get(b[i]) == 0)
                    mp1.remove(b[i]);
            }
        }
  
        return f;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr1[] = { 11, 1, 13, 21, 3, 7 };
        int arr2[] = { 11, 3, 7, 1 };
  
        int m = arr1.length;
        int n = arr2.length;
  
        if (isSubset(arr1, arr2, m, n)!=1)
            System.out.print("arr2[] is subset of arr1[] ");
        else
            System.out.print("arr2[] is not a subset of arr1[]");
    }
}


OUTPUT
arr2[] is subset of arr1[]

Comments

Popular posts from this blog

Solve the Sudoku Python

Solve the Sudoku Java

Find Duplicates Java