Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #295: Find Median from Data Stream

In this guide, we solve Leetcode #295 Find Median from Data Stream in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Design, Two Pointers, Data Stream, Sorting, Heap (Priority Queue)

Intuition

The constraints hint that we can reason about two ends of the data at once, which is perfect for a two-pointer scan.

Moving one pointer at a time keeps the invariant intact and avoids nested loops.

Approach

Place pointers at the left and right ends and move them based on the comparison or target condition.

This yields a clean linear pass after any required sorting.

Steps:

  • Set left and right pointers.
  • Move a pointer based on the condition.
  • Update the best answer while scanning.

Example

Input ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] [[], [1], [2], [], [3], []] Output [null, null, null, 1.5, null, 2.0] Explanation MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0

Python Solution

class MedianFinder: def __init__(self): self.minq = [] self.maxq = [] def addNum(self, num: int) -> None: heappush(self.minq, -heappushpop(self.maxq, -num)) if len(self.minq) - len(self.maxq) > 1: heappush(self.maxq, -heappop(self.minq)) def findMedian(self) -> float: if len(self.minq) == len(self.maxq): return (self.minq[0] - self.maxq[0]) / 2 return self.minq[0] # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()

Complexity

The time complexity is O(log⁡n)O(\log n)O(logn). The space complexity is O(n)O(n)O(n), where nnn is the number of elements.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy