Union and Intersection of Two Arrays
Given two arrays 'A' and 'B' of size 'N' and 'M' respectively, both sorted in non-decreasing order, find the intersection of these two arrays.
The intersection of two arrays consists of all common elements occurring in both arrays.
Input:
The first line of input contains an integer 'T', denoting the number of test cases.
The first line of each test case contains two integers 'N' and 'M', denoting the sizes of the two arrays.
The second line of each test case contains 'N' space-separated integers denoting elements of the first array.
The third line of each test case contains 'M' space-separated integers denoting elements of the second array.
Output:
For each test case, output a single line containing 'K' space-separated integers which correspond to the intersection of arrays A and B.
Example:
Input:
2
4 5
1 2 4 5
2 3 4 5 6
3 3
7 7 8
5 7 8
Output:
2 4 5
7 8
Constraints:
- 1 <= T <= 100
- 1 <= N, M <= 104
- 0 <= A[i], B[i] <= 105
- Time Limit: 1 sec
Note:
You do not need to print anything; implement the given function as the output handling is managed.
Follow-Up:
Can we solve this problem using a time complexity of O(max(N, M))?

AnswerBot
4mo
Yes, we can solve this problem using a time complexity of O(max(N, M)) by using a two-pointer approach.
Use two pointers to iterate through both arrays simultaneously.
Compare the elements at the pointe...read more
Help your peers!
Add answer anonymously...
DE Shaw Mts1 interview questions & answers
A Mts1 was asked Q. What is the Banker's Algorithm?
A Mts1 was asked Q. Inorder Traversal of Binary Tree Without Recursion Given a Binary Tree consistin...read more
A Mts1 was asked Q. What is the difference between malloc() and calloc() in C?
Popular interview questions of Mts1
A Mts1 was asked Q1. What is the Banker's Algorithm?
A Mts1 was asked Q2. Inorder Traversal of Binary Tree Without Recursion Given a Binary Tree consistin...read more
A Mts1 was asked Q3. What is the difference between malloc() and calloc() in C?
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

