Amazon Interview Question for SDE L5 Role
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-09-11Added By Anonymous
Source: Link
Company: Amazon
Role: SDE L5
Interview Stage: Phone Screen
Location: unknown
Year: unknown
Original Post Content:
I was given two sorted arrays and asked to merge them. My initial approach used extra space with a time complexity of O(n + m):
def merge(array1,array2):
res = []
while array1 and array2:
if array1[-1] > array2[-1]:
res.append(array1.pop())
else:
res.append(array2.pop())
if array1:
res.extend(array1)
else:
res.extend(array2)
return res
However, the interviewer asked me to solve the problem without using extra space, which meant rearranging the two arrays in place.
I came up with the following solution, but its worst-case time complexity is O(n * m), where n is the size of array1 and m is the size of array2.
def merge(array1,array2):
i = 0
j = 0
while i < len(array1):
if array1[i] > array2[j]:
array1[i], array2[j] = array2[j], array1[i]
first = array2[j]
k = j + 1
while k < len(array2) and array2[k] < first:
array2[k - 1] = array2[k]
k += 1
array2[k - 1] = first
i += 1
The interviewer kept asking me to solve this with a time complexity of O(n log m) or O(m log n). I'm wondering if this is even possible, and how it could be achieved.