Intersection Of Two Sorted Arrays
Python
Medium
6 views
Problem Description
For each testcase you get two sorted arrays. Output unique common elements in increasing order (space-separated) or EMPTY.
Input Format
First integer t. For each: n m then n ints then m ints.
Output Format
t lines intersections.
Sample Test Case
Input:
1
5 6
1 2 2 3 5
2 2 3 4 5 6
Constraints
Sum of n+m over all testcases
Official Solution
import sys
p=sys.stdin.read().strip().split()
if not p:
sys.exit(0)
it=iter(p)
t=int(next(it))
out=[]
for _ in range(t):
n=int(next(it)); m=int(next(it))
a=[int(next(it)) for _ in range(n)]
b=[int(next(it)) for _ in range(m)]
i=j=0
res=[]
last=None
while i<n and j<m:
if a[i]==b[j]:
if last!=a[i]:
res.append(a[i])
last=a[i]
i+=1
j+=1
elif a[i]<b[j]:
i+=1
else:
j+=1
out.append(' '.join(map(str,res)) if res else 'EMPTY')
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!