Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)).
Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)).
def kth(a, b, k):
if not a: return b[k - 1]
if not b: return a[k - 1]
if k == 1: return min(a[0], b[0])
i = min(len(a), k // 2); j = min(len(b), k // 2)
if a[i - 1] < b[j - 1]:
return kth(a[i:], b, k - i)
return kth(a, b[j:], k - j)
x, y = [1, 4, 7, 10], [2, 3, 8]
print(kth(x, y, 4), kth(x, y, 6), (kth(x, y, 3) + kth(x, y, 4)) / 2)What is printed?- A. 4 7 3.5
- B. 4 8 3.5
- C. 3 8 3.5
- D. 4 8 4.0
Correct answer: B. 4 8 3.5
Discard k/2 elements from the array whose k/2-th element is smaller – they cannot contain the k-th. Merged: 1, 2, 3, 4, 7, 8, 10 → 4th = 4, 6th = 8, and the average of the 3rd and 4th is (3 + 4)/2 = 3.5. (With 7 elements the true median is just the 4th, 4 – the last expression is the even-length formula.) Each step removes about k/2: O(log k).
More Coding Interview Problems questions
- Problem: Reverse a singly linked list of order IDs. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt def…
- Problem: Return the middle node of a linked list (the second middle when the length is even). python class Node: def init(self, v…
- Problem: Remove the k-th node from the end of a list in one pass. python class Node: def init(self, v, nxt=None): self.v, self.next = v…
- Problem: Merge two sorted linked lists into one sorted list. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt…
- Problem: Detect whether a linked list has a cycle and return the value where the cycle starts (None if acyclic). python class Node: def…
- Problem: Reverse the nodes of a linked list k at a time; a final group with fewer than k nodes stays as is. python class Node: def…