Nth smallest element in sorted 2-D array in JavaScript

In JavaScript, finding the Nth smallest element in a sorted 2D array requires an efficient approach. We'll use binary search on the value range rather than indices.

Problem Statement

Given a sorted 2D array (sorted in increasing order both row-wise and column-wise), find the Nth smallest element.

const arr = [
  [ 1,  5,  9],
  [10, 11, 13],
  [12, 13, 15]
];

For example, if we want the 5th smallest element from the above array, the answer would be 11.

Approach: Binary Search on Values

Instead of searching through indices, we perform binary search on the range of possible values. The smallest value is arr[0][0] and the largest is arr[rows-1][cols-1].

Algorithm Steps

1. Set low to the smallest element and high to one more than the largest element

2. For each mid value, count elements ? mid in the matrix

3. If count

Implementation

const arr = [
  [ 1,  5,  9],
  [10, 11, 13],
  [12, 13, 15]
];

const findNthSmallest = (matrix, n) => {
  const rows = matrix.length;
  const cols = matrix[0].length;
  
  let low = matrix[0][0];
  let high = matrix[rows - 1][cols - 1] + 1;
  
  while (low < high) {
    let mid = low + Math.floor((high - low) / 2);
    let count = 0;
    
    // Count elements <= mid
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        if (matrix[i][j] <= mid) {
          count++;
        } else {
          break; // Row is sorted, no need to check further
        }
      }
    }
    
    if (count < n) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  
  return low;
};

// Test cases
console.log("5th smallest element:", findNthSmallest(arr, 5));
console.log("1st smallest element:", findNthSmallest(arr, 1)); 
console.log("9th smallest element:", findNthSmallest(arr, 9));
5th smallest element: 11
1st smallest element: 1
9th smallest element: 15

How It Works

The algorithm uses binary search on the value range. When we calculate mid, we count how many elements are less than or equal to mid. If this count is less than N, we know our target is larger, so we search the upper half. Otherwise, we search the lower half.

The key insight is that we don't need mid to exist in the matrix. By incrementing our search range by 1, we ensure that when the loop terminates, low will be the actual Nth smallest element that exists in the matrix.

Time Complexity

Approach Time Complexity Space Complexity
Flatten + Sort O(m×n log(m×n)) O(m×n)
Binary Search on Values O(m×n×log(max-min)) O(1)

Alternative: Simple Approach

For small matrices, you can flatten and sort:

const findNthSmallestSimple = (matrix, n) => {
  const flattened = matrix.flat().sort((a, b) => a - b);
  return flattened[n - 1];
};

console.log("5th smallest (simple):", findNthSmallestSimple(arr, 5));
5th smallest (simple): 11

Conclusion

The binary search approach efficiently finds the Nth smallest element in O(m×n×log(range)) time without extra space. For larger matrices, this is more efficient than flattening and sorting.

Updated on: 2026-03-15T23:19:00+05:30

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements