'Coding has over 700 languages', '67% of programming jobs aren’t in the
technology industry', 'Coding is behind almost everything that is powered
by electricity'

Problem of the day

Last Updated: 8 Jan, 2021

Easy

```
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.
```

```
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.
```

```
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.
```

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

```
1 <= T <= 100
1 <= N, M <= 10^4
0 <= A[i] <= 10^5
0 <= B[i] <= 10^5
Time Limit: 1 sec
```

```
Can we solve this problem using the time complexity of O(max(N, M)).
```

- 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 and check whether the same elements is present in the map or not, if it present then we print it else we continue.
- After the end of this loop we will have all the common elements from both the arrays.

- 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 be the second pointer which points to another array and j = 0.
- Now run the loop while i< N and j < M:
- if(arr[i] == brr[j]) then the elements are same so print arr[i] and do j = j + 1 , i = i + 1.
- Else if (arr[i] > brr[j]) then do j = j + 1 because in arr we have already processed some greater element.
- Else do i = i + 1.

- After the end of this loop, we will have the common elements from both the arrays.