Find Median From Data Stream
Detailed guide and Python implementation for the 'Find Median From Data Stream' problem.
1. Узнать
The 'Find Median From Data Stream' problem is a key challenge in the Heap / Priority Queue section.
This implementation focuses on hard-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Find Median From Data Stream.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Find Median From Data Stream carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Постановка задачи
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.
Implement the MedianFinder class:
- MedianFinder() Initializes the MedianFinder object.
- addNum(num: int) Adds the integer num from the data stream to the data structure.
- findMedian() -> float Returns the median of all elements so far.
Input is a list of operations and arguments. Implement a function medianFinder(operations: list, arguments: list) -> list that returns a list of results (None for constructor/addNum, float for findMedian).
- •-10^5 <= num <= 10^5
- •There will be at least one element in the data structure before calling findMedian
- •At most 5 * 10^4 calls will be made to addNum and findMedian
Примеры
operations = ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"], arguments = [[], [1], [2], [], [3], []]
[None, None, None, 1.5, None, 2.0]
Initialize. Add 1, 2. Median is 1.5. Add 3. Median is 2.0.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Готовы решить?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Интервью: идеи и вариации
Разбивка анализа сложности
Почему время: Directly evaluates all possibilities.
Почему космос: Uses standard local memory.
Почему время: Optimized paths reduce total operations.
Почему космос: May trade memory for speed.
Оптимизированный код Python для решения
Оптимизированный код Python для решения
import heapq
class MedianFinderOpt:
def __init__(self):
self.small, self.large = [], []
def addNum(self, num):
heapq.heappush(self.small, -1 * num)
if self.small and self.large and (-1 * self.small[0]) > self.large[0]:
val = -1 * heapq.heappop(self.small)
heapq.heappush(self.large, val)
if len(self.small) > len(self.large) + 1:
val = -1 * heapq.heappop(self.small)
heapq.heappush(self.large, val)
if len(self.large) > len(self.small) + 1:
val = heapq.heappop(self.large)
heapq.heappush(self.small, -1 * val)
def findMedian(self):
if len(self.small) > len(self.large): return -1 * self.small[0]
if len(self.large) > len(self.small): return self.large[0]
return (-1 * self.small[0] + self.large[0]) / 2Код грубой силы (спойлер защищен)
Код грубой силы (спойлер защищен)
class MedianFinderBrute:
def __init__(self):
self.nums = []
def addNum(self, num):
self.nums.append(num)
def findMedian(self):
self.nums.sort()
n = len(self.nums)
if n % 2: return self.nums[n//2]
return (self.nums[n//2-1] + self.nums[n//2]) / 2Algorithm Pattern Checklist
When dealing with Heap / Priority Queue data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
Key Revision Notes
Standard Heap / Priority Queue problem properties apply.
Связанные вопросы
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
Рекомендуемые ресурсы Python
Расширьте свои знания с помощью соответствующих интерактивных руководств, шпаргалок и сравнений кода.
Циклы Python
Узнайте, как использовать циклы Python для перебора данных. Освойте циклы for, while, прерывание, продолжение и лучшие практики работы с циклами с помощью интерактивных примеров.
Как удалить дубликаты из списка в Python
Узнайте, как удалить дубликаты из списка в Python, сохраняя или игнорируя порядок. Сравните преобразования множеств, ключи dict и методы цикла.
Памятка по коллекциям и структурам данных Python
Полное руководство по модулю коллекций Python и собственным структурам данных. Изучите списки, словари, наборы, кортежи, деки и именованные кортежи.
Python против JavaScript: какой язык программирования лучше?
Всестороннее сравнение Python и JavaScript. Изучите синтаксические различия, производительность, варианты использования (серверная и клиентская части) и примеры кодирования.