JavaScript Program to Find median in row wise sorted matrix

We will be describing the process of finding the median in a row-wise sorted matrix using JavaScript. First, we will traverse the matrix to gather all the elements into a single array. Then, we will sort the array to find the middle value, which will be our median. In case of an even number of elements, the median will be the average of the two middle values.

Approach 1: Simple Array Concatenation Method

Given a row-wise sorted matrix, the median can be found by the following approach ?

  • Combine all rows into a single sorted array.

  • Find the middle element(s) of the combined array, which will be the median.

  • If the number of elements in the combined array is odd, return the middle element as the median.

  • If the number of elements in the combined array is even, return the average of the two middle elements as the median.

  • The time complexity for this approach is O(m * n log (m * n)), where m is the number of rows and n is the number of columns in the matrix.

  • The space complexity is O(m * n), as the entire matrix needs to be combined into a single array.

Example: Array Concatenation Method

function findMedianSimple(matrix) {
   // Flatten the matrix into a single array
   let flatArray = [];
   for (let i = 0; i < matrix.length; i++) {
      flatArray = flatArray.concat(matrix[i]);
   }
   
   // Sort the flattened array
   flatArray.sort((a, b) => a - b);
   
   const n = flatArray.length;
   
   // Find median
   if (n % 2 === 1) {
      // Odd number of elements
      return flatArray[Math.floor(n / 2)];
   } else {
      // Even number of elements
      const mid1 = flatArray[n / 2 - 1];
      const mid2 = flatArray[n / 2];
      return (mid1 + mid2) / 2;
   }
}

// Test with example matrix
const matrix1 = [
   [1, 3, 5],
   [2, 6, 9],
   [3, 6, 9]
];

console.log("Matrix:", matrix1);
console.log("Median:", findMedianSimple(matrix1));
Matrix: [ [ 1, 3, 5 ], [ 2, 6, 9 ], [ 3, 6, 9 ] ]
Median: 5

Approach 2: Optimized Binary Search Method

For better space efficiency, we can use binary search to find the median without creating an additional array:

function findMedianOptimized(matrix) {
   const rows = matrix.length;
   const cols = matrix[0].length;
   const totalElements = rows * cols;
   const targetPosition = Math.floor(totalElements / 2);
   
   // Find min and max elements in matrix
   let minVal = matrix[0][0];
   let maxVal = matrix[0][cols - 1];
   
   for (let i = 1; i < rows; i++) {
      minVal = Math.min(minVal, matrix[i][0]);
      maxVal = Math.max(maxVal, matrix[i][cols - 1]);
   }
   
   // Binary search for median
   while (minVal < maxVal) {
      const midVal = Math.floor((minVal + maxVal) / 2);
      let count = 0;
      
      // Count elements less than or equal to midVal
      for (let i = 0; i < rows; i++) {
         count += countLessEqual(matrix[i], midVal);
      }
      
      if (count <= targetPosition) {
         minVal = midVal + 1;
      } else {
         maxVal = midVal;
      }
   }
   
   return minVal;
}

// Helper function to count elements <= target in sorted array
function countLessEqual(arr, target) {
   let left = 0;
   let right = arr.length;
   
   while (left < right) {
      const mid = Math.floor((left + right) / 2);
      if (arr[mid] <= target) {
         left = mid + 1;
      } else {
         right = mid;
      }
   }
   
   return left;
}

// Test with example matrix
const matrix2 = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

console.log("Matrix:", matrix2);
console.log("Median (Optimized):", findMedianOptimized(matrix2));
Matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
Median (Optimized): 5

Comparison of Methods

Method Time Complexity Space Complexity Pros Cons
Array Concatenation O(m*n log(m*n)) O(m*n) Simple to understand Uses extra space
Binary Search O(m*n*log(max-min)) O(1) Space efficient More complex logic

Testing with Different Matrices

// Test with even number of elements
const evenMatrix = [
   [1, 2],
   [3, 4]
];

console.log("Even matrix median:", findMedianSimple(evenMatrix));

// Test with single row
const singleRow = [[1, 3, 5, 7, 9]];
console.log("Single row median:", findMedianSimple(singleRow));
Even matrix median: 2.5
Single row median: 5

Conclusion

Both methods effectively find the median in a row-wise sorted matrix. The simple concatenation method is easier to understand and implement, while the binary search approach offers better space efficiency for large matrices. Choose based on your memory constraints and performance requirements.

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

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements