Skip to content

Commit e8a434d

Browse files
Solution Leetcode and Explaination Every single line
1 parent 1ab148f commit e8a434d

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class MedianFinder {
2+
private PriorityQueue<Integer> small; // Max Heap
3+
private PriorityQueue<Integer> large; // Min Heap
4+
5+
public MedianFinder() {
6+
small = new PriorityQueue<>(Collections.reverseOrder());
7+
large = new PriorityQueue<>();
8+
}
9+
10+
public void addNum(int num) {
11+
small.offer(num);
12+
large.offer(small.poll());
13+
14+
if (small.size() < large.size()) {
15+
small.offer(large.poll());
16+
}
17+
}
18+
19+
public double findMedian() {
20+
if (small.size() == large.size()) {
21+
return (small.peek() + large.peek()) / 2.0;
22+
}
23+
return small.peek();
24+
}
25+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
LeetCode 295 – Find Median from Data Stream
2+
3+
class MedianFinder {
4+
private PriorityQueue<Integer> small; // Max Heap
5+
private PriorityQueue<Integer> large; // Min Heap
6+
7+
public MedianFinder() {
8+
small = new PriorityQueue<>(Collections.reverseOrder());
9+
large = new PriorityQueue<>();
10+
}
11+
12+
public void addNum(int num) {
13+
small.offer(num);
14+
large.offer(small.poll());
15+
16+
if (small.size() < large.size()) {
17+
small.offer(large.poll());
18+
}
19+
}
20+
21+
public double findMedian() {
22+
if (small.size() == large.size()) {
23+
return (small.peek() + large.peek()) / 2.0;
24+
}
25+
return small.peek();
26+
}
27+
}
28+
29+
Explanation
30+
31+
PriorityQueue<Integer> small = MaxHeap (left side)
32+
PriorityQueue<Integer> large = MinHeap (right side)
33+
🔹 small: lower half numbers
34+
🔹 large: upper half numbers
35+
36+
Constructor → dono heaps initialize kiye.
37+
38+
addNum(int num)
39+
🔹 Step 1: num ko small (maxheap) me daala
40+
🔹 Step 2: small se top element large (minheap) me daala (to balance)
41+
🔹 Step 3: Agar large zyada bada ho gaya ho toh wapas small me daal do
42+
43+
→ Is logic se heaps ka balance maintained rahega
44+
45+
findMedian()
46+
🔹 Agar dono heaps ka size equal hai:
47+
return average of top elements
48+
🔹 Agar unequal:
49+
return top of small (kyunki vo zyada size ka hoga)
50+
51+
Example:
52+
addNum(1)
53+
addNum(2)
54+
findMedian() → 1.5
55+
56+
addNum(3)
57+
findMedian() → 2.0
58+
59+
Time and Space Complexity:
60+
Operation Time Space
61+
addNum() O(log n) O(n)
62+
findMedian() O(1) O(n)
63+
64+
Efficient for dynamic data stream scenarios.
65+
66+
🔗 Need more help or Java tricks?
67+
https://www.linkedin.com/in/saurabh884095/

0 commit comments

Comments
 (0)