Earliest Peak Concurrent RAM Window

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A cluster scheduler logs the RAM footprint of jobs running on a host machine. Each job entry in processes has the form [start, end, memory], meaning that job reserves memory units of RAM across the half-open time window [start, end)—it is active at moment t whenever start <= t < end.

Implement find_peak_memory(processes) to return (peak_memory, peak_start, peak_end), where peak_memory is the highest combined RAM held simultaneously at any moment, and [peak_start, peak_end) is the earliest positive-duration continuous window (peak_start < peak_end) throughout which combined RAM stays at peak_memory.

Observe the following boundary and tie-breaking rules:

  • Half-open hand-offs: A job finishing at time t releases its RAM at the exact instant another job starting at time t claims its RAM; the two jobs never overlap at t, nor is there an idle gap at t.
  • Contiguous merging: Whenever adjacent time segments sustain peak_memory back-to-back with no drop between them, coalesce them into a single [peak_start, peak_end) window.
  • Earliest tie-breaker: If peak_memory is reached during two or more separate windows with lower usage in between, return the window with the smallest peak_start.
  • Empty log: When processes contains zero entries, return (0, 0, 0).
def find_peak_memory(processes: List[List[int]]) -> Tuple[int, int, int]:

Examples

Example 1

Input:
processes = [
    [0, 6, 12],
    [2, 5, 18],
    [3, 8, 25],
]

Output:
(55, 3, 5)

Walk-through: Total RAM is 12 on [0, 2), rises to 12 + 18 = 30 on [2, 3), peaks at 12 + 18 + 25 = 55 across [3, 5), then drops to 37 on [5, 6) and 25 on [6, 8).

Example 2

Input:
processes = [
    [1, 5, 8],
    [3, 6, 12],
    [5, 8, 8],
    [9, 11, 20],
]

Output:
(20, 3, 6)

Walk-through: Combined RAM reaches 8 + 12 = 20 at t = 3. At t = 5, the first job frees 8 right as the third job claims 8, keeping total RAM continuously at 20 until t = 6, so [3, 5) and [5, 6) merge into [3, 6). Although [9, 11) also hits 20, [3, 6) starts earlier and wins.

Constraints

  • 0 <= len(processes) <= 2 * 10^5
  • 0 <= start < end <= 10^9
  • 1 <= memory <= 10^9
  • Combined RAM totals can exceed standard 32-bit signed integers.

Step-by-step walkthrough

  1. Understand the goal and the half-open interval rule

    Each process is given as [start, end, memory] and uses memory units of RAM during the half-open interval [start, end). Half-open means the process is active at time t when start <= t < end: it claims memory at start and releases it right at end.

    We need to return (peak_memory, peak_start, peak_end):

    • peak_memory: the highest total RAM used at any moment across all running processes.
    • [peak_start, peak_end): the earliest continuous time window during which total RAM stays at peak_memory without dropping below it.
    • If processes is empty, return (0, 0, 0).

    Pay special attention to simultaneous hand-offs at a shared timestamp t:

    Job A: [1, 5) uses 8 MB   |===========o
    Job B: [5, 8) uses 8 MB               *=========o
    Timeline:                 1     3     5    6    8
    Total RAM:                    8 MB    |   8 MB   (never spikes to 16, never dips to 0)
    

    At t = 5, Job A frees 8 at the exact instant Job B claims 8, so total memory stays smoothly at 8 across [1, 8).

  2. Why checking every timestamp is too slow

    A literal simulation would loop through every integer second t from the earliest start to the latest end and add up all active processes. Because timestamps can reach 10^9, simply looping from 0 to 10^9 would take a billion iterations even for a single process.

    What if we only check the timestamps where a process starts or ends, and re-sum all active processes at each one? With up to n = 2 * 10^5 processes, there are up to 2n = 4 * 10^5 event timestamps, and scanning n processes at each timestamp takes O(n^2) steps (up to 8 * 10^10 checks). That still times out, but it reveals the key insight: total memory never changes between event timestamps.

  3. Key idea: sweep line over net memory changes

    Instead of recounting active processes from scratch, imagine sliding a vertical line from left to right across the timeline (a sweep-line algorithm), keeping a single running_memory counter:

    1. Every process [start, end, memory] adds +memory at start and -memory at end.
    2. If several processes start or end at the exact same timestamp t, we combine all of their + and - changes into one net change at t before reading the new memory level.
    3. Between two sorted adjacent event timestamps timestamps[i] and timestamps[i + 1], nothing starts or stops, so memory stays completely flat across [timestamps[i], timestamps[i + 1]).

    Combining simultaneous changes into a dictionary first automatically handles hand-offs: -8 and +8 at t = 5 sum to 0, so running_memory neither spikes nor dips.

  4. Aggregate net changes and sort timestamps

    First handle the empty input edge case. Then build a dictionary net_change mapping each timestamp to the net RAM added or freed at that moment, and sort its keys into timestamps.

        # Empty input has no active intervals, so peak usage and window bounds are all 0.
        if not processes:
            return (0, 0, 0)
    
        # net_change maps each event timestamp -> net RAM delta at that exact moment,
        # e.g. {1: +8, 3: +12, 5: 0, 6: -12, 8: -8, 9: +20, 11: -20}.
        # Summing starts (+memory) and ends (-memory) at the same timestamp enforces
        # the half-open [start, end) hand-off rule without fake spikes or momentary dips.
        net_change: Dict[int, int] = {}
        for start, end, memory in processes:
            net_change[start] = net_change.get(start, 0) + memory
            net_change[end] = net_change.get(end, 0) - memory
    
        # Distinct timestamps in ascending order: t_0 < t_1 < ... < t_k.
        timestamps = sorted(net_change.keys())
    

    Notice that a timestamp where starts and ends cancel out (such as net_change[5] == 0) stays in timestamps. That simply splits a flat window into two adjacent pieces with the exact same memory level, which our final step will merge back together.

  5. Sweep across elementary segments

    If timestamps has k distinct points, they divide the active timeline into k - 1 back-to-back elementary intervals:

    timestamps:      t_0       t_1       t_2       t_3
    segments:         [t_0, t_1) [t_1, t_2) [t_2, t_3)
    segment_levels:   level[0]   level[1]   level[2]
    

    Every non-empty input has at least one process with start < end, so len(timestamps) >= 2 and there is at least one segment. We stop the loop at len(timestamps) - 1 because the very last timestamp timestamps[-1] only drops running_memory back down to 0—no active interval begins there.

        # Phase 2: sweep left-to-right across elementary intervals [timestamps[i], timestamps[i + 1]).
        # Memory usage stays completely constant inside each elementary interval because
        # no process starts or ends strictly between two adjacent event timestamps.
        segment_levels: List[int] = []
        running_memory = 0
        # Stop at len(timestamps) - 1 because the final timestamp only closes the last process.
        for i in range(len(timestamps) - 1):
            running_memory += net_change[timestamps[i]]
            segment_levels.append(running_memory)
    
  6. Find the earliest peak and merge flat neighbors

    Once we have segment_levels, finding the answer takes three clean operations:

    1. peak_memory = max(segment_levels) finds the highest simultaneous RAM usage.
    2. first_idx = segment_levels.index(peak_memory) finds the first segment that hits peak_memory, guaranteeing the earliest start time if multiple separate intervals tie for the peak.
    3. Advance last_idx rightward as long as segment_levels[last_idx + 1] == peak_memory. Because segment i ends at timestamps[i + 1] and segment i + 1 immediately starts at timestamps[i + 1], consecutive entries in segment_levels always touch with zero gap! (What if there is a quiet gap where no process runs? During that gap, segment_levels equals 0, and since every process has memory >= 1, peak_memory >= 1, so a 0-memory gap always stops the while loop.)
        # Phase 3: locate the earliest peak segment and merge consecutive peak segments.
        peak_memory = max(segment_levels)
        # .index() returns the first occurrence, selecting the earliest window if disjoint peaks tie.
        first_idx = segment_levels.index(peak_memory)
        last_idx = first_idx
    
        # Adjacent entries in segment_levels share a boundary timestamp (timestamps[i + 1]),
        # so advancing while the level stays at peak_memory merges back-to-back peak segments.
        while last_idx + 1 < len(segment_levels) and segment_levels[last_idx + 1] == peak_memory:
            last_idx += 1
    
        # Segment first_idx starts at timestamps[first_idx]; segment last_idx ends at timestamps[last_idx + 1].
        return (peak_memory, timestamps[first_idx], timestamps[last_idx + 1])
    
  7. Trace through Example 2

    Let's trace processes = [[1, 5, 8], [3, 6, 12], [5, 8, 8], [9, 11, 20]]:

    1. Accumulate net_change:
       [1, 5, 8]   -> net_change[1] = +8,   net_change[5] = -8
       [3, 6, 12]  -> net_change[3] = +12,  net_change[6] = -12
       [5, 8, 8]   -> net_change[5] = -8 + 8 = 0,  net_change[8] = -8
       [9, 11, 20] -> net_change[9] = +20,  net_change[11] = -20
    
    2. Sort timestamps:
       timestamps = [1, 3, 5, 6, 8, 9, 11]
    
    3. Sweep elementary segments:
       i = 0: [1, 3)  -> running_memory = 0 + 8   = 8    segment_levels[0] = 8
       i = 1: [3, 5)  -> running_memory = 8 + 12  = 20   segment_levels[1] = 20  <-- first_idx = 1
       i = 2: [5, 6)  -> running_memory = 20 + 0  = 20   segment_levels[2] = 20  <-- merged! last_idx = 2
       i = 3: [6, 8)  -> running_memory = 20 - 12 = 8    segment_levels[3] = 8   <-- drops below 20, stop
       i = 4: [8, 9)  -> running_memory = 8 - 8   = 0    segment_levels[4] = 0
       i = 5: [9, 11) -> running_memory = 0 + 20  = 20   segment_levels[5] = 20  (ignored: starts later)
    
    4. Read window bounds:
       peak_memory = 20
       peak_start  = timestamps[first_idx]    = timestamps[1] = 3
       peak_end    = timestamps[last_idx + 1] = timestamps[3] = 6
       Result: (20, 3, 6)
    
  8. Complete solution

    Putting all phases together inside find_peak_memory gives the complete solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def find_peak_memory(processes: List[List[int]]) -> Tuple[int, int, int]:
        # Empty input has no active intervals, so peak usage and window bounds are all 0.
        if not processes:
            return (0, 0, 0)
    
        # net_change maps each event timestamp -> net RAM delta at that exact moment,
        # e.g. {1: +8, 3: +12, 5: 0, 6: -12, 8: -8, 9: +20, 11: -20}.
        # Summing starts (+memory) and ends (-memory) at the same timestamp enforces
        # the half-open [start, end) hand-off rule without fake spikes or momentary dips.
        net_change: Dict[int, int] = {}
        for start, end, memory in processes:
            net_change[start] = net_change.get(start, 0) + memory
            net_change[end] = net_change.get(end, 0) - memory
    
        # Distinct timestamps in ascending order: t_0 < t_1 < ... < t_k.
        timestamps = sorted(net_change.keys())
    
        # Phase 2: sweep left-to-right across elementary intervals [timestamps[i], timestamps[i + 1]).
        # Memory usage stays completely constant inside each elementary interval because
        # no process starts or ends strictly between two adjacent event timestamps.
        segment_levels: List[int] = []
        running_memory = 0
        # Stop at len(timestamps) - 1 because the final timestamp only closes the last process.
        for i in range(len(timestamps) - 1):
            running_memory += net_change[timestamps[i]]
            segment_levels.append(running_memory)
    
        # Phase 3: locate the earliest peak segment and merge consecutive peak segments.
        peak_memory = max(segment_levels)
        # .index() returns the first occurrence, selecting the earliest window if disjoint peaks tie.
        first_idx = segment_levels.index(peak_memory)
        last_idx = first_idx
    
        # Adjacent entries in segment_levels share a boundary timestamp (timestamps[i + 1]),
        # so advancing while the level stays at peak_memory merges back-to-back peak segments.
        while last_idx + 1 < len(segment_levels) and segment_levels[last_idx + 1] == peak_memory:
            last_idx += 1
    
        # Segment first_idx starts at timestamps[first_idx]; segment last_idx ends at timestamps[last_idx + 1].
        return (peak_memory, timestamps[first_idx], timestamps[last_idx + 1])
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine tracking how many people are inside an office building throughout the day. You do not need to count heads inside every room once per second; instead, you only need to look at the turnstile log whenever someone enters (+1) or exits (-1), keep a running headcount, and note when that count hits its highest value. Here, each process [start, end, memory] occupies a half-open interval (a time range [start, end) that includes start and excludes end), and we process those boundary changes in chronological order using a sweep-line algorithm (a technique that slides a virtual marker across sorted timestamps while updating a running state).

Checking every integer timestamp fails immediately because timestamps can reach 10^9, requiring up to a billion checks. Even checking only the 2n start and end timestamps by re-scanning all n processes takes O(n^2) work—around 80 billion operations for 200,000 processes. Furthermore, if you sort individual +memory and -memory events as separate items and check the peak after each single event, a simultaneous hand-off at time t will either create a fake spike (if + comes before -) or a fake momentary drop that breaks a continuous peak window in half (if - comes before +).

Grouping all changes at each timestamp into a dictionary fixes both speed and hand-offs cleanly. Consider Example 2 ([[1, 5, 8], [3, 6, 12], [5, 8, 8], [9, 11, 20]]):

net_change:      t=1:+8,  t=3:+12,  t=5:-8+8=0,  t=6:-12,  t=8:-8,  t=9:+20,  t=11:-20
segments:        [1, 3)->8,  [3, 5)->20,  [5, 6)->20,  [6, 8)->8,  [8, 9)->0,  [9, 11)->20
earliest peak:   peak = 20 across [3, 5) + [5, 6) = [3, 6)  -->  (20, 3, 6)

Because -8 and +8 cancel to 0 at t = 5, both [3, 5) and [5, 6) sustain 20, and extending from the earliest peak segment produces (20, 3, 6) ahead of [9, 11).

Complexity

Let n be the number of processes.

  • Time: O(n log n). We iterate through the n processes once with O(1) average-time hash-map updates to build net_change in O(n) time, sort at most 2n distinct timestamps in O(n log n) time, and sweep the O(n) elementary segments twice (once to compute segment_levels and once to find and merge the peak window) in O(n) time.
  • Space: O(n). The net_change dictionary, timestamps list, and segment_levels list each store at most 2n entries.

Edge cases

  • Empty input ([]): Handled first by returning (0, 0, 0) before calling max() on an empty list.
  • Single process ([[3, 8, 7]]): Produces two timestamps [3, 8] and one segment [3, 8) with level 7, returning (7, 3, 8).
  • Touching intervals with different memory ([[1, 3, 5], [3, 6, 7]]): At t = 3, -5 + 7 = +2, so [1, 3) has 5 and [3, 6) has 7—never 12.
  • Back-to-back hand-off at peak ([[1, 5, 8], [3, 6, 12], [5, 8, 8]]): Adjacent segments [3, 5) and [5, 6) both have level 20 and merge into [3, 6).
  • Multiple disjoint peaks ([[0, 10, 1], [6, 8, 5], [2, 4, 5]]): segment_levels.index(peak_memory) stops at the earliest peak [2, 4), ignoring the later [6, 8) window.
  • Idle gaps ([[1, 2, 10], [5, 7, 10]]): Segment [2, 5) is explicitly in segment_levels with value 0; since every process has memory >= 1, peak_memory >= 1 and the 0-level gap prevents [1, 2) and [5, 7) from merging.
  • 64-bit integer sums: Up to 2 * 10^5 processes of 10^9 memory each can reach 2 * 10^14, exceeding 32-bit signed integers (~2.1 * 10^9). Python int has arbitrary precision; in C++ or Java, use long long or long.

Common mistakes

  • Processing individual (time, delta) events without grouping equal timestamps. Putting +memory before -memory at the same timestamp inflates the peak at touching boundaries; putting -memory before +memory creates an artificial dip that prematurely cuts a continuous peak interval in two.
  • Forgetting to merge consecutive segments at the peak level. Returning (peak_memory, timestamps[first_idx], timestamps[first_idx + 1]) fails whenever a zero-net hand-off splits one continuous peak stretch across two elementary segments.
  • Overwriting the earliest peak with a later tied peak. Using >= instead of > when tracking the best window in a single pass returns the latest peak window instead of the earliest one.
  • Assuming the input list is already sorted. Processes can arrive in any order; always sort the unique event timestamps explicitly.

Alternative approaches

  • Sorting (timestamp, delta) pairs directly: Instead of a hash map, build a 2n-element list of (start, +memory) and (end, -memory) tuples, sort it in O(n log n) time, and consume all tuples sharing the same timestamp inside an inner while loop before evaluating the segment. This avoids hash-table overhead while keeping O(n log n) time and O(n) space.
  • Single-pass sweep without segment_levels: Maintain peak_memory, peak_start, peak_end, and an in_peak boolean while sweeping timestamps once. It cuts auxiliary memory slightly by avoiding segment_levels, at the cost of trickier state-transition edge cases.

Follow-up questions

  • How would you maintain the peak usage window over a live telemetry stream when start and stop records can arrive out of chronological order? If events are delayed by at most a bounded window L, buffer incoming events in a min-heap (a priority queue that always pops the smallest timestamp first) and sweep only timestamps older than a watermark (a moving cutoff equal to the newest timestamp seen minus L, before which all events have arrived). If events can arrive arbitrarily out of order across [0, 10^9] and you must query the peak at any moment, store timestamp deltas in a dynamic segment tree (a binary tree built on demand over time intervals where each node summarizes its range). Each tree node stores its total net change plus its maximum and minimum prefix sums (cumulative totals from the start of the range), allowing point updates and global earliest-peak queries in O(log U) time where U = 10^9.
  • Suppose you have hundreds of millions of interval logs stored across a cluster—how would you compute the global peak window in a distributed framework like Spark or MapReduce? In the Map phase, emit (start, +memory) and (end, -memory) for every job, using local map-side aggregation to pre-sum identical timestamps, and Reduce by timestamp to get net deltas. Next, range-partition the timestamps into K ordered intervals [B_k, B_{k+1}); each worker sorts its slice (including boundaries B_k and B_{k+1} with delta 0) and sweeps from 0 to report its net change, local peak, and local peak windows. Finally, a single coordinator computes a prefix sum over the K worker net changes to add each partition's starting memory offset to its local peak, then stitches any global-peak window that reaches a boundary B_{k+1} into partition k + 1.
  • What changes if each task's memory footprint grows linearly from 0 at start to memory at end instead of staying flat? Because a sum of linear functions is still linear, total memory inside each elementary segment [t_i, t_{i+1}) follows M(t) = base_memory + total_slope * (t - t_i) with slope rate = memory / (end - start) per active task. During the sweep, maintain both running_memory and running_slope: at start, add +rate to running_slope; at end, subtract rate from running_slope and subtract memory from running_memory (since the task reached memory right as it ended). Because positive slopes cause memory to climb steadily across each segment rather than stay flat, the supremum on [t_i, t_{i+1}) is approached right before t_{i+1} (running_memory + running_slope * (t_{i+1} - t_i)), so you would report that peak limit and timestamp rather than a flat interval (using exact Fraction arithmetic if exact tie-breaking is needed).

Follow-up questions

Similar questions

More Nutanix interview questions

All 2 Nutanix questions →