I got this interview question from Pramp. You can find it online through their website: https://www.pramp.com/challenge/15oxrQx6LjtQj9JK9XlA
Find The Duplicates
Given two sorted arrays
arr1andarr2of passport numbers, implement a functionfindDuplicatesthat returns an array of all passport numbers that are both inarr1andarr2. Note that the output array should be sorted in an ascending order.Let
NandMbe the lengths ofarr1andarr2, respectively. Solve for two cases and analyze the time & space complexities of your solutions:M ≈ N- the array lengths are approximately the sameM ≫ N-arr2is much bigger thanarr1.Example:
input:
arr1 = [1, 2, 3, 5, 6, 7], arr2 = [3, 6, 7, 8, 20]output:
[3, 6, 7] # since only these three
def find_duplicates(arr1, arr2):
output = []
for val in arr1:
if b_search(arr2, val):
output.append(val)
return output
def b_search(A, value):
lower_ind = 0
upper_ind = len(A) - 1
while lower_ind <= upper_ind:
middle_ind = lower_ind + (upper_ind - lower_ind) // 2
if A[middle_ind] == value:
return value
elif A[middle_ind] > value:
upper_ind = middle_ind - 1
elif A[middle_ind] < value:
lower_ind = middle_ind + 1
return False
#I also tested it against the test cases, and it passed all of the test cases.
# Input: [1, 2, 3, 5, 6, 7], [3, 6, 7, 8, 20]
print(find_duplicates([1, 2, 3, 5, 6, 7], [3, 6, 7, 8, 20]))
# Output: [3,6,7]
Test Case #1
Input: [11], [11],
Expected: [11],
Actual: [11]
Test Case #2
Input: [1,3,5,9], [2,4,6,10],
Expected: [],
Actual: []
Test Case #3
Input: [1,2,3,5,6,7], [3,6,7,8,20],
Expected: [3,6,7],
Actual: [3, 6, 7]
Test Case #4
Input: [1,2,3,5,6,7], [7,8,9,10,11,12],
Expected: [7],
Actual: [7]
Test Case #5
Input: [10,20,30,40,50,60,70,80], [10,20,30,40,50,60],
Expected: [10,20,30,40,50,60],
Actual: [10, 20, 30, 40, 50, 60]
Test Case #6
Input: [10,20,30,40,50,60,70], [10,20,30,40,50,60,70],
Expected: [10,20,30,40,50,60,70],
Actual: [10, 20, 30, 40, 50, 60, 70]