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 loans is [start_time, end_time] with 0 <= start_time < end_time <= 10^9

Step-by-step walkthrough

  1. Understand the half-open interval rule

    Each loan [start, end] is active on the half-open interval [start, end): it counts at start and at every moment in between, except at end, where the loan has already finished. We want the highest number of loans active at the exact same moment.

    • Input: 1 <= len(loans) <= 10^5 pairs [start, end] with 0 <= 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     0
    

    At 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 at t = 40, so the peak stays 3 (reached on [30, 40)), not 4.

  2. 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 t from 0 to 10^9: with coordinates up to a billion, an array count[t] uses gigabytes of memory and takes up to 10^9 steps even when there is only one loan.
    • Checking how many loans are active at each loan's start time: because the active count only goes up when a loan starts, the peak must occur at some start. Testing all n loans against each start is always accurate, so it makes a great brute-force test oracle, but O(n^2) takes up to 10^10 comparisons when n = 10^5.

    Notice what that second idea gets right: nothing changes in the quiet stretches between endpoints. Only the 2n start and end timestamps matter.

  3. 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 +1 when someone enters and -1 when 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_time becomes (start_time, +1) — one loan becomes active.
    • end_time becomes (end_time, -1) — one loan stops being active.

    Because there are n loans, there are only 2n events in total, no matter how large 10^9 is.

  4. Break ties so endings happen before starts

    What happens when loans end at t = 40 and another starts at t = 40? Compare the two orders when active_loans enters t = 40 at 3 (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)--> 2
    

    Because a loan is already inactive at its end_time, every end event at time t must run before any start event at time t.

    Representing each event as (timestamp, delta) with delta = -1 for an end and delta = +1 for a start gives us this tie-breaker automatically: Python sorts tuples by item 0 (timestamp) first and item 1 (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 events
    
  5. Sweep through the sorted events

    Now walk through events in sorted order, add each delta to active_loans, and update peak_loans whenever active_loans reaches a new high.

    Is it safe to update peak_loans in the middle of several events that share the same timestamp t? Yes: at timestamp t, all -1 events happen first (so active_loans only goes down), and then all +1 events happen (climbing up to the true count at time t). None of the intermediate numbers can ever exceed both the true count right before t and the true count at t.

    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
    
  6. Trace Example 1 step by step

    For loans = [[10, 40], [20, 50], [30, 40], [40, 70]], build_events produces 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              3
    

    peak_loans finishes at 3, matching Example 1.

  7. 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 n is the number of loans. Creating 2n event tuples takes one O(n) pass, sorting those 2n tuples takes O(n log n) comparisons, and sweeping through the sorted list takes one more O(n) pass.
  • Space: O(n) because we store 2n (timestamp, delta) tuples in events. The memory depends only on how many loans exist, never on how large the timestamps (up to 10^9) are.

Edge cases

  • A single loan: produces one +1 followed by one -1, returning 1.
  • Back-to-back touching loans ([[1, 2], [2, 3], [3, 4]]): at t = 2 and t = 3, the -1 runs before the +1, so the counter drops to 0 before returning to 1, giving 1.
  • 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 stays 2 instead of spiking to 4.
  • Identical duplicate intervals: three copies of [3, 7] produce three (3, +1) events and correctly reach 3.
  • Unsorted input: events.sort() orders all endpoints regardless of how loans was ordered.
  • Extreme timestamps (0 to 10^9): timestamps are only compared, never used as array indices, so 10^9 costs the same as 10.

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 of 4 at t = 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 returns 2.
  • 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 is 2, not 4.

Alternative approaches

  • Two sorted arrays with two pointers (O(n log n) time, O(n) space): sort all start times in one list and all end times in another. Advance the start pointer (active += 1) strictly when starts[i] < ends[j], and advance the end pointer (active -= 1) whenever starts[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 by start_time and maintain a min-heap (a tree-based priority queue that always exposes and removes its smallest element in O(log n) time) holding the end_time of currently active loans. Before pushing a new loan starting at s, pop every end_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 at t and a loan starting at t are both active at moment t, 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 gives 4 on Example 1 at t = 40.
  • How do your runtime and memory scale when timestamps reach 10^9, and can auxiliary memory be reduced below O(n)? Our event sweep runs in O(n log n) time and O(n) space, which is already completely independent of the 10^9 time range because it stores only the 2n endpoints 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 most 2n distinct timestamps onto compact indices 0 .. m - 1 in sorted order), which also takes O(n log n) time and O(n) space. If modifying loans in place is allowed, sorting loans by start time and keeping a min-heap of active end times reduces auxiliary memory to O(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 timestamp together so active_loans reflects the true count over the stretch [timestamp, next_timestamp). Whenever active_loans beats peak_loans, start a new peak window [timestamp, next_timestamp), and if the very next timestamp group keeps active_loans == peak_loans (for instance when one loan ends at 12 while another starts at 12), extend peak_end to 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

Similar questions

More Tekion interview questions

All 4 Tekion questions →