Compute interval mode, BST range sum, exclusive time
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
You are given three independent coding tasks. For each one, write working code and state its time and space complexity.
### Constraints & Assumptions
- The three parts are independent; solve each on its own.
- **Part 1:** $M$ and every interval endpoint are integers, and intervals are inclusive on both ends. Neither $M$ nor the number of intervals $k$ is fixed, and $M$ may be far larger than $k$, so be explicit about how your time and memory grow with each.
- **Part 2:** The tree has $n$ nodes and height $h$. It is a valid BST but is not guaranteed to be balanced, so $h$ can be as large as $n$.
- **Part 3:** Timestamps are integers, the logs are in chronological order, and execution is single-threaded, so exactly one function runs at any moment. A `start` at time $t$ begins at the start of time unit $t$; an `end` at time $t$ finishes at the end of time unit $t$.
### Clarifying Questions to Ask
- May I rely on the language's standard library (sorting, binary search, ordered maps)?
- Can I assume every input is valid, or should I detect bad input? If so, should I raise an error or return a sentinel?
- Would you like a simple correct version first and then an optimized one, or should I go straight to the best approach?
### Part 1: Most frequent integer covered by intervals
You are given an integer range $[-M, M]$ and a list of $k$ inclusive integer intervals. An interval $[l, r]$ covers each of the integers $l, l+1, \dots, r$ once; for example, `[1, 3]` covers `{1, 2, 3}`. Intervals may overlap.
Return **any** integer in $[-M, M]$ with the **maximum coverage count**, meaning it lies in the most intervals once every interval is expanded to its integers. If several integers tie for the maximum, returning any one of them is fine.
**Example:** `M = 10`, intervals `[1, 3]`, `[2, 4]`, `[5, 8]`. The integers 2 and 3 are each covered twice and nothing is covered more often, so return 2 or 3.
```hint Where to start
Expanding every interval into its integers can cost $O(M)$ per interval. Coverage only changes at a few boundary points. Think about recording just those changes rather than every integer.
```
```hint When M is huge
If an array over the whole range $[-M, M]$ is too big, notice that only the change points matter, and there are at most two per interval. How could you visit just those?
```
#### Clarifying Questions for this Part
- Roughly how large is $M$ compared with $k$? Can I afford memory proportional to $M$?
- Are all endpoints guaranteed to lie within $[-M, M]$ with $l \le r$, or should I clip or skip intervals that don't?
- What should I return when there are no intervals, so every integer has coverage zero?
- Is any tie-break preferred, such as the smallest integer?
#### What This Part Should Cover
- Avoiding per-integer expansion by tracking only where coverage changes, with the inclusive right endpoint handled exactly.
- Choice of representation, justified by the relative sizes of $M$ and $k$.
- Correct handling of changes that share a coordinate, of ties, and of empty or out-of-range input.
- Time and space complexity stated in terms of both $M$ and $k$.
### Part 2: Range sum on a BST, then many queries
Given the root of a binary search tree (BST) and two integers `low` and `high`, return the **sum of all node values** $v$ such that $\text{low} \le v \le \text{high}$.
**Example:** For the BST with level order `[8, 3, 10, 1, 6, null, 14, null, null, 4, 7, 13]`, `low = 4` and `high = 10`, the in-range values are 4, 6, 7, 8 and 10, so return 35.
**Follow-up:** The tree is very large and you must answer **many** queries with different `[low, high]` ranges. What preprocessing or data structure would you use to make each query faster?
```hint Use the ordering
At a node whose value is below `low`, which of its subtrees cannot contain any in-range value? Skip whatever the BST property rules out instead of visiting every node.
```
```hint Many queries
An in-order traversal lists the values in sorted order. Which precomputed array turns "the sum of a contiguous run of sorted values" into a single subtraction once you have found the two ends of the run?
```
```hint If the tree changes
If nodes are inserted or deleted between queries, rebuilding a flat array each time is expensive. Think about an extra value each node could store about its own subtree, and how one root-to-leaf walk could then add up everything on one side of a boundary.
```
#### Clarifying Questions for this Part
- Can values repeat, and if so, on which side are duplicates stored?
- For the follow-up: is the tree static, or are there inserts and deletes between queries?
- Are all queries known up front, or do they arrive one at a time?
- How much extra memory may the preprocessing use, and can a sum overflow a 32-bit integer?
#### What This Part Should Cover
- Using the BST ordering to prune whole subtrees, with complexity stated for both balanced and skewed trees.
- A preprocessing scheme that makes each query sublinear, with its build cost, query cost and memory.
- If the interviewer adds inserts and deletes, whether the scheme survives them and what it costs to keep current.
- Implementation hazards such as recursion depth on a skewed tree and integer overflow of the sum.
### Part 3: Exclusive execution time from logs
There are $n$ functions labelled `0` to `n - 1`. You are given a list of logs in chronological order. Each log is a string in one of two forms:
`"<functionId>:start:<timestamp>"` or `"<functionId>:end:<timestamp>"`
- `start` means the function starts at that timestamp.
- `end` means the function ends at that timestamp (inclusive).
- Functions may be nested because one function calls another.
Return an array `ans` of length $n$ where `ans[i]` is the **exclusive time** of function `i`: the time spent in `i` excluding the time spent in any functions it calls.
**Example:** `n = 3`, logs `["0:start:0", "1:start:2", "2:start:3", "2:end:4", "1:end:6", "0:end:8"]`. Function 0 owns time units 0, 1, 7 and 8; function 1 owns units 2, 5 and 6; function 2 owns units 3 and 4. Return `[4, 3, 2]`.
```hint Data structure
Nested calls behave like a call stack: the function running right now is always the most recently started one that has not yet ended.
```
```hint Accounting for time
Think about which function owns the time between two consecutive log lines. Watch the off-by-one: an `end` at $t$ includes unit $t$ itself.
```
#### Clarifying Questions for this Part
- Can a function call itself recursively, and can the same function be called more than once?
- Are the logs guaranteed to be well formed (each `end` matches the most recent unmatched `start`), or should I validate them?
- Can there be idle gaps between top-level calls, and should that time be left unattributed?
#### What This Part Should Cover
- Modelling nested calls so that every time slice is charged to exactly one function.
- Getting the inclusive `end` boundary right, so that slices neither overlap nor leave gaps.
- Recursion, repeated calls of the same function, and idle gaps between calls.
- Time and memory stated in terms of the number of logs and the maximum nesting depth, plus robust parsing of the log strings.
### What a Strong Answer Covers
Across all three parts:
- Stating assumptions before coding and letting them drive the choice of approach.
- A correct baseline first, then an optimization whose benefit is explained rather than asserted.
- Complexity expressed in the variables that matter ($M$, $k$, $n$, $h$, number of logs) instead of a generic $O(n)$.
- Deliberate handling of boundaries: inclusive endpoints, empty input and ties.
- Testing by tracing a small example and at least one edge case through the code.
### Follow-up Questions
- **Part 1:** Instead of one integer, return every maximal range of integers that reaches the maximum coverage. And if intervals arrive one at a time and you must report a most-covered integer after each arrival, what data structure would you use?
- **Part 2:** If the sorted values do not fit in memory, how would you lay the data out on disk so that a range-sum query reads only a few blocks?
- **Part 3:** If the logs come from several threads, with each line tagged by a thread id, how does your solution change?
- **Part 3:** How would you also report each function's inclusive time (including its callees) when a function can call itself recursively, without double-counting?
Overview: Solve three independent coding tasks: pick an integer in [-M, M] covered by the most inclusive intervals, sum the values of a binary search tree that fall in a range (then serve many such queries), and compute each function's exclusive run time from nested start/end logs. Inclusive boundaries matter, as does a huge M.
Read the full Meta Software Engineer interview experience this question came from