Advertisement

Kth Smallest Element in a Sorted Matrix - LeetCode 378 Solution

Kth Smallest Element in a Sorted Matrix - Complete Solution Guide

Kth Smallest Element in a Sorted Matrix is LeetCode problem 378, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the k th smallest element in the matrix . Note that it is the k th smallest element in the sorted order , not the k th distinct element. You must find a solution with a memory complexity better than O(n 2 ) . Example 1: Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 Output: 13 Explanation: The elements in the matrix are [1,5,9,10,11,12,13, 13 ,15], and the 8 th smallest number is 13 Example 2: I

Detailed Explanation

The problem asks us to find the k-th smallest element in an n x n matrix where each row and column is sorted in ascending order. It is important to note that we are looking for the k-th smallest element in the *sorted order* of all elements in the matrix, not the k-th distinct element. The memory complexity should be better than O(n^2), hinting that we should avoid simply flattening the matrix into a single sorted array. We are given the matrix size 'n' and an integer 'k' as input. The output is the k-th smallest element in the matrix.

Solution Approach

The solution utilizes binary search. The search space is defined by the minimum and maximum values in the matrix (matrix[0][0] and matrix[n-1][n-1] respectively). For each 'mid' value during the binary search, we iterate through the matrix and count the number of elements that are less than or equal to 'mid'. This counting is done efficiently by starting from the top-right corner of each row and moving towards the left until we find an element that is less than or equal to 'mid'. The number of elements to the left of the current position (including the current position) gives the count of elements less than or equal to 'mid' in that row. The sum of these counts for all rows gives the total count of elements less than or equal to 'mid' in the matrix. Based on whether this count is less than or greater than or equal to 'k', the binary search adjusts its lower or upper bounds.

Step-by-Step Algorithm

  1. Step 1: Initialize 'low' to the smallest element in the matrix (matrix[0][0]) and 'high' to the largest element in the matrix (matrix[n-1][n-1]).
  2. Step 2: Perform binary search while 'low' is less than or equal to 'high'.
  3. Step 3: Calculate the 'mid' value as 'low + (high - low) // 2'.
  4. Step 4: Initialize 'count' to 0 and 'j' to 'n - 1'.
  5. Step 5: Iterate through each row 'i' of the matrix.
  6. Step 6: While 'j' is within bounds (>= 0) and matrix[i][j] is greater than 'mid', decrement 'j'.
  7. Step 7: Add 'j + 1' to 'count' (since all elements from matrix[i][0] to matrix[i][j] are less than or equal to 'mid').
  8. Step 8: After iterating through all rows, check if 'count' is less than 'k'.
  9. Step 9: If 'count' is less than 'k', it means that the k-th smallest element is greater than 'mid', so update 'low' to 'mid + 1'.
  10. Step 10: Otherwise, it means that the k-th smallest element is less than or equal to 'mid', so update 'high' to 'mid - 1'.
  11. Step 11: After the binary search finishes (i.e., 'low' > 'high'), 'low' will be the k-th smallest element. Return 'low'.

Key Insights

  • Insight 1: The matrix is sorted both row-wise and column-wise, which enables the use of binary search.
  • Insight 2: Instead of directly searching for the k-th smallest element, we can use binary search to find a potential 'mid' value and count how many elements in the matrix are less than or equal to 'mid'.
  • Insight 3: If the count is less than k, the k-th smallest element must be greater than 'mid', so we adjust the lower bound of the binary search. Otherwise, the k-th smallest element is less than or equal to 'mid', so we adjust the upper bound.

Complexity Analysis

Time Complexity: O(n*log(m))

Space Complexity: O(1)

Topics

This problem involves: Array, Binary Search, Sorting, Heap (Priority Queue), Matrix.

Companies

Asked at: OKX, PhonePe, Salesforce, X.