← PayPal bank

PayPal · Question 73 · Trees

Kth Smallest Element in a Sorted Matrix

TreesJavacode⏱ O(klogn)💾 O(n)
Product-based

Problem

Find the kth smallest element in a sorted matrix (rows and columns sorted).

Approach

Use min-heap or binary search. (Min-Heap): push row heads, advance winners.

Time O(klogn)Space O(n)

How it works

  1. 1Seed the heap with every row head.
  2. 2Pop k times, advancing each winner rightward.

Sample input / output

Input:
matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8
Output:
13

Constraints

n == matrix.length; 1 <= n <= 300; rows and columns sorted.

Solution — read it, then walk it

Time O(klogn)Space O(n)Loops 2Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intkthSmallest(int[][] matrix,int k)DEFINE n = matrix.lengthPriorityQueue<int[]> pq =new PriorityQueue<>((a, b)-> matrix[a[0]][a[1]] …for (int i = 0; i < n;i++)pq.offer(new int[]{i, 0})DEFINE [] curr = new int[2]for (int i = 0; i < k;i++)curr = pq.poll()if (curr[1] < n - 1)pq.offer(new int[]{curr[0],curr[1] + 1})RETURNmatrix[curr[0]][curr[1]]DEFINE static voidmain(String[] args)System.out.println(kthSmallest(newint[][]{{1, 5, 9}, {10, 11,13}, {12, 13, 15}}, 8))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/16

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits