Skip to content

Commit dd80139

Browse files
committed
Intersection Of Sorted Arrays
1 parent c2c87e1 commit dd80139

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Problem Link: https://www.interviewbit.com/problems/intersection-of-sorted-arrays/
3+
4+
Find the intersection of two sorted arrays.
5+
OR in other words,
6+
Given 2 sorted arrays, find all the elements which occur in both the arrays.
7+
8+
Example :
9+
Input :
10+
A : [1 2 3 3 4 5 6]
11+
B : [3 3 5]
12+
Output : [3 3 5]
13+
14+
Input :
15+
A : [1 2 3 3 4 5 6]
16+
B : [3 5]
17+
Output : [3 5]
18+
19+
NOTE : For the purpose of this problem ( as also conveyed by the sample case ),
20+
assume that elements that appear more than once in both arrays should be included
21+
multiple times in the final output.
22+
"""
23+
class Solution:
24+
# @param A : tuple of integers
25+
# @param B : tuple of integers
26+
# @return a list of integers
27+
def intersect(self, A, B):
28+
res = []
29+
index1 = index2 = 0
30+
while index1 < len(A) and index2 < len(B):
31+
if A[index1] == B[index2]:
32+
res.append(A[index1])
33+
index1 += 1
34+
index2 += 1
35+
elif A[index1] > B[index2]:
36+
index2 += 1
37+
else:
38+
index1 += 1
39+
return res

0 commit comments

Comments
 (0)