Skip to main content

JP Morgan

JP Morgan OA 2023 - Intersection and Union of Two Arrays


You are given two arrays arr1 and arr2 of size N and M respectively. Your task is to perform the following operations:

  1. Find the intersection of the two arrays, which includes all elements that are common to both arrays.
  2. Find the union of the two arrays, which includes all unique elements from both arrays, with duplicates removed.

Note:

  • The input arrays can contain duplicate elements.
  • The intersection and union arrays should be sorted in ascending order.
  • If no elements are found in either the intersection or union, print -1 for that array.
  • No duplicate elements should be present in the output arrays.

Input Format:

The input consists of three lines:

  1. The first line contains two space-separated integers N and M representing the lengths of each array.
  2. The second line consists of N space-separated integers denoting the elements of array arr1.
  3. The third line consists of M space-separated integers denoting the elements of array arr2.

Output Format:

The output consists of two lines:

  1. The first line consists of space-separated elements of the intersection array.
  2. The second line consists of space-separated elements of the union array.

Constraints:

  • (1 <= N <= 10^4)
  • (1 <= M <= 10^4)
  • (-10^9 <= arr1[i], arr2[i] <= 10^9)

Example:

Input:

5 4
1 2 2 3 4
2 2 3 5

Output:

2 3
1 2 3 4 5

Explanation:

  • Intersection: The common elements between arr1 and arr2 are 2 and 3.
  • Union: The unique elements from both arrays are 1, 2, 3, 4, 5. All duplicates have been removed, and the result is sorted in ascending order.