Kth Smallest Element in a Sorted Matrix

Solution Code
class Solution:
    def kthSmallest(self, matrix: list[list[int]], k: int) -> int:
        n = len(matrix)
        low, high = matrix[0][0], matrix[n - 1][n - 1]
        
        def count_less_equal(mid):
            count, c = 0, n - 1
            for r in range(n):
                while c >= 0 and matrix[r][c] > mid:
                    c -= 1
                count += (c + 1)
            return count
        
        ans = low
        while low <= high:
            mid = (low + high) // 2
            if count_less_equal(mid) >= k:
                ans = mid
                high = mid - 1
            else:
                low = mid + 1
        return ans

Time Complexity

O(N log(Max - Min)

Space Complexity

O(1)