Peak Overlap Point, Bounded BST Sums, and Call-Stack Self Time
Greedy & IntervalsModel answerLast 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The three parts are independent. For each I give assumptions, a baseline, the improvement, and code.
Part 1: Point with the greatest overlap
Assumptions. Up to about 10^5 intervals. M may be as large as 10^9, so I avoid per-integer arrays unless M is small. Clip endpoints to [-M, M] and drop intervals that become empty. With no intervals, every integer has overlap 0, so return -M.
Baseline. Expand each interval and count per integer. This costs the sum of interval lengths, which can be huge.
Better. Overlap is a step function that changes only at event coordinates: +1 at l and -1 at r+1.
- Small
M: a difference array of size2M+2(offset byM), then a prefix sum. Time O(M + k). - Large
M: build events, sort, and process all events sharing a coordinate together before reading the running count. Time O(k log k), space O(k).
Grouping by coordinate matters. With [1,3] and [4,6], events (4,-1) and (4,+1) occur together. Applying only the +1 first would show a false overlap of 2.
The maximum is reached at the left end of some constant stretch, so checking the running count after each coordinate group is enough. Skip coordinates beyond M (the r+1 = M+1 case).
def most_covered(M, intervals):
events = []
for l, r in intervals:
l, r = max(l, -M), min(r, M)
if l <= r:
events.append((l, 1))
events.append((r + 1, -1))
if not events:
return -M
events.sort()
best_val, best_cnt, cnt = -M, 0, 0
i = 0
while i < len(events):
x = events[i][0]
while i < len(events) and events[i][0] == x:
cnt += events[i][1]
i += 1
if cnt > best_cnt and x <= M:
best_cnt, best_val = cnt, x
return best_val
Edge cases. No intervals; single-point intervals [x, x]; negative coordinates (offset by M in the array version); ties (keep the first).
Part 2: BST range sum
Idea. Use the ordering to prune.
- If
node.val < low, only the right subtree can contain in-range values. - If
node.val > high, only the left subtree can. - Otherwise add the node and visit both children.
Time is O(h + m), where h is the height and m the number of in-range nodes; worst case O(n). Space is O(h). An explicit stack avoids recursion-depth problems on skewed trees.
def range_sum_bst(root, low, high):
total, stack = 0, [root]
while stack:
node = stack.pop()
if not node:
continue
if node.val < low:
stack.append(node.right)
elif node.val > high:
stack.append(node.left)
else:
total += node.val
stack.append(node.left)
stack.append(node.right)
return total
Follow-up: many queries.
Static tree. Do one in-order traversal to get a sorted array vals, then build prefix sums pre where pre[i] = sum(vals[:i]). Each query is two binary searches:
from bisect import bisect_left, bisect_right
def query(vals, pre, low, high):
if low > high:
return 0
return pre[bisect_right(vals, high)] - pre[bisect_left(vals, low)]
Preprocessing is O(n) time and space; each query is O(log n).
Dynamic tree. Use a balanced BST (AVL, red-black, treap) where each node stores its subtree sum, updated during insertions, deletions and rotations. Then sum(<= high) - sum(< low) each follow one root-to-leaf path, giving O(log n) for queries and updates. If all values are known in advance, a Fenwick tree over compressed coordinates gives the same bounds with less code.
Edge cases. Empty tree; low > high returns 0; duplicates (if allowed, each in-range node is still counted).
Part 3: Self time from logs
Assumptions. Single thread, integer timestamps, logs sorted and well formed (every end matches the most recent unmatched start). A function with start:2 and end:5 runs 4 units. The same id may appear multiple times on the stack (recursion).
Idea. Keep a stack of active ids and a pointer prev, the first time unit not yet credited to anyone.
- On
startatt: if the stack is non-empty, credit the top functiont - prev; push the new id; setprev = t. - On
endatt: pop the id; credit itt - prev + 1; setprev = t + 1.
Only the top of the stack is running at any moment, and every time unit between consecutive events is credited exactly once to that function. The +1 and prev = t + 1 reflect inclusive ends: the caller resumes at t + 1. Recursion needs no special handling because credit goes to the id, not the frame.
def exclusive_time(n, logs):
ans = [0] * n
stack, prev = [], 0
for log in logs:
fid, kind, ts = log.split(":")
fid, ts = int(fid), int(ts)
if kind == "start":
if stack:
ans[stack[-1]] += ts - prev
stack.append(fid)
prev = ts
else:
ans[stack.pop()] += ts - prev + 1
prev = ts + 1
return ans
Time O(L) for L logs; space O(depth) for the stack.
Edge cases. Empty log gives all zeros; a function that calls another at its very first unit gets 0 before the call; back-to-back calls and a caller that ends immediately after a callee.
Common mistakes. Forgetting inclusive ends (off by one); processing a same-coordinate +1 before -1 in Part 1; using recursion on a skewed tree in Part 2; reusing a function's start time instead of a running prev, which double-counts nested time in Part 3.