Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and counting entries ≤ mid with a staircase walk.
Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and counting entries ≤ mid with a staircase walk.
def kth(m, k):
n = len(m); lo, hi = m[0][0], m[-1][-1]
while lo < hi:
mid = (lo + hi) // 2
cnt, r, c = 0, n - 1, 0
while r >= 0 and c < n:
if m[r][c] <= mid: cnt += r + 1; c += 1
else: r -= 1
if cnt < k: lo = mid + 1
else: hi = mid
return lo
print(kth([[2, 6, 8], [3, 7, 10], [5, 9, 12]], 5))What is printed?- A. 6
- B. 8
- C. 10
- D. 7
Correct answer: D. 7
Sorted values are 2, 3, 5, 6, 7, 8, 9, 10, 12, so the 5th smallest is 7; the search returns the smallest v with count(≤ v) ≥ k, which is always a matrix entry. Counting with < instead of ≤ returns the 6th smallest (8), an off-by-one in k returns the 4th (6), and adding r instead of r + 1 per column undercounts and gives 10.
More Coding Interview Problems questions
- Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass. python class N: def init(s, v, nx=None)…
- Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order. python class N: def…
- Deep-copy a linked list whose nodes also have a random pointer. Which approach uses O(n) time and only O(1) extra space (besides the…
- Problem: Simulate an LRU cache of capacity 3 (get returns −1 on a miss; a get or put marks the key most recently used). python from…
- Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs. python class T: def…
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with…