/* Given two integer arrays, A and B of size N and M, respectively. Your task is to find all the common elements in both the array.
NOTE: Each element in the result should appear as many times as it appears in both arrays. The result can be in any order.
        Problem Constraints
            1 <= N, M <= 10^5
            1 <= A[i] <= 10^9   */

import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {
    
    public static int[] commonElements(int[] A, int[] B) {
        
        List<Integer> commonElementsList = new ArrayList<>();
        // Iterate over array A
        for (int i = 0; i < A.length; i++) {
            int eleA = A[i];

            // Check if the element exists in array B
            for (int j = 0; j < B.length; j++) {
                int eleB = B[j];

                // If the elements match, add it to the common elements list
                if (eleA == eleB) {
                    commonElementsList.add(eleA);

                    // Remove the element from array B to avoid duplicates
                    B[j] = Integer.MIN_VALUE; // Using a placeholder value
                    break; // Move to the next element in array A
                }
            }
        }
        // Convert the common elements list to an integer array
        int[] result = new int[commonElementsList.size()];
        for (int i = 0; i < commonElementsList.size(); i++) {
            result[i] = commonElementsList.get(i);
        }
        return result;
    }

    public static void main(String[] args) {
        

        int[] A1 = {1, 2, 2, 1};
        int[] B1 = {2, 3, 1, 2};
        int[] result1 = commonElements(A1, B1);
        System.out.println(Arrays.toString(result1)); // Output: [1, 2, 2]

        int[] A2 = {2, 1, 4, 10};
        int[] B2 = {3, 6, 2, 10, 10};
        int[] result2 = commonElements(A2, B2);
        System.out.println(Arrays.toString(result2)); // Output: [2, 10]
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: