Coding Interview Patterns Module 13
Heaps and top-K interview questions
Interview questions on heaps and top-K: short warm-ups, then what each harder question tests, the first step of a good answer and its follow-ups.
Warm-up questions
Short questions with short answers, each answered in full.
-
Fresher to mid
Python's heappush raised TypeError: '<' not supported between instances of 'dict' and 'dict'. What happened, and what is the usual fix?
-
Fresher to mid
Why does heapify take O(n) time when n pushes take O(n log n) in the worst case?
-
Fresher to mid
Why does merging k sorted lists with a heap cost O(N log k) and not O(N log N), and when does the difference matter?
The heap never holds more than k entries, one front per list, so each push or pop walks at most about log2 k levels, not log2 N. Each of the N values is pushed once and popped once, which gives O(N log k). Sorting the concatenation is O(N log N), and it needs every value in memory before it returns the first. The gap matters when k is much smaller than N, and above all when the lists are files or streams: merging 1,000 lists of a million values walks about 10 levels per value instead of 20, and holds 1,000 values at a time instead of a million.
From the lesson Merging k sorted lists with a heap
-
Fresher to mid
To keep the 100 largest values of a long stream, why do you keep a min-heap of 100 values and not a max-heap?
-
Fresher to mid
Why does the grid of sums a[i] + b[j] of two sorted lists rise along every row and down every column, and what does that tell you about where the next smallest sum can be?
Along row i the first term a[i] stays fixed while b[j] grows with j, because b is sorted, so the sums rise from left to right. Down column j, b[j] stays fixed while a[i] grows, so the sums rise from top to bottom. The smallest sum of all is therefore in the corner, a[0] + b[0]. More generally, a pair costs at least as much as the pair to its left and the pair above it, so it can be the next smallest only once those two have been taken. The candidates for the next smallest sum always form a thin edge around the pairs already taken, which is why a heap that holds only that edge is enough, instead of all n times m sums.
From the lesson Frontier heaps for k-th smallest pairs
-
Fresher to mid
In the k most frequent words problem with ties broken alphabetically, why does the order need two keys, and which comes first?
Counts alone do not decide the order, because two words can occur equally often, and the problem says which of them ranks higher: the one that comes first alphabetically. So the order compares counts first, the higher count ranking higher, and compares the words only when the counts are equal. With the count as the only key, the order of equal counts is left to the method: a heap returns them in no promised order, and a stable sort returns them in the order they reached it, which depends on the log. The answer would then change when the same searches arrive in another order. The second key has to be part of every comparison the method makes, not a sort applied at the end, because the method may already have dropped the word that should have won the tie.
From the lesson Top k frequent words: heap or buckets
-
Fresher to mid
Why does a running median use two heaps rather than one, and why is one a max-heap and the other a min-heap?
A heap gives fast access to one value only, its top: the smallest of a min-heap or the largest of a max-heap. The median is neither; it sits in the middle, where the sorted values split into halves. So split them: the lower half in a max-heap, whose top is its largest value, and the upper half in a min-heap, whose top is its smallest. Those two tops are exactly the values next to the split, so the median is the lower top when the count is odd and the mean of both tops when it is even. A new value joins one half and at most one top moves across to keep the halves even, so each value costs O(log n). One heap would need n/2 pops to reach the middle every time.
From the lesson Running median with two heaps
-
Fresher to mid
Why do k-closest-points solutions compare x² + y² instead of the distance itself, and what do they still have to watch for?
The square root keeps order: for distances that are not negative, one is smaller than another exactly when its square is, so x² + y² ranks the points as their distances do. Skipping the root saves work, and with whole-number coordinates the squared distance is a whole number, compared exactly, while a square root is rounded and can make two different distances look equal. What remains to watch is size. Squares grow fast: with coordinates up to 10⁹, x² + y² reaches 2 × 10¹⁸, so it needs a 64-bit integer type, and in languages with fixed-size integers the coordinates must be widened before they are multiplied, not after.
From the lesson K closest points to origin and closest values
-
Fresher to mid
In the fewest-rooms problem, why does the heap hold end times, and why only the smallest one is checked when a meeting starts?
A room becomes usable again when its current meeting ends, so the only fact that matters about a busy room is its end time. When a new meeting starts, the question is whether any room is free by then, and the room that frees first answers it: if even the earliest end time is later than the start, every room is busy. So a min-heap of end times keeps exactly the needed fact on top. If the earliest end is at most the start, for half-open meetings, that room is reused and its end time is replaced; otherwise a room opens. Meetings must be visited in start order for this to work, and each one costs O(log n).
From the lesson Scheduling with heaps
-
Fresher to mid
Why does lazy deletion leave old entries in a heap instead of removing them when a value changes?
Because a heap can find only its top. An old entry may sit anywhere in the array, so removing it means searching the whole heap, O(n), and then repairing the heap around the hole. Lazy deletion avoids the search: the update pushes a new entry and records which entry is current, and the old one stays where it is. It can only change an answer when it reaches the top, and at that moment it is easy to recognise and pop. Every entry is pushed once and popped at most once, so the work stays O(log n) per operation, amortised, even when one query happens to pop several out-of-date entries in a row.
From the lesson Heaps with lazy deletion
Questions with model answers
What each question tests, the first step of a good answer and the follow-ups to expect.
-
Fresher to mid
An event scheduler runs events in time order and, for equal times, in the order they were scheduled. The Python version pushes (time, event id) tuples and passes its tests, but the Java and Go ports sometimes run two events with the same time out of order. Explain why, and give one fix for all five languages.
- What it tests
- Knowing that heaps do not keep equal entries in arrival order, why the Python tuples hide the problem, and adding a sequence number to the key, with its cost and its overflow limit.
- First step
- Ask what each heap compares. A heap only keeps every parent at most its children; it never records which of two equal entries arrived first, and Java's documentation says ties are broken arbitrarily. The Python tuples pass because their second element, the event id, grows in scheduling order, so equal times fall back to it. The ports compare times only. Make every version compare (time, sequence number), with the number handed out when the event is scheduled.
- Follow-ups
-
- Why does the Python version pass, and when would it fail too?
- The sequence number is a Java int and the service runs for months. When does it break?
- Can you get the same order without an extra number?
- How would you test for this bug before it reaches production?
From the lesson Heaps in five languages
Model answer, Pro. Model answers open with any pass; prices are in the notice on this page.Opening the model answers with your pass…
Model answers open with any MySmartCoPilot pass.
- Pro pass · 1 week₹79$2.99
- 30 days₹179$5.99
- 1 year₹1,699$45
One payment; nothing renews unless you choose to. The price shown is the total you pay: no fees or charges are added at checkout.
Passes can’t be bought right now, so the model answers can’t be opened at the moment. If you have a pass, enter your licence key.
It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).
In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 5 minutes
-
Mid to senior
A service rebuilds its job queue at startup by pushing 10 million (deadline, job) records from a file into a min-heap, one at a time. Startup is far slower when the file is sorted by deadline, latest first. Explain why, estimate the comparisons, and say how you would build the queue in Python, Java and Go.
- What it tests
- Building a heap in one step against repeated pushes, how the input order changes what pushes cost, and each language's bulk build, including Java's lack of a constructor that takes a collection and a comparator.
- First step
- Count what one push does: the new entry climbs past larger parents. With deadlines arriving latest first, every new entry is the earliest so far and climbs to the root, about log2 n levels, which is 23 for 10 million entries. That is over 200 million comparisons in all. Building the heap from the full list in one step costs under two comparisons per entry, about 20 million.
- Follow-ups
-
- The records arrive over the network for 30 minutes. Does a one-step build still help?
- In Java the queue needs a comparator on the deadline. How do you build it in one step?
- Would sorting the records be faster than heapify?
- After startup, a million more jobs arrive at once. Push them, or rebuild?
From the lesson Heaps in five languages
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to staff
A batch job must merge 2,000 sorted log files of about 5 GB each into one sorted file, on a machine with 16 GB of RAM. Describe the merge, how much memory it needs, and what limits its speed.
- What it tests
- Turning the k-way merge into an external merge: read buffers per file, limits on open files, passes over the data, and whether disks or comparisons set the time.
- First step
- Notice that the heap needs only one record per file, 2,000 entries, so memory goes on read buffers, not on the heap. Size them: about 15 GB left for buffers over 2,000 files is roughly 7 MB each. Then size the job: 10 TB is read once and written once, so estimate both the disk time and the comparison time before choosing what to tune.
- Follow-ups
-
- The process may open only 1,024 files at once.
- Records with equal time stamps must keep the order of their files.
- Downstream jobs want the output while the merge is still running.
- One file turns out to be out of order in the middle.
From the lesson Merging k sorted lists with a heap
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to senior
For the smallest range that contains a value from each of k sorted lists, a scan holds one value per list and moves one list forward at each step. Which list must move, why does that never skip the answer, and what changes when values repeat?
- What it tests
- Proving a pointer rule instead of trusting it, justifying the stopping rule, and keeping ties deterministic when values repeat.
- First step
- Fix one shortest range and think about the values each list can contribute to it. Then ask what the heap holds at the moment the scan's smallest value first enters that range.
- Follow-ups
-
- Why may the scan stop as soon as the list on top has no next value?
- Two ranges are equally short. Which does your code return, and why?
- The lists are live streams instead of arrays.
From the lesson Merging k sorted lists with a heap
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Fresher to senior
You must merge k sorted linked lists with N nodes in all. Compare merging them in pairs, round after round, with a heap of the k heads. Which would you write in an interview, and which in a service?
- What it tests
- Analysing two O(N log k) methods by comparisons, writes, memory and access pattern, and choosing by context rather than by habit.
- First step
- Count the work per node. The heap moves each node once and pays about log2 k comparisons for it; merging in pairs relinks each node once per round, for log2 k rounds, with about one comparison each time. Then ask what each needs at hand: the heap only the k heads, the rounds every list from the start.
- Follow-ups
-
- What changes when k = 2?
- The lists arrive one at a time over an hour.
- Extra memory must be O(1).
From the lesson Merging k sorted lists with a heap
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A service logs about 2 billion response times a day. A daily report needs the 1,000 slowest requests with their request ids, computed on one machine with 512 MB of memory. Design the computation, estimate its cost, and say what changes if the report must be refreshed every minute.
- What it tests
- Choosing a bounded heap for a stream, carrying ids with a tie rule, estimating time and memory with numbers, and adapting the design to a report that is refreshed often.
- First step
- Check what fits. Two billion 8-byte times are 16 GB, so nothing that holds the day fits in 512 MB. A min-heap of 1,000 (time, id) entries does, at well under a megabyte, and it reads the log once: an entry gets in only if it is slower than the root. Then estimate how often the heap actually changes as the day goes on.
- Follow-ups
-
- Two requests have the same time. Which one stays, and how do you make that deterministic?
- The report must cover a rolling 24 hours and refresh every minute. Does one heap still work?
- Eight machines each see part of the traffic. How do you combine their answers?
- The times get slower all afternoon instead of arriving in random order. What happens to the cost?
From the lesson Top-k with a size-k heap
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Fresher to mid
You hold 10 million integers in an array and need the 10 largest, in order. A colleague says the size-k heap is O(n log k), so it always beats sorting. When is that false, and what would you write in Python and in C++?
- What it tests
- Telling worst-case bounds from typical costs, knowing that some sorts exploit order already in the data, and knowing the library calls of two languages.
- First step
- Write the bounds for n = 10⁷ and k = 10: a sort makes about n log₂ n ≈ 2.3 × 10⁸ comparisons on random data, and the heap at most about n log₂ k ≈ 3.3 × 10⁷. Then ask how many values actually get into the heap, which depends on the order the data is in, and how the sort behaves on the same orders.
- Follow-ups
-
- The array is already sorted in ascending order. What do the heap and Python's sort cost?
- k grows to 5 million. Which method wins now?
- Which call would you use in each language, and what does it promise about its cost?
From the lesson Top-k with a size-k heap
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A teammate's top-k function calls heapq.heapreplace on every item once the heap holds k items, without comparing first. It passes the team's three tests. What is wrong, what is the smallest input that shows it, and how would you change the tests so it cannot happen again?
- What it tests
- Reading a library call's contract precisely, finding a smallest counterexample, and designing tests that catch a missing gate instead of trusting hand-picked cases.
- First step
- Read the contract of heapreplace in the heapq documentation, word by word: what does it do when the new item is smaller than the root? Then trace the loop on a short list whose last item is smaller than everything kept before it, and compare the result with sorting.
- Follow-ups
-
- Which one-line change fixes it, and which other call compares for you?
- Why did the three tests pass?
- How would you test it so that a slip like this fails in seconds?
From the lesson Top-k with a size-k heap
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A k-smallest-pairs solution starts at (0, 0) and pushes both neighbours, (i + 1, j) and (i, j + 1), of every pair it pops. On some inputs it returns the same pair twice. Explain why, and give two fixes with their costs.
- What it tests
- Finding why a grid search repeats a pair, fixing it at its cause rather than filtering the output, and the memory each fix costs.
- First step
- Draw the 2 by 2 grid of sums and trace the pushes by hand. Which popped pairs push (1, 1), and how many copies of it can the heap then hold?
- Follow-ups
-
- Should a pair be marked as seen when it is pushed or when it is popped?
- Prove that your one-parent rule never misses a pair.
- Which fix uses less memory on random prices, and by how much?
From the lesson Frontier heaps for k-th smallest pairs
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Two sorted lists hold 100,000 values each, from 1 to 10⁹. You need the k-th smallest pair sum for k up to 10¹⁰, and nothing else. Which method do you choose, what does it cost, and how do you know the value it returns is a real pair sum?
- What it tests
- Choosing a method by the size of k, answering a counting question instead of listing pairs, and showing that the value returned is an actual pair sum.
- First step
- Notice that any method that lists pairs one by one does up to 10¹⁰ steps. Look for a question about a single guess x that is cheap to answer for two sorted lists, and ask how its answer changes as x grows.
- Follow-ups
-
- The values may be negative.
- Return the k-th pair itself, not only its sum.
- The lists are rows of a matrix sorted along rows and columns.
From the lesson Frontier heaps for k-th smallest pairs
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
You need the 100 most frequent words of 10⁸ searches with about 10⁶ distinct words, ties broken alphabetically. Compare counting and sorting, a size-k heap and buckets by count. Which do you choose, and what would change your mind?
- What it tests
- Separating the counting cost from the picking cost, pricing each picking method with numbers, and seeing how ties and skewed counts change the buckets' cost.
- First step
- Separate the two steps, counting and picking, and price each for these sizes before choosing: how many hash-map updates the counting makes, and how many comparisons each way of picking makes over d = 10⁶ pairs. Then ask how the counts are spread, because the cost of one of the three depends on it.
- Follow-ups
-
- Every word occurs exactly once.
- One word occurs 10⁷ times and the rest a few times each.
- The counts barely fit in memory. What else can you save?
From the lesson Top k frequent words: heap or buckets
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Mid to senior
A search box shows the 10 most searched words of the last hour, refreshed every second, at about 2,000 searches a second. Design the data structures, and give the cost of handling one search and of one refresh.
- What it tests
- Counting over a sliding window with expiry, keeping a top-k current while counts rise and fall, and estimating the cost and memory of each operation.
- First step
- Start from the two events: a search arrives, and a search turns an hour old. Decide what each must change, then size the window: at 2,000 searches a second, an hour holds 7.2 million of them. Only then decide what a refresh has to read, and how often.
- Follow-ups
-
- The window holds 500,000 distinct words, so every refresh scans half a million counts. Can you avoid that?
- Two words tie for 10th place. Which one do you show?
- Keeping 7.2 million queue entries is too much memory. What do you keep instead?
From the lesson Top k frequent words: heap or buckets
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A solution returns [w for w, _ in Counter(words).most_common(k)] and fails a hidden test of the alphabetical tie rule. Explain the failure, give the smallest input that shows it, and fix it with as few changes as possible.
- What it tests
- Reading a library's promise about ties, building a smallest counterexample, and fixing the selection without giving up its cost.
- First step
- Read what the collections documentation promises about the order of equal counts in most_common. Then build the shortest log in which that order and the alphabetical order disagree, and keep the counting while changing only how the k words are picked.
- Follow-ups
-
- Write the fix with heapq.nsmallest.
- Would counting sorted(words) instead of words fix it, and at what cost?
- Which test would have caught it before the hidden one did?
From the lesson Top k frequent words: heap or buckets
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A Java running-median passes every test with small positive values, but prints -3 for the stream [-3, -4] and a large negative number when two middle values are both 2,000,000,000. Find both bugs, fix them, and say what tests would have caught them.
- What it tests
- Reading arithmetic in a fixed-width language closely, choosing result types, and testing with negative and extreme values.
- First step
- Look at the even case, where the two tops are combined. Evaluate that one line by hand, in 32-bit Java arithmetic, for -3 and -4, then for two values of 2,000,000,000.
- Follow-ups
-
- Why does the same code give the right answer for [3, 5] but not for [3, 4]?
- The values are 64-bit nanosecond time stamps. What changes?
- How would you print the median exactly, without floating point at all?
From the lesson Running median with two heaps
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Senior to staff
A service handles about 2 billion requests a day and wants the median response time of the day so far, updated every minute, in a few megabytes of memory. Two heaps would hold every time. What do you build, and what do you give up?
- What it tests
- Memory bounds for exact and approximate medians, using what is known about the values, and combining results from several servers.
- First step
- Ask what the values can be and how many different values are possible. Then ask whether the median needs the values themselves, or only how many requests had each value.
- Follow-ups
-
- The times are in microseconds with no upper limit.
- Several servers each keep their own summary. How do you combine them?
- How do you report the median of the last hour rather than of the day?
From the lesson Running median with two heaps
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
After every request, a dashboard must show the 99th percentile of all response times so far, by nearest rank. Adapt the two-heap median. What sizes do the heaps have, and what does each request cost?
- What it tests
- Generalising a known structure to a new target, keeping it correct as n grows, and the cost of each request.
- First step
- Write the value the dashboard needs after n requests as a rank, the r-th smallest, and compare r with the median's rank. Then ask what each of the two heaps would have to hold.
- Follow-ups
-
- How many values can cross per request?
- The upper heap holds only 1 % of the values. Can you store less?
- The percentile must cover only the last 10 minutes.
From the lesson Running median with two heaps
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A map app answers "the 10 ATMs nearest to me" for 50,000 users a minute, over 200,000 ATMs that rarely change. A size-k heap per query reads every ATM. What would you build instead, and what would a query cost?
- What it tests
- Recognising when preprocessing beats a per-query scan, designing a simple spatial index, and stating when a search may stop while still being exact.
- First step
- Count the cost of the current design first: a heap per query reads every ATM, so 50,000 queries a minute over 200,000 ATMs is 10¹⁰ squared distances a minute. The ATMs rarely change, so look for work you can do once, ahead of the queries, that lets a query read only the ATMs near the user.
- Follow-ups
-
- ATMs are dense in cities and sparse in villages. How do you choose the cell size?
- How does a query know that no farther cell can still hold one of the 10 nearest?
- An ATM goes out of service. What has to change?
From the lesson K closest points to origin and closest values
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to senior
For the k values closest to x in a sorted array, a candidate's binary search tests abs(x − a[mid]) > abs(a[mid + k] − x). Find an input where it fails, explain why, and prove that the signed test x − a[mid] > a[mid + k] − x is correct.
- What it tests
- Finding a smallest counterexample for a comparison, explaining what absolute values hide, and proving a binary search with a monotone test and a tie rule.
- First step
- Look for inputs where both values the test compares lie on the same side of x, so that their absolute distances hide which one is closer; repeated values make such inputs easy to build. Then prove the signed test: show that it is true for every window start before the answer and false from the answer on.
- Follow-ups
-
- Why is the signed test monotone in mid?
- What changes if ties must go to the larger value?
- How would you test the function before the interview ends?
From the lesson K closest points to origin and closest values
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
In a Java code review you see long d = x * x + y * y; with int coordinates up to 10⁹, and if (x - a[mid] > a[mid + k] - x) with int values up to 2 × 10⁹. Both pass the unit tests. What is wrong, which inputs show it, and how do you fix and test it?
- What it tests
- Knowing that Java computes an int expression before widening it, estimating where each expression overflows, and writing tests at the limits instead of near zero.
- First step
- Find where each expression is computed, not where it is stored: Java evaluates x * x + y * y in int and widens the result to long only afterwards. Then work out the input sizes at which each int expression passes 2,147,483,647, and write tests at those sizes.
- Follow-ups
-
- What does Java print, and why is there no exception?
- What would the same code do in C++ and in Go?
- Which unit tests would have caught both?
From the lesson K closest points to origin and closest values
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
Prove that the heap of end times opens the fewest rooms possible. Then a colleague suggests sorting the start times and the end times separately and sweeping them with two pointers. Is that correct, and when would you prefer it?
- What it tests
- A lower-bound proof for a greedy count, tie handling at equal times, and comparing two O(n log n) methods.
- First step
- Look at the moment the heap opens a new room, and ask what is true at that moment of every room that is already open.
- Follow-ups
-
- At equal times, should the sweep process an end or a start first?
- Which method also tells you which room each meeting gets?
- The times are minutes of one day. Is there something faster?
From the lesson Scheduling with heaps
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 4 minutes
-
Fresher to mid
A shortest-job-first printer simulation passes the examples but fails hidden tests with idle gaps and equal durations. Walk through what the loop must do after an idle gap and on a tie, and how you would test it.
- What it tests
- The order of steps in a simulation, the tie rule, the size of the clock, and testing against a brute force.
- First step
- Trace the loop by hand on two jobs that arrive in the same minute while the printer is idle, and on two jobs of equal duration whose indices and arrivals are in opposite orders.
- Follow-ups
-
- The jobs come unsorted, and two arrive at the same minute.
- Durations reach 10⁹ and there are 10⁵ jobs. What overflows?
- How would you report each job's waiting time as well?
From the lesson Scheduling with heaps
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Senior to staff
The office now has k identical printers. Each free printer takes the shortest waiting job, the lower printer number first when several are free. Return the printer and start time of every job. Design the simulation and give its cost.
- What it tests
- An event-driven simulation with two heaps, ordering of simultaneous events, and the cost with n jobs and k printers.
- First step
- List the events that can change what the printers do, and decide what must be completely up to date at a given minute before any job is assigned at that minute.
- Follow-ups
-
- Why must printers that free up at the same minute be released before any job is assigned?
- k = 1,000 and n = 10⁶. What does each event cost?
- Jobs may be cancelled while they wait.
From the lesson Scheduling with heaps
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Fresher to mid
A leaderboard keeps (score, player) entries in a max-heap and treats an entry as current when its score equals the player's current score. It passes most tests, but sometimes lists the same player twice in the top three. Why, and what do you change?
- What it tests
- Finding why a stale-entry check lets an entry through, fixing what identifies an entry, and testing the fix.
- First step
- Look for a short sequence of updates after which two entries of the same player both pass the check, then follow what a listing that pops entries does with them.
- Follow-ups
-
- Why do highest() and lowest() still give the right number with the price check?
- Is a version per player enough, or does it have to be global?
- Could you avoid versions by storing a reference to the current entry instead?
From the lesson Heaps with lazy deletion
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Mid to senior
A service tracks the lowest price of 10,000 products with a min-heap and lazy deletion. Prices fall slowly all day, and by evening the process uses gigabytes of memory, although only 10,000 prices are current. Explain the growth and fix it without hurting the cost per update.
- What it tests
- Explaining memory growth under lazy deletion, a fix with an amortised cost argument, and the alternatives.
- First step
- Ask where an old price ends up in a min-heap when prices fall, and whether any query will ever reach it. Then estimate how many entries a day of updates leaves behind.
- Follow-ups
-
- When exactly would you rebuild, and what does it cost on average per update?
- The same service also needs the highest price. Does that heap grow too?
- Would an ordered map be the better choice here?
From the lesson Heaps with lazy deletion
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
-
Senior to staff
Design a game leaderboard for a million players with three operations: set a player's score, return the top 10, and return one player's rank. Scores change thousands of times a second. Where does lazy deletion fit, and where does it not?
- What it tests
- Choosing a structure per operation, the cost of queries over stale entries, and the trade-offs of each option.
- First step
- Write each operation's target cost first. Then ask which of the three operations a heap can answer from its top alone, and what the others need to count.
- Follow-ups
-
- What does one top-10 query cost when many entries near the top are stale?
- Scores are integers from 0 to 1,000,000. How does that change the design?
- Two players tie. How is the rank defined, and how do you keep it stable?
From the lesson Heaps with lazy deletion
Model answer, Pro.In the answer:
- Model answer
- Follow-up answers
- Common mistakes
- Rubric
- Variants
- about 3 minutes
All Coding Interview Patterns interview questions · The Coding Interview Patterns track