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
treleases its RAM at the exact instant another job starting at timetclaims its RAM; the two jobs never overlap att, nor is there an idle gap att. - Contiguous merging: Whenever adjacent time segments sustain
peak_memoryback-to-back with no drop between them, coalesce them into a single[peak_start, peak_end)window. - Earliest tie-breaker: If
peak_memoryis reached during two or more separate windows with lower usage in between, return the window with the smallestpeak_start. - Empty log: When
processescontains 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^50 <= start < end <= 10^91 <= memory <= 10^9- Combined RAM totals can exceed standard 32-bit signed integers.
Step-by-step walkthrough
Understand the goal and the half-open interval rule
Each process is given as
[start, end, memory]and usesmemoryunits of RAM during the half-open interval[start, end). Half-open means the process is active at timetwhenstart <= t < end: it claims memory atstartand releases it right atend.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 atpeak_memorywithout dropping below it.- If
processesis 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 frees8at the exact instant Job B claims8, so total memory stays smoothly at8across[1, 8).Why checking every timestamp is too slow
A literal simulation would loop through every integer second
tfrom the earliest start to the latest end and add up all active processes. Because timestamps can reach10^9, simply looping from0to10^9would 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^5processes, there are up to2n = 4 * 10^5event timestamps, and scanningnprocesses at each timestamp takesO(n^2)steps (up to8 * 10^10checks). That still times out, but it reveals the key insight: total memory never changes between event timestamps.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_memorycounter:- Every process
[start, end, memory]adds+memoryatstartand-memoryatend. - If several processes start or end at the exact same timestamp
t, we combine all of their+and-changes into one net change attbefore reading the new memory level. - Between two sorted adjacent event timestamps
timestamps[i]andtimestamps[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:
-8and+8att = 5sum to0, sorunning_memoryneither spikes nor dips.- Every process
Aggregate net changes and sort timestamps
First handle the empty input edge case. Then build a dictionary
net_changemapping each timestamp to the net RAM added or freed at that moment, and sort its keys intotimestamps.# 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 intimestamps. That simply splits a flat window into two adjacent pieces with the exact same memory level, which our final step will merge back together.Sweep across elementary segments
If
timestampshaskdistinct points, they divide the active timeline intok - 1back-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, solen(timestamps) >= 2and there is at least one segment. We stop the loop atlen(timestamps) - 1because the very last timestamptimestamps[-1]only dropsrunning_memoryback down to0—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)Find the earliest peak and merge flat neighbors
Once we have
segment_levels, finding the answer takes three clean operations:peak_memory = max(segment_levels)finds the highest simultaneous RAM usage.first_idx = segment_levels.index(peak_memory)finds the first segment that hitspeak_memory, guaranteeing the earliest start time if multiple separate intervals tie for the peak.- Advance
last_idxrightward as long assegment_levels[last_idx + 1] == peak_memory. Because segmentiends attimestamps[i + 1]and segmenti + 1immediately starts attimestamps[i + 1], consecutive entries insegment_levelsalways touch with zero gap! (What if there is a quiet gap where no process runs? During that gap,segment_levelsequals0, and since every process hasmemory >= 1,peak_memory >= 1, so a0-memory gap always stops thewhileloop.)
# 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])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)Complete solution
Putting all phases together inside
find_peak_memorygives 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 thenprocesses once withO(1)average-time hash-map updates to buildnet_changeinO(n)time, sort at most2ndistinct timestamps inO(n log n)time, and sweep theO(n)elementary segments twice (once to computesegment_levelsand once to find and merge the peak window) inO(n)time. - Space:
O(n). Thenet_changedictionary,timestampslist, andsegment_levelslist each store at most2nentries.
Edge cases
- Empty input (
[]): Handled first by returning(0, 0, 0)before callingmax()on an empty list. - Single process (
[[3, 8, 7]]): Produces two timestamps[3, 8]and one segment[3, 8)with level7, returning(7, 3, 8). - Touching intervals with different memory (
[[1, 3, 5], [3, 6, 7]]): Att = 3,-5 + 7 = +2, so[1, 3)has5and[3, 6)has7—never12. - 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 level20and 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 insegment_levelswith value0; since every process hasmemory >= 1,peak_memory >= 1and the0-level gap prevents[1, 2)and[5, 7)from merging. - 64-bit integer sums: Up to
2 * 10^5processes of10^9memory each can reach2 * 10^14, exceeding 32-bit signed integers (~2.1 * 10^9). Pythoninthas arbitrary precision; in C++ or Java, uselong longorlong.
Common mistakes
- Processing individual
(time, delta)events without grouping equal timestamps. Putting+memorybefore-memoryat the same timestamp inflates the peak at touching boundaries; putting-memorybefore+memorycreates 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 a2n-element list of(start, +memory)and(end, -memory)tuples, sort it inO(n log n)time, and consume all tuples sharing the same timestamp inside an innerwhileloop before evaluating the segment. This avoids hash-table overhead while keepingO(n log n)time andO(n)space. - Single-pass sweep without
segment_levels: Maintainpeak_memory,peak_start,peak_end, and anin_peakboolean while sweepingtimestampsonce. It cuts auxiliary memory slightly by avoidingsegment_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 minusL, 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 inO(log U)time whereU = 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 intoKordered intervals[B_k, B_{k+1}); each worker sorts its slice (including boundariesB_kandB_{k+1}with delta0) and sweeps from0to report its net change, local peak, and local peak windows. Finally, a single coordinator computes a prefix sum over theKworker net changes to add each partition's starting memory offset to its local peak, then stitches any global-peak window that reaches a boundaryB_{k+1}into partitionk + 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})followsM(t) = base_memory + total_slope * (t - t_i)with sloperate = memory / (end - start)per active task. During the sweep, maintain bothrunning_memoryandrunning_slope: atstart, add+ratetorunning_slope; atend, subtractratefromrunning_slopeand subtractmemoryfromrunning_memory(since the task reachedmemoryright 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 beforet_{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 exactFractionarithmetic if exact tie-breaking is needed).
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?
- 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?
- What changes if each task's memory footprint grows linearly from 0 at start to memory at end instead of staying flat?
Similar questions
- Maximum End-to-End Path Reliability
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One