9: Find the intersection of two arrays.
⏳⌚ 00:00:00

Question:-

Given two array of size n and m, Find the intersection of the two array .
Example 1:
Input:
N=4 M =4
arr1[] = {1, 2, 3 , 4}
arr2[] = {3, 4, 9 , 11}
Output: 3, 4
Example 2:
Input:
N=5 M =5
arr1[] = {1, 2, 3 , 4, 9}
arr2[] = {3, 4, 9 , 11, 22}
Output: 3, 4, 9

Steps to solve:-

1. Input:- The code takes two integers, n and m, as input. These integers represent the sizes of two arrays, arr1 and arr2, respectively.
2. Array Initialization:-arr1[n] and arr2[m] are declared to store the elements of the two arrays. A for loop is used to read n integers from the standard input and store them in arr1. Another for loop is used to read m integers from the standard input and store them in arr2.
3. Intersection Detection:-Two nested for loops are used to iterate through all possible pairs of elements from arr1 and arr2.
The outer loop iterates through each element of arr1 from the first element to the last element (0 to n-1). The inner loop iterates through each element of arr2 from the first element to the last element (0 to m-1). For each pair of elements (arr1[i] and arr2[j]), it checks if they are equal: if (arr1[i] == arr2[j]). If the elements are equal, it prints the common element to the standard output using cout << arr1[i] << " " . After printing the common element, the break statement is used to exit the inner loop because we have already found a match for the current element from arr1. This prevents duplicate elements from being printed.
4. Output:- The code prints the common elements (the intersection) of arr1 and arr2 separated by spaces.

solution->

View Code 1
Time Complexity = O(n*m)
Space Complexity = O(n*m)