Implement a balance tracker and interval merger
Company: Rippling
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates data-structure design and algorithmic problem-solving skills, focusing on incremental aggregation for an in-memory ledger, historical prefix-sum style queries, and merging of overlapping intervals, and it falls under the Coding & Algorithms domain.
Part 1: Delivery Driver Balance Tracker
Constraints
- 0 <= len(operations) <= 200000
- driver_id consists of printable characters and has length between 1 and 50
- -10^9 <= amount <= 10^9
- The running balances and total fit in a signed 64-bit integer
Examples
Input: [('ADD', 'd1', 10), ('ADD', 'd2', 5), ('BALANCE', 'd1'), ('TOTAL',), ('ADD', 'd1', -3), ('TOTAL',)]
Expected Output: [10, 15, 12]
Explanation: After the updates, d1 has 10, then total is 15, then d1 becomes 7 and total becomes 12.
Input: [('BALANCE', 'ghost'), ('TOTAL',)]
Expected Output: [0, 0]
Explanation: An unseen driver has balance 0, and the total is also 0.
Input: [('ADD', 'a', 7), ('ADD', 'a', 3), ('ADD', 'b', -4), ('BALANCE', 'a'), ('BALANCE', 'b'), ('TOTAL',)]
Expected Output: [10, -4, 6]
Explanation: Driver a ends with 10, driver b ends with -4, and the total is 6.
Input: []
Expected Output: []
Explanation: No operations means no query answers.
Hints
- If TOTAL is called often, do not sum all balances each time. Keep a cached running total and update it whenever an ADD happens.
- A missing driver has balance 0, so BALANCE for an unseen driver should return 0.
Part 2: Merge Intervals
Constraints
- 0 <= len(intervals) <= 200000
- -10^9 <= start <= end <= 10^9
Examples
Input: [[1, 3], [2, 6], [8, 10], [15, 18]]
Expected Output: [[1, 6], [8, 10], [15, 18]]
Explanation: The first two intervals overlap and merge into [1, 6].
Input: [[1, 4], [4, 5]]
Expected Output: [[1, 5]]
Explanation: Touching closed intervals are merged.
Input: []
Expected Output: []
Explanation: No intervals to merge.
Input: [[5, 7]]
Expected Output: [[5, 7]]
Explanation: A single interval remains unchanged.
Input: [[6, 8], [1, 9], [2, 4], [4, 7]]
Expected Output: [[1, 9]]
Explanation: All intervals are contained within or overlap with [1, 9].
Hints
- Sorting by interval start makes it possible to merge in one left-to-right pass.
- Compare each interval with the last merged interval. If they overlap, extend the end; otherwise, start a new merged interval.