Problem title
Difficulty
Avg time to solve

Longest Consecutive Sequence In A Binary Tree
Moderate
15 mins
Maximum Difference Between Node And Ancestor
Easy
10 mins
Count Distinct Elements In Every Window
Moderate
15 mins
Convert A Binary Tree To A Circular Doubly Linked List
Hard
10 mins
Elements In Two BSTs
Easy
15 mins
Print Matrix Elements In Sorted Order
Easy
15 mins
String Conversion
Moderate
15 mins
Spiral Matrix
Easy
--
Prerequisite Task
Moderate
35 mins
Gray Code
Moderate
25 mins
2

Common Elements

Difficulty: MEDIUM
Contributed By
Avg. time to solve
35 min
Success Rate
70%

Problem Statement

Given two 1-dimensional arrays containing strings of lowercase alphabets, print the elements that are common in both the arrays i.e. the strings that are present in both the arrays.

Note:
An element of one array can be mapped only to one element of the array. For example :

Array 1 = {“ab”, “dc”, “ab”, “ab”}
Array 2 = {“dc”, “ab”, “ab”} 

The common elements for the above example will be “dc”, “ab”, and “ab”. 
Input Format:
The first line of input contains an integer 'T' representing the number of test cases. Then the test cases follow.

The first line of each test case includes two integers, 'N' and 'M', representing the sizes of both the arrays.

The second line of each test case contains 'N' single-spaced strings representing the elements of the first array.

The third line of each test case contains 'M' single-spaced strings representing the elements of the second array.
Output Format:
For each test case, the common elements of both arrays are printed in the order in which they appear in the second array. The elements are printed in a single space-separated manner. 

The output for each test case will be printed in a separate line.

Note:

You do not need to print anything, it has already been taken care of. Just return the common elements in the specified order.
Constraints:
1 <= T <= 10
1 <= N, M <= 10000    
1 <= S <= 10

Where 'T' is the number of test cases. 'N' and 'M' are the sizes of both the arrays and 'S' is the length of the strings of the arrays. Also, the strings contain only lowercase alphabets.

Time limit: 1 sec.
Sample Input 1:
1
3 5
at bat rat
rat bar bat rat to
Sample Output 1:
rat bat
Explanation of the Sample Input 1:
The common elements of both the arrays are “bat” and “rat”. Thus, these two elements are printed in the order in which they appear in the second array.
Sample Input 2:
2
2 2
a b
c d
2 1
coding ninjas
coding
Sample Output 2:
coding
Explanation of Sample Input 2
There are no common elements for the first test case. For the second case, “coding” is the common element.
Reset Code
Full screen
copy-code
Console