Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Kth Smallest Element In A Matrix

Medium Acceptance 70.00% Points 30.00

You are given an n × n matrix matrix where each row and each column is sorted in ascending order. Given an integer k, return the kth smallest element in the matrix. The kth smallest element is the element that would appear at position k when all elements of the matrix are arranged in sorted order.

Examples
Example 1

Example 1

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

Output: 13

Explanation: All elements in sorted order are [1,5,9,10,11,12,13,13,15]. The 8th smallest element is 13.

Example 2

Example 2

Input: matrix = [[-5,-4],[-3,-1]], k = 2

Output: -4

Explanation: All elements in sorted order are [-5,-4,-3,-1]. The 2nd smallest element is -4.

Example 3

Example 3

Input: matrix = [[2,3,6],[4,7,9],[5,8,10]], k = 5

Output: 6

Explanation: All elements in sorted order are [2,3,4,5,6,7,8,9,10]. The 5th smallest element is 6.

Hints
Hint 1
N/A
Constraints
  • 1 = n = 300
  • -10? = matrix[i][j] = 10?
  • 1 = k = n × n
Companies
Amazon
Topics
Binary Search
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions