Skip to content

Commit e3b909e

Browse files
committed
Daily Coding Problem | Day 1134 | Stream median
1 parent a6b25ac commit e3b909e

3 files changed

Lines changed: 79 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Good morning! Here's your coding interview problem for today.
2+
3+
This problem was asked by Microsoft.
4+
5+
Compute the running median of a sequence of numbers. That is, given a stream of numbers, print out the median of the list so far on each new element.
6+
7+
Recall that the median of an even-numbered list is the average of the two middle numbers.
8+
9+
For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should print out:
10+
11+
```
12+
2
13+
1.5
14+
2
15+
3.5
16+
2
17+
2
18+
2
19+
```
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.devstromo.day1134;
2+
3+
import java.util.Comparator;
4+
import java.util.PriorityQueue;
5+
6+
public class Problem {
7+
// Max-heap for the lower half
8+
private final PriorityQueue<Integer> lower =
9+
new PriorityQueue<>(Comparator.reverseOrder());
10+
// Min-heap for the upper half
11+
private final PriorityQueue<Integer> higher = new PriorityQueue<>();
12+
13+
/** Inserts the next value and returns the median after the insertion. */
14+
public double add(int value) {
15+
// 1. Insert
16+
if (lower.isEmpty() || value <= lower.peek()) {
17+
lower.offer(value);
18+
} else {
19+
higher.offer(value);
20+
}
21+
22+
// 2. Re-balance (at most one element difference)
23+
if (lower.size() > higher.size() + 1) {
24+
higher.offer(lower.poll());
25+
} else if (higher.size() > lower.size() + 1) {
26+
lower.offer(higher.poll());
27+
}
28+
29+
// 3. Median
30+
if (lower.size() == higher.size()) {
31+
// Both heaps non-empty because we maintain balance
32+
return (lower.peek() + higher.peek()) / 2.0;
33+
}
34+
return (lower.size() > higher.size()) ? lower.peek() : higher.peek();
35+
}
36+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.devstromo.day1134;
2+
3+
import org.junit.jupiter.api.DisplayName;
4+
import org.junit.jupiter.api.Test;
5+
6+
import static org.junit.jupiter.api.Assertions.*;
7+
8+
class ProblemUnitTest {
9+
private final Problem problem = new Problem();
10+
11+
@Test
12+
@DisplayName("Test stream median")
13+
void testStreamMedian() {
14+
int[] stream = {2, 1, 5, 7, 2, 0, 5};
15+
double[] expected = {2, 1.5, 2, 3.5, 2, 2, 2};
16+
for (int i = 0; i < stream.length; i++) {
17+
double actual = problem.add(stream[i]);
18+
assertEquals(expected[i], actual, 1e-9,
19+
"Mismatch at index " + i);
20+
}
21+
}
22+
23+
24+
}

0 commit comments

Comments
 (0)