714133. Median of the Subarrays

Hard

Median of the Subarrays

Summary

Given a 2D array arr[][] of size n x m, find the median of all subarrays of length k. The median is calculated by considering all elements in the subarray and then finding the middle element if the number of elements is odd, or taking the average of two middle elements if the number of elements is even. This problem requires a combination of sorting, mapping, and data structures to solve efficiently.

Detailed Explanation

To solve this problem, we will follow these steps:

  1. Initialize an empty map medianMap to store the median values of subarrays.
  2. Iterate through each row in the 2D array using two nested loops (one for rows and one for columns).
  3. Extract a subarray of length k from the current row, starting from the first element.
  4. Sort the elements in the subarray in ascending order.
  5. Calculate the median of the sorted subarray by finding the middle element if the number of elements is odd or taking the average of two middle elements if the number of elements is even.
  6. Store the calculated median value in the medianMap with the subarray's starting index as the key.
  7. Repeat steps 2-6 for all subarrays.

Time Complexity: O(nmk log k) due to sorting, where n and m are the dimensions of the 2D array and k is the length of the subarray. Space Complexity: O(nmk) for storing the median values in the map.

Here's a step-by-step breakdown of the solution:

          +---------------+
          |  arr[][]    |
          +---------------+
                  |
                  v
+---------------+       +---------------+
|  Iterate rows   |       |  Calculate     |
|  and columns    |       |  median value  |
+---------------+       +---------------+
                  |
                  v
+---------------+       +---------------+
|  Extract        |       |  Sort elements |
|  subarray of    |       |  in ascending  |
|  length k       |       |  order          |
+---------------+       +---------------+
                  |
                  v
+---------------+       +---------------+
|  Calculate     |       |  Median value  |
|  median value   |       |  (middle      |
|  of the sorted |       |  element if    |
|  subarray)     |       |  odd, or average|
|                |       |  of two middle |
|                |       |  elements if    |
|                |       |  even          |
+---------------+       +---------------+
                  |
                  v
+---------------+       +---------------+
|  Store median   |       |  Store the     |
|  value in map   |       |  calculated    |
|  with subarray's|       |  median value   |
|  starting index as key|
+---------------+       +---------------+

Optimized Solutions

Here are optimized solutions for this problem in various programming languages:

Java

View on GeeksforGeeks
import java.util.*;

public class MedianOfSubarrays {
    public static double[] findMedian(int[][] arr, int k) {
        Map<Integer, Double> medianMap = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j <= arr[0].length - k; j++) {
                int[] subarray = Arrays.stream(arr[i].subArray(j, j + k)).mapToInt(Integer::intValue).toArray();
                Arrays.sort(subarray);
                double median;
                if ((k % 2) == 1) {
                    median = (double) subarray[k / 2];
                } else {
                    median = (subarray[(k - 1) / 2] + subarray[k / 2]) / 2.0;
                }
                medianMap.put(i * arr[0].length + j, median);
            }
        }
        double[] result = new double[medianMap.size()];
        int index = 0;
        for (double value : medianMap.values()) {
            result[index++] = value;
        }
        return result;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.