Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Median of two sorted arrays in O(log(min(m, n))) by binary searching the partition of the shorter array.
Problem: Median of two sorted arrays in O(log(min(m, n))) by binary searching the partition of the shorter array.
def median(a, b):
if len(a) > len(b): a, b = b, a
m, n = len(a), len(b); lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2; j = (m + n + 1) // 2 - i
L1 = a[i-1] if i else float('-inf'); R1 = a[i] if i < m else float('inf')
L2 = b[j-1] if j else float('-inf'); R2 = b[j] if j < n else float('inf')
if L1 <= R2 and L2 <= R1:
if (m + n) % 2: return max(L1, L2)
return (max(L1, L2) + min(R1, R2)) / 2
if L1 > R2: hi = i - 1
else: lo = i + 1
print(median([1, 3, 8, 9, 15], [7, 11, 18, 19, 21, 25]))What is printed?- A. 9
- B. 10.0
- C. 11
- D. 15
Correct answer: C. 11
There are 11 values, so the median is the 6th smallest: 1, 3, 7, 8, 9, 11, … gives 11. The search settles on i = 4, j = 2: the left side {1, 3, 8, 9} ∪ {7, 11} has every value ≤ the right side {15} ∪ {18, …}, and with an odd total the median is max(9, 11) = 11.
More Coding Interview Problems questions
- Problem: Find the k-th positive integer missing from a strictly increasing array, by binary search on 'missing before index i' = a[i] − (i…
- Problem: Find the area of the largest square of 1s in a binary matrix. python def square(m): R, C = len(m), len(m[0]); dp = [[0] (C + 1)…
- Problem: Length of the longest common CONTIGUOUS subarray of two arrays (DP on suffix matches). python def common(a, b): dp = [[0] (len(b)…
- Problem: A knight makes k uniformly random moves (8 directions) on an n × n board; once it leaves the board it stays off. What is the…
- Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack). python def most(strs…
- Problem: Delete characters from two strings so they become equal, minimising the sum of ASCII codes deleted. python def cost(a, b): m, n =…