Bruh loves playing fighting games, and in each round he performs a series of moves, where each move is represented by an integer between 1 and 10^9. A sequence of one or more continuous moves is called a “Combo”. He just played two rounds and now wants your help to find the length of the longest Combo which occurred in both the rounds he played.
For example, if the moves in the first round were [8,7,5,7,9] and the moves in the second round were [6,5,7,9,1], the longest combo which occurred in both rounds would be [5,7,9].
Note: It is possible for a Combo to contain the same move multiple times.
The first line contains 'T', denoting the number of test cases.
For each Test :
The first line contains two space separated integers 'N' and ‘M’, denoting the number of moves in the first and second game respectively.
The second line contains an array 'A' of length 'N', denoting the moves of the first game.
The third line contains an array 'B' of length 'M', denoting the moves of the second game.
Output Format:
For each test, print an integer, denoting the length of the longest Combo which occurred in both rounds.
Note:
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N,M <= 10^3
1 <= A[i] <= 10^9, i ∈ (1,N)
1 <= B[j] <= 10^9, j ∈ (1,M)
Note -
The sum of 'N' and ‘M’ over all test cases does not exceed 2000.
Time Limit: 1 sec
2
4 4
5 7 8 9
9 8 7 5
5 3
1 3 5 5 1
3 5 5
1
3
For case 1:
There are multiple Combos that occur in both rounds, including [5], [7], [8] and [9]. The length of all of these is 1, so the answer would be 1.
For Case 2:
The Combo [3, 5, 5] occurs in both rounds and is also the longest such Combo. Hence, the answer is 3.
2
3 4
1 2 3
4 5 6 7
3 3
4 5 6
5 6 7
0
2
Try computing the longest common Combo starting from all pairs of indices.
Approach: For all ‘i’ ∈ (1, ‘N’) and ‘j’ ∈ (1,’M’), we compute the longest possible Combo starting from ‘i’ and ‘j’. We can use two pointers and keep extending them until there is a mismatch. The maximum of all these lengths computed will be the final answer.
Algorithm:
O (N * M * min(N,M)), where N is the size of A and M is the size of B.
For each of the N*M pairs, we extend the Combo as long as possible. Hence, the overall complexity is O(N * M * min(N, M)).
O(1), as we only use constant space.