Day 84 of 100 days dsa coding challenge

Published: (December 26, 2025 at 11:39 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Problem

GeeksforGeeks – Kth smallest element in a Matrix

Difficulty: Medium | Accuracy: 61.42%

Given a matrix mat[][] of size n × n, where each row and column is sorted in non‑decreasing order, find the k‑th smallest element in the matrix.

Solution

class Solution:
    def kthSmallest(self, mat, k):
        n = len(mat)
        low, high = mat[0][0], mat[-1][-1]

        while low < high:
            mid = (low + high) // 2
            count = 0

            # Count elements ≤ mid in each row using binary search
            for row in mat:
                l, r = 0, n
                while l < r:
                    m = (l + r) // 2
                    if row[m] <= mid:
                        l = m + 1
                    else:
                        r = m
                count += l

            if count < k:
                low = mid + 1
            else:
                high = mid

        return low
Back to Blog

Related posts

Read more »

Day 85 of 100 days dsa coding challenge

Challenge Overview Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! 💻🔥 Problem Minimum time to fulfil all orders Geeksfo...

Day 78 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! 💻🔥 The goal: sharpen problem‑solving skills, level up coding, and learn...

Day 76 of 100 days dsa coding challenge

Problem Bus Conductor – GeeksforGeekshttps://www.geeksforgeeks.org/problems/bus-conductor--170647/1 Difficulty: Easy Accuracy: 75.3% Examples Example 1 - Input...