-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnion of 2 Sorted Arrays.py
70 lines (62 loc) · 1.69 KB
/
Union of 2 Sorted Arrays.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#User function Template for python3
class Solution:
#Function to return a list containing the union of the two arrays.
def findUnion(self,arr1,arr2,n,m):
'''
:param a: given sorted array a
:param n: size of sorted array a
:param b: given sorted array b
:param m: size of sorted array b
:return: The union of both arrays as a list
'''
# code here
i = 0
j = 0
c = {}
while i < n and j < m:
if a[i] in c:
i += 1
continue
if b[j] in c:
j += 1
continue
if a[i] < b[j]:
c[a[i]] = 1
i += 1
elif a[i] > b[j]:
c[b[j]] = 1
j += 1
else:
c[a[i]] = 1
i += 1
j += 1
while i < n:
if a[i] in c:
i += 1
continue
c[a[i]] = 1
i += 1
while j < m:
if b[j] in c:
j+= 1
continue
c[b[j]] = 1
j += 1
return list(c.keys())
#{
# Driver Code Starts
#Initial Template for Python 3
# Contributed by : Nagendra Jha
# Modified by : Sagar Gupta
if __name__ == '__main__':
test_cases = int(input())
for cases in range(test_cases) :
n,m = map(int,input().strip().split())
a = list(map(int,input().strip().split()))
b = list(map(int,input().strip().split()))
ob=Solution()
li = ob.findUnion(a,b,n,m)
for val in li:
print(val, end = ' ')
print()
# } Driver Code Ends