This is an interview question.
Find the Kth smallest element in a matrix with sorted rows and columns.
Is it correct that the Kth small
O(k log(k))
solution.
Build a minheap.
Add (0,0)
to the heap. While, we haven't found the kth
smallest element, remove the top element (x,y)
from heap and add next two elements [(x+1,y)
and (x,y+1)]
if they haven't been visited before.
We are doing O(k)
operations on a heap of size O(k)
and hence the complexity.