Multi-Track Audio Stream Mixer
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Design a multi-channel waveform combiner (AudioStreamMixer) that records integer amplitude clips onto independent numbered channels aligned to discrete clock ticks 0, 1, 2, ... and renders their combined playback signal.
Implement audio_stream_mixer(operations, arguments) to execute a sequence of commands on a single mixer instance and collect each command's result:
"write"with[track_id, start_time, samples]: Places the sequencesamplesonto channeltrack_idat consecutive clock ticksstart_time, start_time + 1, ..., start_time + len(samples) - 1, returningNone. Whenever channeltrack_idalready holds a value at one of those ticks, the incoming value replaces that channel's previous value at that tick (without affecting other channels). Passing an emptysampleslist leaves all channels unchanged."get_mixed_output"with[end_time]: Computes and returns a new list ofend_timeintegers covering ticks0throughend_time - 1(end_timeis exclusive, soend_time == 0produces[]). For each ticktin that window, the output value equals the sum of the latest values stored across every channel at tickt, defaulting to0when no channel has recorded a value att. Values stored at ticks>= end_timeare omitted from this call's output list but remain saved for later queries, and later"write"calls must not mutate any previously returned list."AudioStreamMixer"with[](if present): Resets the mixer to a clean empty state and appendsNone.
Examples
Example 1
Input:
operations = ["write", "write", "get_mixed_output"]
arguments = [[10, 1, [4, 6, 8]], [20, 0, [3, 2]], [5]]
Output:
[None, None, [3, 6, 6, 8, 0]]
Walk-through:
- Channel 10 writes 4, 6, 8 at ticks 1, 2, 3.
- Channel 20 writes 3, 2 at ticks 0, 1.
- Reading up to end_time = 5 inspects ticks 0..4: tick 0 has 3, tick 1 sums 4 + 2 = 6, tick 2 has 6, tick 3 has 8, and unwritten tick 4 defaults to 0, yielding [3, 6, 6, 8, 0].
Example 2
Input:
operations = ["write", "get_mixed_output", "write", "write", "get_mixed_output"]
arguments = [[4, 0, [12, 15, 9]], [2], [4, 1, [7, 11, 5]], [7, 2, [-4, 10]], [5]]
Output:
[None, [12, 15], None, None, [12, 7, 7, 15, 0]]
Walk-through:
- Channel 4 first stores {0: 12, 1: 15, 2: 9}.
- get_mixed_output(2) reads ticks 0 and 1 only, returning [12, 15].
- Writing [7, 11, 5] to channel 4 at start_time = 1 overwrites ticks 1 and 2 on channel 4 (15 -> 7, 9 -> 11) and writes 5 at tick 3, without altering the [12, 15] list returned earlier.
- Channel 7 writes -4 at tick 2 and 10 at tick 3.
- get_mixed_output(5) sums both channels across ticks 0..4: [12, 7, 11 + (-4), 5 + 10, 0] = [12, 7, 7, 15, 0].
Constraints
track_idis an integer (negative, zero, or positive).start_timeandend_timeare integers with0 <= start_time, end_time <= 10^6.samplesis a list of integers (elements may be negative, zero, or positive, andsamplesmay be empty).- Timeline positions accessed by writes and reads do not exceed
10^6.
Step-by-step walkthrough
Understand the two mixing rules
An
AudioStreamMixermanages several numbered audio channels along a shared discrete clockt = 0, 1, 2, .... Each clip is a list of integer sample amplitudes placed onto one channel starting atstart_time.Two distinct rules govern how samples combine:
- Same channel -> overwrite: writing new samples onto a channel replaces whatever that same channel previously held at those clock ticks.
- Different channels -> add: the mixed signal at tick
tis the sum of the latest values across all channels att(treating any channel with no sample attas0).
Look at how
get_mixed_output(end_time)slices the timeline in Example 1:get_mixed_output(5)returns 5 values fort = 0, 1, 2, 3, 4, soend_timeis exclusive (we stop atend_time - 1):Clock tick t: 0 1 2 3 4 5 Channel 10: . 4 6 8 . . <- write(10, 1, [4, 6, 8]) Channel 20: 3 2 . . . . <- write(20, 0, [3, 2]) -------------------------------------------------- Mixed sum: 3 6 6 8 0 0 |<----- get_mixed_output(5) ---->| returns [3, 6, 6, 8, 0]The driver
audio_stream_mixer(operations, arguments)receives two parallel lists and returns one entry per operation:Nonefor"write"and the rendered list for"get_mixed_output".Why a naive list or read-time scan falls short
Before choosing data structures, check what goes wrong with the obvious ideas:
- One shared array for everything: if
writeassignsbuffer[t] = sample, Channel 20 erases Channel 10 instead of summing with it. Ifwriteinstead doesbuffer[t] += sample, writing twice to Channel 4 adds onto Channel 4's old audio instead of replacing it. We must remember each individual channel's current value. - One zero-padded Python list per channel: timestamps can jump straight to
999,997(up to10^6). Padding every channel's list with hundreds of thousands of zeros wastes time and memory when clips are short and spread far apart. - Summing across all channels on every read: storing each channel separately and looping over all
Kchannels for everytin0 .. end_time - 1makes eachget_mixed_output(end_time)call costO(K * end_time)time, re-adding unchanged numbers on every read.
- One shared array for everything: if
Key idea: sparse per-track dictionaries plus a running mix
A sparse representation stores only the ticks where data was actually written, skipping silent gaps completely. In Python, a dictionary
{time_step: sample}per channel givesO(1)average lookup and update without zero padding.To keep reads independent of the number of channels, we also maintain one running sum dictionary,
mixed, mappingtime_step -> sum across all tracks.Whenever
writeplacesnew_sampleontotrack_idattime_step, how doesmixed[time_step]change? If that channel previously heldold_sampleattime_step(or0if unwritten), its contribution changes fromold_sampletonew_samplewhile every other channel stays untouched:Before overwrite at t = 2: Channel 4 has 9, Channel 7 has -4 --> mixed[2] = 5 Write new_sample = 11 onto Channel 4 at t = 2: old_sample on Channel 4 = 9 mixed[2] = mixed[2] - old_sample + new_sample = 5 - 9 + 11 = 7 (which matches 11 + (-4)!)Subtracting
old_sampleand addingnew_sampleupdates the running mix inO(1)average time without touching any other channel.Implement write with overwrite tracking
In
__init__,self.tracksmaps eachtrack_idto its{time_step: sample}dictionary, andself.mixedmaps eachtime_stepto the current sum across all channels.Inside
write, we readold_sample = track_samples.get(time_step, 0)before overwritingtrack_samples[time_step] = new_sample, then adjustself.mixed[time_step]by- old_sample + new_sample.class AudioStreamMixer: def __init__(self) -> None: # tracks: {track_id: {time_step: sample}}, e.g. {10: {1: 4, 2: 6}}. # Only time positions that were actually written are stored (sparse storage). self.tracks: Dict[int, Dict[int, int]] = {} # mixed: {time_step: sum_across_all_tracks}, e.g. {0: 3, 1: 6}. # Maintained incrementally on every write so reads do not loop over every track. self.mixed: Dict[int, int] = {} def write(self, track_id: int, start_time: int, samples: List[int]) -> None: # Create the per-track dictionary the first time we see this track_id. if track_id not in self.tracks: self.tracks[track_id] = {} track_samples = self.tracks[track_id] # Walk each incoming sample and place it at start_time + offset. for offset, new_sample in enumerate(samples): time_step = start_time + offset # If this track had nothing at time_step yet, its previous contribution was 0. old_sample = track_samples.get(time_step, 0) track_samples[time_step] = new_sample # Overwrite rule within one track, sum rule across tracks: # subtract this track's old contribution and add its new contribution. current_total = self.mixed.get(time_step, 0) self.mixed[time_step] = current_total - old_sample + new_sampleIf
samplesis empty ([]), the loop runs zero iterations and leaves state untouched.Implement get_mixed_output and the operation driver
For
get_mixed_output(end_time), we looptime_stepoverrange(end_time)— producing0, 1, ..., end_time - 1(and nothing whenend_time == 0). Looking upself.mixed.get(time_step, 0)fills unwritten ticks with0and leaves any samples at or beyondend_timeundisturbed for future calls.Allocating a brand-new
outputlist on every read guarantees that later writes never mutate an earlier returned list.def audio_stream_mixer(operations: List[str], arguments: List[List]) -> List: mixer = AudioStreamMixer() results: List[Any] = [] # Replay each operation in order; writes return None and reads return the mixed list. for op, args in zip(operations, arguments): if op == "AudioStreamMixer": mixer = AudioStreamMixer() results.append(None) elif op == "write": track_id, start_time, samples = args mixer.write(track_id, start_time, samples) results.append(None) elif op == "get_mixed_output": end_time = args[0] results.append(mixer.get_mixed_output(end_time)) else: raise ValueError(f"Unknown operation: {op}") return resultsTrace Example 2 step by step
Let us walk through Example 2: 1.
write(4, 0, [12, 15, 9])2.get_mixed_output(2)3.write(4, 1, [7, 11, 5])4.write(7, 2, [-4, 10])5.get_mixed_output(5)1) write(4, 0, [12, 15, 9]) Channel 4: {0: 12, 1: 15, 2: 9} mixed: {0: 12, 1: 15, 2: 9} 2) get_mixed_output(2) <-- reads t = 0, 1 (t=2 stays saved) Output: [12, 15] 3) write(4, 1, [7, 11, 5]) <-- overwrites t=1, t=2 on Channel 4 and adds t=3 t=1: old_sample = 15, new_sample = 7 -> mixed[1] = 15 - 15 + 7 = 7 t=2: old_sample = 9, new_sample = 11 -> mixed[2] = 9 - 9 + 11 = 11 t=3: old_sample = 0, new_sample = 5 -> mixed[3] = 0 - 0 + 5 = 5 Channel 4: {0: 12, 1: 7, 2: 11, 3: 5} mixed: {0: 12, 1: 7, 2: 11, 3: 5} 4) write(7, 2, [-4, 10]) <-- combines Channel 7 with Channel 4 at t=2 and t=3 t=2: old_sample on Channel 7 = 0, new_sample = -4 -> mixed[2] = 11 - 0 + (-4) = 7 t=3: old_sample on Channel 7 = 0, new_sample = 10 -> mixed[3] = 5 - 0 + 10 = 15 Channel 7: {2: -4, 3: 10} mixed: {0: 12, 1: 7, 2: 7, 3: 15} 5) get_mixed_output(5) <-- reads t = 0, 1, 2, 3, 4 t=4 is absent from mixed, so mixed.get(4, 0) -> 0 Output: [12, 7, 7, 15, 0]Including
Nonefor each"write", the complete output is[None, [12, 15], None, None, [12, 7, 7, 15, 0]].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class AudioStreamMixer: def __init__(self) -> None: # tracks: {track_id: {time_step: sample}}, e.g. {10: {1: 4, 2: 6}}. # Only time positions that were actually written are stored (sparse storage). self.tracks: Dict[int, Dict[int, int]] = {} # mixed: {time_step: sum_across_all_tracks}, e.g. {0: 3, 1: 6}. # Maintained incrementally on every write so reads do not loop over every track. self.mixed: Dict[int, int] = {} def write(self, track_id: int, start_time: int, samples: List[int]) -> None: # Create the per-track dictionary the first time we see this track_id. if track_id not in self.tracks: self.tracks[track_id] = {} track_samples = self.tracks[track_id] # Walk each incoming sample and place it at start_time + offset. for offset, new_sample in enumerate(samples): time_step = start_time + offset # If this track had nothing at time_step yet, its previous contribution was 0. old_sample = track_samples.get(time_step, 0) track_samples[time_step] = new_sample # Overwrite rule within one track, sum rule across tracks: # subtract this track's old contribution and add its new contribution. current_total = self.mixed.get(time_step, 0) self.mixed[time_step] = current_total - old_sample + new_sample def get_mixed_output(self, end_time: int) -> List[int]: # Build a fresh list for time steps 0 through end_time - 1 (end_time is exclusive). # Returning a new list ensures later writes never mutate an earlier result. output: List[int] = [] for time_step in range(end_time): # Unwritten time steps default to silence (0). output.append(self.mixed.get(time_step, 0)) return output def audio_stream_mixer(operations: List[str], arguments: List[List]) -> List: mixer = AudioStreamMixer() results: List[Any] = [] # Replay each operation in order; writes return None and reads return the mixed list. for op, args in zip(operations, arguments): if op == "AudioStreamMixer": mixer = AudioStreamMixer() results.append(None) elif op == "write": track_id, start_time, samples = args mixer.write(track_id, start_time, samples) results.append(None) elif op == "get_mixed_output": end_time = args[0] results.append(mixer.get_mixed_output(end_time)) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture a multi-channel recording desk where several separate tape reels run on a synchronized clock. Recording a new take onto Reel 4 tapes over whatever was previously on Reel 4 during those moments, while pressing Play adds the signals from Reel 4, Reel 7, and every other reel together at each tick of the clock.
A naive design either writes everything into one shared array — causing Channel 7 to erase Channel 4 — or pads a dense list with zeros per channel and re-sums all K channels from scratch on every read. Zero-padding wastes memory when short clips land near tick 1,000,000, and re-summing all channels costs O(K * end_time) work on every get_mixed_output call even when nothing changed. Instead, we use a sparse dictionary (a hash map storing only clock ticks where samples were actually written, skipping silent slots) for each channel, plus one running sum dictionary (mixed, a precomputed per-tick total updated incrementally on every write).
Walk through a compact 4-step trace:
1. write(4, 0, [12, 15]): Channel 4 records {0: 12, 1: 15}, and mixed becomes {0: 12, 1: 15}.
2. write(4, 1, [7]): at t = 1, Channel 4 previously held 15, so we update mixed[1] = 15 - 15 + 7 = 7 and replace Channel 4's t = 1 entry with 7.
3. write(7, 1, [6]): at t = 1, Channel 7 previously held 0, so we update mixed[1] = 7 - 0 + 6 = 13 and store 6 on Channel 7.
4. get_mixed_output(3): we look up t = 0, 1, 2 in mixed (defaulting missing keys to 0) and return [12, 13, 0].
Complexity
write(track_id, start_time, samples)—O(L)average time, whereL = len(samples): we visit each incoming sample once and perform a constant number ofO(1)average-time dictionary lookups and assignments.get_mixed_output(end_time)—O(end_time)average time andO(end_time)output space: we step from0toend_time - 1performing oneO(1)dictionary lookup per tick, regardless of how many channels exist.- Total mixer space —
O(W), whereWis the number of distinct(track_id, time_step)positions ever written: each written tick is stored once in its channel's dictionary, andmixedholds at most one entry per distinct written tick (<= Wentries).
Edge cases
end_time == 0or empty operation list:range(0)performs zero iterations, cleanly returning[].- Empty
sampleslist (write(4, 0, [])): the write loop runs zero times, alters nothing, and appendsNone. end_timesmaller than written ticks: samples at or beyondend_timestay stored for future queries, while the current call omits them and fills unwritten earlier ticks with0.- Silent gaps within or between channels: unwritten ticks are absent from
mixedand default to0viamixed.get(time_step, 0). - Overwriting a non-zero sample with
0:old_sampleis subtracted and0is added, silencing that channel's contribution while preserving other channels at that tick. - Negative sample values or negative
track_ids: signed arithmetic and integer dictionary keys behave identically; opposite amplitudes (5and-5) sum to0. - Multiple reads interleaved with writes: each
get_mixed_outputcall allocates a fresh list, so subsequent writes never mutate earlier return values.
Common mistakes
- Adding instead of overwriting on the same channel: updating
mixed[t] += new_samplewithout subtractingold_sampleleaves the overwritten sample's amplitude permanently stuck in the mix. - Keeping only a single dictionary without per-channel state: assigning
mixed[t] = new_samplecauses one channel to overwrite another channel's audio instead of summing across channels. - Off-by-one error on
end_time: iterating withrange(end_time + 1)returnsend_time + 1elements instead ofend_timeelements (0throughend_time - 1). - Returning an internal buffer reference: returning a shared list directly causes previously captured outputs to mutate during later
writeoperations.
Alternative approaches
- Sum across channels at read time (omit
mixed): record onlytracks[track_id][t] = sampleonwrite, and computesum(track.get(t, 0) for track in tracks.values())insideget_mixed_output. Writes stayO(L)with slightly lower memory overhead, which works well when reads are rare, but every read slows toO(K * end_time)acrossKchannels. - Chunked fixed-size blocks: partition the timeline into fixed blocks of, say,
4,096integers and allocate a block only when touched by a write. This preserves sparse memory savings while avoiding per-sample hash table overhead.
Follow-up questions
- How would you redesign storage and
get_mixed_outputto handle multi-hour recordings without exhausting memory or stalling reads? One hour of 44.1 kHz audio contains3,600 * 44,100 = 158,760,000samples per channel, and storing one Pythonintper dictionary entry incurs ~70–100 bytes of object and hash-table overhead (~12+ GB per channel-hour). Instead, partition the timeline into fixed-size pages (such as 4,096 samples per page) backed by packed arrays (contiguous buffers of raw 32-bit integers like Python'sarray('i')or NumPyint32arrays using 4 bytes per sample), allocating a page only when written. Writes andmixedupdates become fast slice operations on touched pages, andget_mixed_outputshould take a[start_time, end_time)window or stream pages via an iterator rather than materializing hours of samples into one giant list. - What simplifies or changes if writing to an existing timestamp on the same track accumulates samples rather than replacing them? Within a channel,
track_samples[t] = track_samples.get(t, 0) + new_sample, and the running mix reduces toself.mixed[t] = self.mixed.get(t, 0) + new_samplebecause prior contributions are never erased. Even simpler, if individual channels never need to be queried or cleared separately,self.trackscan be dropped altogether in favor ofself.mixedalone. In production audio pipelines, accumulating many loud takes can overflow fixed-width sample formats, so output rendering would also apply clamping (bounding values to the legal sample range, such as-32768to32767for signed 16-bit PCM). - Which data structures would you choose to efficiently support erasing a slice via
delete_range(track_id, start, end)? With a per-tick dictionary, scanningtfromstarttoend - 1works for short slices, yet costsO(end - start)even when that channel is mostly silent in that interval. For large sparse ranges, represent each channel as a sorted list of non-overlapping segments(seg_start, samples)and use binary search (repeatedly halving the sorted list viabisectto locate overlapping intervals inO(log S)time forSsegments). You then trim any segment straddlingstartorend, remove segments completely inside[start, end), and subtract only the actually erased samples frommixed, scaling work with the deleted audio rather thanend - start.
Follow-up questions
- How would you redesign storage and `get_mixed_output` to handle multi-hour recordings without exhausting memory or stalling reads?
- What simplifies or changes if writing to an existing timestamp on the same track accumulates samples rather than replacing them?
- Which data structures would you choose to efficiently support erasing a slice via `delete_range(track_id, start, end)`?
Similar questions
- Monte Carlo Pi Estimation
- CSS Channel Color Function
- CSS Color Functions for Alpha Transparency
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses