Skip to main content

Kth Smallest Element in a Sorted Matrix

Question

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Example 1
Input:

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

Output: 13

Solution

all//Kth Smallest Element in a Sorted Matrix.py


def kthSmallest(matrix, k):

# convert 2d matrix into 1d array
arr = []
for row in matrix:
for ele in row:
arr.append(ele)

# sort the array
arr.sort()

# return kth smallest element
return arr[k-1]

# Driver Code
matrix = [[2, 6, 8],
[3, 7, 10],
[5, 8, 11]]

k = 5
print(kthSmallest(matrix, k))

# Output: 7