Peak Concurrent Active Loans
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A lending system records each issued loan as a two-element list [start_time, end_time]. Every loan spans the half-open time interval [start_time, end_time): it is active starting at start_time and at every moment strictly before end_time, and it is already repaid and inactive at end_time.
Implement:
def max_active_loans(loans: List[List[int]]) -> int:
Given loans, compute and return the maximum number of loans that are simultaneously active at any single point in time.
Examples
Example 1
Input: loans = [[10, 40], [20, 50], [30, 40], [40, 70]]
Output: 3
Over [30, 40), loans [10, 40), [20, 50), and [30, 40) are all active together (3 concurrent loans). At t = 40, [10, 40) and [30, 40) both end before [40, 70) begins, leaving [20, 50) and [40, 70) (2 loans) active over [40, 50).
Example 2
Input: loans = [[0, 30], [5, 12], [12, 20], [22, 28]]
Output: 2
Loan [0, 30) overlaps each of the three shorter loans, yet [5, 12), [12, 20), and [22, 28) never overlap one another ([5, 12) ends right as [12, 20) starts), so at most 2 loans are ever active simultaneously.
Constraints
1 <= len(loans) <= 10^5- Each element of
loansis[start_time, end_time]with0 <= start_time < end_time <= 10^9
Step-by-step walkthrough
Understand the half-open interval rule
Each loan
[start, end]is active on the half-open interval[start, end): it counts atstartand at every moment in between, except atend, where the loan has already finished. We want the highest number of loans active at the exact same moment.- Input:
1 <= len(loans) <= 10^5pairs[start, end]with0 <= start < end <= 10^9. - Output: a single integer, the peak overlap.
Drawing Example 1 (
[[10, 40], [20, 50], [30, 40], [40, 70]]) on a number line shows why the boundary rule matters (●= included start,○= excluded end):time: 10 20 30 40 50 60 70 [10, 40): ●━━━━━━━━━━━━━━━━━○ [20, 50): ●━━━━━━━━━━━━━━━━━○ [30, 40): ●━━━━━○ [40, 70): ●━━━━━━━━━━━━━━━━━○ active: 1 2 3 2 1 1 0At
t = 40, loans[10, 40)and[30, 40)have already ended while[40, 70)is just starting. Only[20, 50)and[40, 70)are active att = 40, so the peak stays3(reached on[30, 40)), not4.- Input:
Why checking every timestamp or pair is too slow
Two obvious ideas run into wall-clock or memory limits right away:
- Counting every integer timestamp
tfrom0to10^9: with coordinates up to a billion, an arraycount[t]uses gigabytes of memory and takes up to10^9steps even when there is only one loan. - Checking how many loans are active at each loan's
starttime: because the active count only goes up when a loan starts, the peak must occur at somestart. Testing allnloans against eachstartis always accurate, so it makes a great brute-force test oracle, butO(n^2)takes up to10^10comparisons whenn = 10^5.
Notice what that second idea gets right: nothing changes in the quiet stretches between endpoints. Only the
2nstart and end timestamps matter.- Counting every integer timestamp
Key idea: turn intervals into +1 and -1 timeline events
Imagine tracking how many people are inside a bank lobby. You do not need to recount the whole room every second; you only record
+1when someone enters and-1when someone leaves, sort those log entries by time, and adjust a single running counter.We can do the exact same sweep-line pass over loans:
start_timebecomes(start_time, +1)— one loan becomes active.end_timebecomes(end_time, -1)— one loan stops being active.
Because there are
nloans, there are only2nevents in total, no matter how large10^9is.Break ties so endings happen before starts
What happens when loans end at
t = 40and another starts att = 40? Compare the two orders whenactive_loansenterst = 40at3(from[10, 40),[20, 50), and[30, 40)):Wrong order (+1 first): 3 --(40,+1)--> 4 (false peak!) --(40,-1)--> 3 --(40,-1)--> 2 Right order (-1 first): 3 --(40,-1)--> 2 --(40,-1)--> 1 --(40,+1)--> 2Because a loan is already inactive at its
end_time, every end event at timetmust run before any start event at timet.Representing each event as
(timestamp, delta)withdelta = -1for an end anddelta = +1for a start gives us this tie-breaker automatically: Python sorts tuples by item0(timestamp) first and item1(delta) second, and-1 < +1.def build_events(loans: List[List[int]]) -> List[Tuple[int, int]]: # events: list of (timestamp, delta) pairs, e.g. [(1, 1), (5, -1), ...] # delta = +1 means a loan starts; delta = -1 means a loan ends. events: List[Tuple[int, int]] = [] # Phase 1: split every half-open [start, end) loan into two timeline events. for start_time, end_time in loans: events.append((start_time, 1)) events.append((end_time, -1)) # Phase 2: sort chronologically. Python compares tuple item 0 (timestamp) first, # then breaks ties with item 1 (delta). Because -1 < +1, all endings at time t # run BEFORE any starts at time t, matching the half-open [start, end) rule. events.sort() return eventsSweep through the sorted events
Now walk through
eventsin sorted order, add eachdeltatoactive_loans, and updatepeak_loanswheneveractive_loansreaches a new high.Is it safe to update
peak_loansin the middle of several events that share the same timestampt? Yes: at timestampt, all-1events happen first (soactive_loansonly goes down), and then all+1events happen (climbing up to the true count at timet). None of the intermediate numbers can ever exceed both the true count right beforetand the true count att.def max_active_loans(loans: List[List[int]]) -> int: events = build_events(loans) # Phase 3: sweep across sorted events, tracking current and peak active loans. active_loans = 0 peak_loans = 0 for timestamp, delta in events: active_loans += delta # Safe to check on every event: at a shared timestamp, all -1 deltas run # before any +1 deltas, so active_loans never spikes above the true count. if active_loans > peak_loans: peak_loans = active_loans return peak_loansTrace Example 1 step by step
For
loans = [[10, 40], [20, 50], [30, 40], [40, 70]],build_eventsproduces 8 sorted tuples:event meaning active_loans peak_loans (10, +1) [10, 40) starts 1 1 (20, +1) [20, 50) starts 2 2 (30, +1) [30, 40) starts 3 3 (40, -1) [10, 40) ends first 2 3 (40, -1) [30, 40) ends second 1 3 (40, +1) [40, 70) starts next 2 3 (50, -1) [20, 50) ends 1 3 (70, -1) [40, 70) ends 0 3peak_loansfinishes at3, matching Example 1.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def build_events(loans: List[List[int]]) -> List[Tuple[int, int]]: # events: list of (timestamp, delta) pairs, e.g. [(1, 1), (5, -1), ...] # delta = +1 means a loan starts; delta = -1 means a loan ends. events: List[Tuple[int, int]] = [] # Phase 1: split every half-open [start, end) loan into two timeline events. for start_time, end_time in loans: events.append((start_time, 1)) events.append((end_time, -1)) # Phase 2: sort chronologically. Python compares tuple item 0 (timestamp) first, # then breaks ties with item 1 (delta). Because -1 < +1, all endings at time t # run BEFORE any starts at time t, matching the half-open [start, end) rule. events.sort() return events def max_active_loans(loans: List[List[int]]) -> int: events = build_events(loans) # Phase 3: sweep across sorted events, tracking current and peak active loans. active_loans = 0 peak_loans = 0 for timestamp, delta in events: active_loans += delta # Safe to check on every event: at a shared timestamp, all -1 deltas run # before any +1 deltas, so active_loans never spikes above the true count. if active_loans > peak_loans: peak_loans = active_loans return peak_loans✅ Submit now — all tests should pass.
Intuition & how it works
Think of tracking how many customers are inside a bank lobby at once. Instead of replaying security footage second-by-second across an entire year, you only need a logbook of door events: write +1 whenever someone walks in, write -1 whenever someone walks out, sort those log lines by timestamp, and adjust a single counter as you read down the page. That technique—jumping from one change point to the next in chronological order—is called a sweep-line algorithm (an algorithm that moves an imaginary vertical line across a timeline and updates state only where intervals start or stop).
Naive approaches fail because of both scale and boundary rules. Allocating an array count[t] for every integer timestamp up to 10^9 uses gigabytes of memory and billions of steps even for two loans, while checking every loan against every other loan takes O(n^2) time (10^10 checks for 10^5 loans). Worse, simply counting how many other loans overlap a single loan gives wrong answers because interval overlap is not transitive (a relation where A matching B and B matching C guarantees A matches C): [0, 4) overlaps both [0, 2) and [2, 4), yet those two never overlap each other.
Each loan uses a half-open interval [start, end) (an interval that includes start but excludes end), so at a tie like t = 40 an ending loan has already left before a starting loan arrives. Encoding an end as (end, -1) and a start as (start, +1) makes plain tuple sorting put (40, -1) before (40, +1). On [[10, 40], [20, 50], [30, 40], [40, 70]], the sorted events move the running counter through 1 -> 2 -> 3 -> 2 -> 1 -> 2 -> 1 -> 0 for a peak of 3.
Complexity
- Time: O(n log n), where
nis the number of loans. Creating2nevent tuples takes oneO(n)pass, sorting those2ntuples takesO(n log n)comparisons, and sweeping through the sorted list takes one moreO(n)pass. - Space: O(n) because we store
2n(timestamp, delta)tuples inevents. The memory depends only on how many loans exist, never on how large the timestamps (up to10^9) are.
Edge cases
- A single loan: produces one
+1followed by one-1, returning1. - Back-to-back touching loans (
[[1, 2], [2, 3], [3, 4]]): att = 2andt = 3, the-1runs before the+1, so the counter drops to0before returning to1, giving1. - Multiple starts and ends at the exact same timestamp (
[[1, 3], [2, 3], [3, 4], [3, 5]]): both(3, -1)events run before both(3, +1)events, so the peak stays2instead of spiking to4. - Identical duplicate intervals: three copies of
[3, 7]produce three(3, +1)events and correctly reach3. - Unsorted input:
events.sort()orders all endpoints regardless of howloanswas ordered. - Extreme timestamps (
0to10^9): timestamps are only compared, never used as array indices, so10^9costs the same as10.
Common mistakes
- Processing starts before ends at ties: encoding a start as
(time, 0)and an end as(time, 1)puts starts first, turning[[10, 40], [20, 50], [30, 40], [40, 70]]into a false peak of4att = 40. - Sorting only by
key=lambda e: e[0]: Python's sort is stable, meaning ties stay in their original input order.[[10, 40], [40, 70]]happens to put(40, -1)first, whereas[[40, 70], [10, 40]]puts(40, +1)first and wrongly returns2. - Building a difference array of length
max_end: allocating[0] * (10**9 + 1)exhausts memory immediately. - Counting how many intervals intersect each interval:
[0, 30)intersects[5, 12),[12, 20), and[22, 28)in Example 2 (three neighbors, total four intervals), yet those three inner loans never overlap each other, so the real peak is2, not4.
Alternative approaches
- Two sorted arrays with two pointers (
O(n log n)time,O(n)space): sort allstarttimes in one list and allendtimes in another. Advance the start pointer (active += 1) strictly whenstarts[i] < ends[j], and advance the end pointer (active -= 1) wheneverstarts[i] >= ends[j]so ties process endings first. - Sorting + min-heap of end times (
O(n log n)time,O(peak)heap space): sort loans bystart_timeand maintain a min-heap (a tree-based priority queue that always exposes and removes its smallest element inO(log n)time) holding theend_timeof currently active loans. Before pushing a new loan starting ats, pop everyend_time <= s; the largest heap size seen is the answer.
Follow-up questions
- What adjustment is needed if each loan interval is closed on both ends
[start, end]so a loan remains active at its exact end timestamp? With inclusive endpoints, a loan ending attand a loan starting attare both active at momentt, so starts must run before ends at ties. For integer timestamps,[start, end]is identical to the half-open interval[start, end + 1), so changing(end_time, -1)to(end_time + 1, -1)(or sorting by(timestamp, -delta)) handles it cleanly and gives4on Example 1 att = 40. - How do your runtime and memory scale when timestamps reach
10^9, and can auxiliary memory be reduced belowO(n)? Our event sweep runs inO(n log n)time andO(n)space, which is already completely independent of the10^9time range because it stores only the2nendpoints that actually appear. If someone wanted to use a difference array without blowing up memory on large timestamps, they would first apply coordinate compression (mapping the at most2ndistinct timestamps onto compact indices0 .. m - 1in sorted order), which also takesO(n log n)time andO(n)space. If modifyingloansin place is allowed, sortingloansby start time and keeping a min-heap of active end times reduces auxiliary memory toO(peak_loans). - How would you adapt the sweep to also output the contiguous time window over which the peak concurrency occurs? Group and apply all events sharing the same
timestamptogether soactive_loansreflects the true count over the stretch[timestamp, next_timestamp). Wheneveractive_loansbeatspeak_loans, start a new peak window[timestamp, next_timestamp), and if the very next timestamp group keepsactive_loans == peak_loans(for instance when one loan ends at12while another starts at12), extendpeak_endto merge the contiguous stretch:
def peak_interval(loans: List[List[int]]) -> Tuple[int, Optional[int], Optional[int]]:
events = build_events(loans)
active_loans = 0
peak_loans = 0
peak_start: Optional[int] = None
peak_end: Optional[int] = None
in_first_peak = False
i = 0
while i < len(events):
current_time = events[i][0]
while i < len(events) and events[i][0] == current_time:
active_loans += events[i][1]
i += 1
if active_loans > peak_loans:
peak_loans = active_loans
peak_start = current_time
peak_end = events[i][0]
in_first_peak = True
elif active_loans == peak_loans and in_first_peak and peak_loans > 0:
peak_end = events[i][0]
else:
in_first_peak = False
return peak_loans, peak_start, peak_end
Follow-up questions
- What adjustment is needed if each loan interval is closed on both ends [start, end] so a loan remains active at its exact end timestamp?
- How do your runtime and memory scale when timestamps reach 10^9, and can auxiliary memory be reduced below O(n)?
- How would you adapt the sweep to also output the contiguous time window over which the peak concurrency occurs?
Similar questions
- Stock Trading Profit With Bounded Trades
- Open Lockers After Multi-Pass Toggling
- First-Player Strategy on an Even-Length Coin Line
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses