Definition
- Median of Two Sorted Arrays via K-way Merge advances a two-way merge to the middle position only.
- Keep indices into both arrays, repeatedly take the smaller head, and count consumed elements.
- For odd combined length, the median is the single middle value at position
n/2. - For even combined length, the median is the average of positions
n/2 - 1andn/2. - Time is O(M + N) linear; a binary search variant achieves O(log(min(M, N))) but is more complex.
- For money, average with
BigDecimalto avoid precision loss.
The National Bank of India has two sorted lists of customer account balances from two regional branches. To report the typical balance of the combined customer base, they need the median. A clerk walks both lists together, always taking the smaller next balance, counting steps, and stops at the middle. There is no need to write out the whole combined list.
Understanding the Concepts
What is the Median of Two Sorted Arrays problem?
Given two sorted arrays of sizes M and N, find the median of the combined sorted order without fully merging the arrays. The median is the middle value if the combined length is odd, or the average of the two middle values if even.
How does the merge-to-the-middle approach work?
We treat the two arrays as two sorted lists in a K-way merge with K equal to 2. We keep an index into each array, compare the current heads, and advance whichever is smaller. We count how many elements we have consumed and remember the last one or two values needed for the median.
package com.bank.service;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class MedianTwoArraysService {
/**
* Finds the median balance across two sorted regional balance lists.
* Uses BigDecimal for precise monetary averaging.
*/
public static BigDecimal findMedian(long[] regionA, long[] regionB) {
int m = regionA.length, n = regionB.length;
int total = m + n;
int midIdx = total / 2;
boolean isEven = (total % 2 == 0);
int i = 0, j = 0;
long prev = 0, curr = 0;
for (int count = 0; count <= midIdx; count++) {
prev = curr;
if (j >= n || (i < m && regionA[i] <= regionB[j])) {
curr = regionA[i++];
} else {
curr = regionB[j++];
}
}
if (isEven) {
BigDecimal sum = BigDecimal.valueOf(prev)
.add(BigDecimal.valueOf(curr));
return sum.divide(BigDecimal.valueOf(2), 2, RoundingMode.HALF_UP);
} else {
return BigDecimal.valueOf(curr);
}
}
public static void main(String[] args) {
long[] regionA = {10000, 25000, 50000, 75000};
long[] regionB = {15000, 30000, 60000};
System.out.println("Median balance: Rs. " + findMedian(regionA, regionB));
}
}
javac -d out com/bank/service/MedianTwoArraysService.java
java -cp out com.bank.service.MedianTwoArraysService
Median balance: Rs. 30000
How do you handle odd vs even combined length?
For combined length total:
- Odd: the median is the value at consumed position
total / 2(zero-based). You need only the current value. - Even: the median is the average of values at positions
total / 2 - 1andtotal / 2. You need both the previous and current values.
The loop runs midIdx + 1 iterations, keeping track of both prev and curr at each step.
Why use BigDecimal for the average?
In a banking context, balances are monetary values. Averaging two monetary amounts using floating-point arithmetic can lose precision. For example, (10001 + 10002) / 2.0 might produce 10001.5 correctly in this case, but with larger values or more decimal places, floating-point errors accumulate. BigDecimal avoids this entirely.
// WRONG for money: floating-point precision loss
double median = (prev + curr) / 2.0;
// CORRECT for money: BigDecimal precision
BigDecimal median = BigDecimal.valueOf(prev)
.add(BigDecimal.valueOf(curr))
.divide(BigDecimal.valueOf(2), 2, RoundingMode.HALF_UP);
What is the binary search alternative?
The binary search approach partitions both arrays such that all elements on the left partition are less than or equal to all elements on the right partition. Binary search on the shorter array finds the correct partition point in O(log(min(M, N))) time.
| Approach | Time | Space | Complexity |
|---|---|---|---|
| Merge-to-middle | O(M + N) | O(1) | Simple |
| Binary search | O(log(min(M, N))) | O(1) | Complex |
The merge view is the clean pattern-based answer. The binary search is the optimal follow-up.
What are the edge cases?
Several edge cases require attention.
- One array empty: the median is simply the middle of the non-empty array.
- Arrays of length 1: the median is the average of the two elements if both have one element.
- All elements equal: the median equals that common value.
- Disjoint ranges: one array is entirely less than the other; the merge is trivial.
package com.bank.core;
import java.math.BigDecimal;
public class MedianEdgeCases {
public static void main(String[] args) {
// One empty array
System.out.println(MedianTwoArraysService.findMedian(
new long[]{10000, 20000, 30000}, new long[]{})); // 20000
// Both single-element
System.out.println(MedianTwoArraysService.findMedian(
new long[]{10000}, new long[]{20000})); // 15000.00
}
}
20000
15000.00
What is the time and space complexity?
The merge-to-the-middle approach runs in O(M + N) time because we advance through both arrays up to the midpoint. Space is O(1) since we only track indices and the previous/current values. The binary search approach runs in O(log(min(M, N))) time with O(1) space.
What should a senior engineer know?
A senior engineer should understand these deeper aspects.
- The merge view is K-way Merge with K=2: framing it this way connects the problem to the broader pattern family.
- Binary search correctness: the partition must satisfy
maxLeft <= minRightfor both arrays, with sentinel values for boundary cases. - Generalization to K arrays: finding the median of K sorted arrays can use a full K-way merge to the middle or more sophisticated techniques.
- Overflow: when summing two values for the average, use
longorBigDecimalto prevent integer overflow.
What are common interview follow-up questions?
Interviewers often extend this problem.
- Kth smallest element in two sorted arrays: generalize the merge-to-the-middle to stop at position K.
- Median of a stream: use two heaps (max-heap and min-heap) to maintain the median as elements arrive.
- Weighted median: each element has a weight, and the median accounts for weights.
Visual Overview
Region A: [10000, 25000, 50000, 75000] (M=4) Region B: [15000, 30000, 60000] (N=3) Total = 7 (odd) -> median at index 3 ┌──────────────────────────────────────────┐ │ Merge walk: │ │ Step 0: A[0]=10000 <= B[0]=15000 │ │ take 10000, i=1 │ │ Step 1: A[1]=25000 > B[0]=15000 │ │ take 15000, j=1 │ │ Step 2: A[1]=25000 <= B[1]=30000 │ │ take 25000, i=2 │ │ Step 3: A[2]=50000 > B[1]=30000 │ │ take 30000 -> MEDIAN │ └──────────────────────────────────────────┘ Median = 30000 (4th element in combined order)
Key Takeaway
Median of Two Sorted Arrays, framed through the K-way Merge pattern, is a two-way merge that you stop at the middle instead of running to completion. You keep an index into each array, repeatedly take the smaller of the two current heads, and count how many elements you have consumed. Because both arrays are already sorted, walking them together produces the combined order element by element, and you only need to reach the middle position.
For the combined length you decide the median rule up front. If the total is odd, the median is the single value at the middle consumed position. If the total is even, it is the average of the two middle values, so you remember both the previous and current values as you merge. For monetary data, you average using BigDecimal to avoid precision loss.
At the National Bank of India, Rajesh used this to report a typical customer balance across two regional branches whose balance lists were each already sorted. He merged the two lists only as far as the middle and read off the median, averaging with BigDecimal when the combined count was even. The linear pass handled the large customer bases efficiently.
The senior-level insight is understanding that this is K-way Merge with K equal to 2, that you stop at the middle rather than merging everything, and that a binary search variant exists for O(log(min(M,N))) time. Being able to explain both approaches and when each is appropriate demonstrates range.
Remember one sentence: two-way merge to the middle position gives the median in linear time; binary search on the shorter array gives it in logarithmic time.
---