KatInterview

Peak Overlap Point, Bounded BST Sums, and Call-Stack Self Time

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalssweep-linebstprefix-sums

Last updated

Three separate tasks: find an integer with the highest interval overlap, sum BST values within a range (plus many-query speedups), and compute per-function self time from nested start/end logs.

This problem bundles three independent tasks. For each, state your assumptions, give a simple baseline, then present an improved solution with its complexity.

Part 1: Point with the greatest overlap

You have a closed integer window [-M, M] and a list of closed integer intervals [l, r]. An interval [l, r] covers every integer l, l+1, ..., r. Intervals may overlap arbitrarily.

The overlap of an integer is the number of intervals containing it. Return any integer in [-M, M] whose overlap is the largest. If several integers tie, any of them is acceptable.

Discuss what you would assume about the size of M, the number of intervals, and whether endpoints always lie inside the window.

Part 2: Sum of BST values in a range

You are given the root of a binary search tree and two integers low and high. Return the sum of every node value v with low <= v <= high.

Follow-up: the tree is huge and you must answer a very large number of queries, each with different low and high. What preprocessing or data structure would you use? Consider both a tree that never changes and one that receives inserts and deletes between queries.

Part 3: Self time of functions from a log

There are n functions numbered 0 to n-1, running on a single thread. You get a chronologically ordered list of log strings, each in one of two forms:

  • "<id>:start:<timestamp>"
  • "<id>:end:<timestamp>"

A start means the function begins running at the start of that timestamp. An end means it finishes at the end of that timestamp, so the end timestamp itself counts as time spent. Functions can call other functions, so intervals nest.

Return an array ans of length n where ans[i] is the self time of function i: the total time it was executing, not counting time spent inside functions it called. State any further assumptions, such as whether recursion can occur.

Hints

Hint 1

Part 1: coverage only changes at interval boundaries. Each interval adds one at l and removes one at r+1. Think difference array when M is small, sorted events when M is huge.

Hint 2

Part 2: use the BST ordering to skip entire subtrees. If a node is below low, nothing in its left subtree can qualify. For many queries, an in-order traversal gives a sorted array you can combine with prefix sums.

Hint 3

Part 3: keep a stack of running functions and a marker for the first time unit not yet credited. On start, credit the current top for the gap; on end, credit the popped function including the end timestamp, then move the marker to t+1.