Lesson overview · Free interview practice

Two Heaps

Maintain two heaps to solve interval and median problems.

Topics in the full lesson
  • Concept and Use Cases
  • When to Use
  • Time and Space Complexity
  • Finding the Median of a Data Stream
  • Maintaining a Dynamic Set of Data

Try the free interview questions

Work through a question before revealing its explanation. These questions and answers are free; Premium adds the full lesson walkthrough, examples and implementation detail.

Question

Given an array of intervals where intervals[i] = [start_i, end_i] and every start_i is unique, the right interval of interval i is the interval j (possibly equal to i) whose start_j is the smallest value satisfying start_j >= end_i. Return an array of right-interval indices for each i, using -1 if no right interval exists.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Question

The goal is to find the median of all elements in an array that are within a certain sliding window, given a set of integers and a target window size.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Question

Design a data structure that supports adding integers from a data stream and reporting the median of all values added so far. Implement addNum(num) to ingest a number and findMedian() to return the median of every number seen up to that point.

Take a moment to think about this before revealing the answer

Explain your reasoning or try an implementation before comparing answers.

Explore the full Two Heaps material

Premium includes the complete lessons and implementation references. Free practice questions remain available without a subscription.

All course tracks & premium content
From basics to advanced masterclasses
Built for JS/TS developers like you
Real-world tips & common pitfalls
Upgrade to Premium

Continue in this section