Intersection Of Two Arrays

You are given two arrays 'A' and 'B' of size 'N' and 'M' respectively. Both these arrays are sorted in non-decreasing order. You have to find the intersection of these two arrays.

Intersection of two arrays is an array that consists of all the common elements occurring in both arrays.

Note :
1. The length of each array is greater than zero.
2. Both the arrays are sorted in non-decreasing order.
3. The output should be in the order of elements that occur in the original arrays.
4. If there is no intersection present then return an empty array.
Input Format :
The first line of the input contains an integer 'T', denoting the number of test cases.

The first line of each test case contains two integers 'N' 'M', denoting the size of the two arrays.

The second line of each test case contains 'N' space-separated integers denoting the elements of the first array.

The third line of each test case contains 'M' space-separated integers denoting the elements of the second array.
Output Format :
The only line of output of each test case contains 'K' space-separated integers which correspond to the intersection of the two arrays A and B.

The output of each test case will be printed on a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 100
1 <= N, M <= 10^4
0 <= A[i] <= 10^5
0 <= B[i] <= 10^5

Time Limit: 1 sec
Follow Up:
Can we solve this problem using the time complexity of O(max(N, M)).
CodingNinjas
author
2y

Union :
1) Initialize an empty hash set or hash map mp;
2) Iterate through the first array and put every element of the first array in the set mp.
3) Repeat the process for the second array.
4) Print the...read more

CodingNinjas
author
2y
Hashing
  • The simplest approach to solve this problem is to use a map to find common elements.
  • Firstly we can hash all the elements from the first array into a map.
  • Now we iterate through the second array ...read more
CodingNinjas
author
2y
Two Pointer Approach
  • We can use two pointers to solve this problem. The main idea to use two pointers is that the arrays are sorted.
  • Let i be the pointer which points at the first array and i = 0.
  • Let j ...read more
Add answer anonymously...
BigBasket Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter