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 sequence samples onto channel track_id at consecutive clock ticks start_time, start_time + 1, ..., start_time + len(samples) - 1, returning None. Whenever channel track_id already 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 empty samples list leaves all channels unchanged.
  • "get_mixed_output" with [end_time]: Computes and returns a new list of end_time integers covering ticks 0 through end_time - 1 (end_time is exclusive, so end_time == 0 produces []). For each tick t in that window, the output value equals the sum of the latest values stored across every channel at tick t, defaulting to 0 when no channel has recorded a value at t. Values stored at ticks >= end_time are 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 appends None.

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_id is an integer (negative, zero, or positive).
  • start_time and end_time are integers with 0 <= start_time, end_time <= 10^6.
  • samples is a list of integers (elements may be negative, zero, or positive, and samples may be empty).
  • Timeline positions accessed by writes and reads do not exceed 10^6.

Step-by-step walkthrough

  1. Understand the two mixing rules

    An AudioStreamMixer manages several numbered audio channels along a shared discrete clock t = 0, 1, 2, .... Each clip is a list of integer sample amplitudes placed onto one channel starting at start_time.

    Two distinct rules govern how samples combine:

    1. Same channel -> overwrite: writing new samples onto a channel replaces whatever that same channel previously held at those clock ticks.
    2. Different channels -> add: the mixed signal at tick t is the sum of the latest values across all channels at t (treating any channel with no sample at t as 0).

    Look at how get_mixed_output(end_time) slices the timeline in Example 1: get_mixed_output(5) returns 5 values for t = 0, 1, 2, 3, 4, so end_time is exclusive (we stop at end_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: None for "write" and the rendered list for "get_mixed_output".

  2. 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 write assigns buffer[t] = sample, Channel 20 erases Channel 10 instead of summing with it. If write instead does buffer[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 to 10^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 K channels for every t in 0 .. end_time - 1 makes each get_mixed_output(end_time) call cost O(K * end_time) time, re-adding unchanged numbers on every read.
  3. 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 gives O(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, mapping time_step -> sum across all tracks.

    Whenever write places new_sample onto track_id at time_step, how does mixed[time_step] change? If that channel previously held old_sample at time_step (or 0 if unwritten), its contribution changes from old_sample to new_sample while 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_sample and adding new_sample updates the running mix in O(1) average time without touching any other channel.

  4. Implement write with overwrite tracking

    In __init__, self.tracks maps each track_id to its {time_step: sample} dictionary, and self.mixed maps each time_step to the current sum across all channels.

    Inside write, we read old_sample = track_samples.get(time_step, 0) before overwriting track_samples[time_step] = new_sample, then adjust self.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_sample
    

    If samples is empty ([]), the loop runs zero iterations and leaves state untouched.

  5. Implement get_mixed_output and the operation driver

    For get_mixed_output(end_time), we loop time_step over range(end_time) — producing 0, 1, ..., end_time - 1 (and nothing when end_time == 0). Looking up self.mixed.get(time_step, 0) fills unwritten ticks with 0 and leaves any samples at or beyond end_time undisturbed for future calls.

    Allocating a brand-new output list 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 results
    
  6. Trace 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 None for each "write", the complete output is [None, [12, 15], None, None, [12, 7, 7, 15, 0]].

  7. 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, where L = len(samples): we visit each incoming sample once and perform a constant number of O(1) average-time dictionary lookups and assignments.
  • get_mixed_output(end_time) — O(end_time) average time and O(end_time) output space: we step from 0 to end_time - 1 performing one O(1) dictionary lookup per tick, regardless of how many channels exist.
  • Total mixer space — O(W), where W is the number of distinct (track_id, time_step) positions ever written: each written tick is stored once in its channel's dictionary, and mixed holds at most one entry per distinct written tick (<= W entries).

Edge cases

  • end_time == 0 or empty operation list: range(0) performs zero iterations, cleanly returning [].
  • Empty samples list (write(4, 0, [])): the write loop runs zero times, alters nothing, and appends None.
  • end_time smaller than written ticks: samples at or beyond end_time stay stored for future queries, while the current call omits them and fills unwritten earlier ticks with 0.
  • Silent gaps within or between channels: unwritten ticks are absent from mixed and default to 0 via mixed.get(time_step, 0).
  • Overwriting a non-zero sample with 0: old_sample is subtracted and 0 is 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 (5 and -5) sum to 0.
  • Multiple reads interleaved with writes: each get_mixed_output call 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_sample without subtracting old_sample leaves the overwritten sample's amplitude permanently stuck in the mix.
  • Keeping only a single dictionary without per-channel state: assigning mixed[t] = new_sample causes one channel to overwrite another channel's audio instead of summing across channels.
  • Off-by-one error on end_time: iterating with range(end_time + 1) returns end_time + 1 elements instead of end_time elements (0 through end_time - 1).
  • Returning an internal buffer reference: returning a shared list directly causes previously captured outputs to mutate during later write operations.

Alternative approaches

  • Sum across channels at read time (omit mixed): record only tracks[track_id][t] = sample on write, and compute sum(track.get(t, 0) for track in tracks.values()) inside get_mixed_output. Writes stay O(L) with slightly lower memory overhead, which works well when reads are rare, but every read slows to O(K * end_time) across K channels.
  • Chunked fixed-size blocks: partition the timeline into fixed blocks of, say, 4,096 integers 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_output to handle multi-hour recordings without exhausting memory or stalling reads? One hour of 44.1 kHz audio contains 3,600 * 44,100 = 158,760,000 samples per channel, and storing one Python int per 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's array('i') or NumPy int32 arrays using 4 bytes per sample), allocating a page only when written. Writes and mixed updates become fast slice operations on touched pages, and get_mixed_output should 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 to self.mixed[t] = self.mixed.get(t, 0) + new_sample because prior contributions are never erased. Even simpler, if individual channels never need to be queried or cleared separately, self.tracks can be dropped altogether in favor of self.mixed alone. 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 -32768 to 32767 for 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, scanning t from start to end - 1 works for short slices, yet costs O(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 via bisect to locate overlapping intervals in O(log S) time for S segments). You then trim any segment straddling start or end, remove segments completely inside [start, end), and subtract only the actually erased samples from mixed, scaling work with the deleted audio rather than end - start.

Follow-up questions

Similar questions

More Toma interview questions

All 4 Toma questions →