Find Common Elements Between Two Arrays

Find Common Elements Between Two Arrays

You are given two 0-indexed integer arrays nums1 and nums2 of sizes n and m, respectively.

Consider calculating the following values:

  • The number of indices i such that 0 <= i < n and nums1[i] occurs at least once in nums2.

  • The number of indices i such that 0 <= i < m and nums2[i] occurs at least once in nums1.

Return an integer array answer of size 2 containing the two values in the above order.

LeetCode Problem - 2956

class Solution {
    // Function to find intersection values between two arrays
    public int[] findIntersectionValues(int[] nums1, int[] nums2) {
        int[] result = new int[2]; // Array to store intersection counts

        int count = 0; // Initialize count for intersections from nums1 to nums2
        for(int e : nums1){ // Iterate over elements of nums1
            for(int f : nums2){ // Iterate over elements of nums2
                if(e == f){ // If an intersection is found
                    count++; // Increment the intersection count
                    break; // Exit the loop to avoid counting duplicates
                }
            }
        }
        result[0] = count; // Store the intersection count from nums1 to nums2
        count = 0; // Reset count for intersections from nums2 to nums1

        for(int f : nums2){ // Iterate over elements of nums2
            for(int e : nums1){ // Iterate over elements of nums1
                if(f == e){ // If an intersection is found
                    count++; // Increment the intersection count
                    break; // Exit the loop to avoid counting duplicates
                }
            }
        }
        result[1] = count; // Store the intersection count from nums2 to nums1

        return result; // Return the array containing intersection counts
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!