Walkthrough

Short DSA screens with an infrastructure flavor: idle GPUs, padding, scheduling, cycles

Classic algorithm problems dressed in infrastructure words: idle GPUs, padding uneven arrays, scheduling jobs, finding loops. Name the pattern, ask the one question that changes the algorithm, and test against a brute force.

Researched

Coding Both tracks Senior + Staff 60 min Coding (DSA)Practical coding
On this page

The prompt

If you only remember one thing, say this in the first minute: “This is a classic problem with infrastructure words on it. GPU busy times are merge-intervals. Padding is ‘find the longest row and fill the rest’. Scheduling is a greedy sort. ‘Where does it repeat’ and ‘pod dependency cycles’ are cycle detection. Before I code, I’ll ask the one question that changes the algorithm, say the complexity, and test my answer against a ten-line brute force.”

The rest of this page explains each part of that answer.

What makes these screens different

You already know the algorithms. Merging intervals, sorting greedily and finding a cycle with depth-first search are standard interview material. What is different here is the costume. The problem says “GPU”, “pod” or “batch”, and those words make it feel like a systems question. It isn’t. Under the nouns is a textbook pattern, and the first job is to see it.

A GPU (graphics processing unit) is the expensive chip that AI models run on. For these problems you can treat a GPU as any machine that is either busy or idle at a given minute. Nothing about how GPUs compute matters.

Three things make the round harder than its size suggests:

  1. The nouns hide the pattern. “When is every GPU idle?” is merge-intervals. You lose minutes if you don’t say so early.
  2. One small ambiguity changes the algorithm. Does a GPU busy until minute 10 overlap a job that starts at minute 10? Do you minimize the average finish time or the last finish time? Each question has a different answer, and asking it is most of the signal.
  3. The follow-ups change the model. The last follow-up in the interval problem looks like the one before it, but needs a different algorithm. Strong candidates notice before they code.

These five screens were reported at NVIDIA, Fireworks AI, Anthropic and Together AI. Each report is short and some are second-hand, so treat wordings as approximate (details under “Where these screens were reported” below).

The one problem this page works in full

The five screens share a format (short, classic, infra-themed), not a problem. This page works one of them from start to finish and then applies the same playbook to the other four.

The full one: you have the busy intervals of many GPUs; find when every GPU is idle. Then the interviewer extends it. First, the lists are already sorted and there are many GPUs. Next, find when at least k GPUs are idle. Last, find the earliest time a job can run on k GPUs for d minutes.

The example that runs through this page

Three GPUs, a window from minute 0 to minute 10, and these busy times:

GPUBusy
GPU 0minutes 0–2 and 6–8
GPU 1minutes 2–4 and 7–9
GPU 2minutes 5–7

Here it is as a timeline. Each column is one minute; # is busy and . is idle:

minute  0   1   2   3   4   5   6   7   8   9   10
GPU 0   ########................########........
GPU 1   ........########............########....
GPU 2   ....................########............
all idle                ^^^^                ^^^^

Read it column by column. Every GPU is idle only from 4 to 5 and from 9 to 10. That is the answer to the first question, and every stage below uses this same picture.

What is being tested

Recognizing the pattern under the costume

“GPU busy intervals” is merge-intervals. “Schedule tasks to minimize total completion time” is a greedy sort with a proof by swapping. “Detect where execution repeats” is cycle detection on the states of a small machine. “Break cycles in pod dependencies” is cycle detection on a graph. One NVIDIA candidate’s lesson was to recognize the pattern and get to correct code fast (Acedfirst-hand · 2025).

Say it like this: “Under the GPU words, this is merge-intervals. I’ll sort, sweep once, and report the gaps.”

Pinning down the model with one question

Each problem has one ambiguity that changes the algorithm:

  • Intervals: does a busy period that ends at 10 touch one that starts at 10?
  • Scheduling: do we want the smallest total of finish times, or the earliest time the last task finishes? The second is called the makespan.
  • Simulation: what counts as the “state” that repeats: only the current instruction, or the registers too?
  • Cycles: when you break a cycle, which dependency may you remove, and what does removing it cost?

Asking that one question, out loud, before code, is most of what separates a strong answer from a lucky one.

Code that is aware of performance

The same NVIDIA candidate says interviewers cared about code that was “well written, performance-aware” and preferred building pieces from scratch (Acedfirst-hand · 2025). In practice that means: state the big-O complexity as you go, avoid needless copies, and use the vectorized path (whole-array operations in a library such as NumPy) when the problem is about arrays.

Why companies still ask these

interviewing.io reports “Of the 52 respondents from FAANG, ZERO said that their company has moved away from algorithmic questions” (interviewing.iosecondary · 8 Oct 2025). Companies that lean toward infrastructure keep a short classic screen even when their onsite rounds are practical.

AI tools in the round

No policy is reported for NVIDIA, Fireworks or Together AI as of 2026-10-11. Anthropic’s is no AI in live interviews unless told otherwise (Anthropicofficial · 10 Jul 2025). Ask the recruiter, and practise without an assistant.

Where these screens were reported

  • Fireworks. A DesignGurus prep page on Fireworks’ process says “Reported problems include finding the global idle intervals across many GPUs”, and that candidates describe “live coding at medium difficulty” (DesignGurussecondary). It is a secondary page with no date on the question; treat it as one report.
  • NVIDIA (Senior). One candidate’s onsite had a padding round (“a straightforward implementation problem”) and a scheduling round they approached “like a standard LeetCode scheduling problem”, focused on “getting to a correct implementation quickly”. They called the onsite coding “more speed-driven” than the screen, which was an LRU cache with multithreading follow-ups (Acedfirst-hand · 2025).
  • Anthropic (Sr Staff). A Blind poster’s coding round was to “simulate a list of instructions and detect where execution starts repeating”: “I had a few bugs early on but finished around the 50-minute mark” (Blindfirst-hand). The poster blames a different round for the outcome.
  • Together AI. PracHub lists a Software Engineer question titled “Detect cycles and break them in pod dependencies”, dated Feb 12, 2026 (PracHubaggregator · 2026). Only the title is reported.

Clarify and scope

For the idle-interval problem, ask these five things. Each one has a default you can propose if the interviewer says “your call”.

  1. Do touching intervals overlap? Propose half-open intervals, written [start, end): the start minute is included and the end minute is not. Then a GPU busy until 10 and another busy from 10 leave no gap at 10. In our example, GPU 0’s [0, 2) and GPU 1’s [2, 4) join into one busy stretch [0, 4). Closed intervals would change every comparison in the code.
  2. Idle within which window? Before the first job and after the last, a GPU is idle forever, so the answer needs a bound. Call it [lo, hi). In our example it is [0, 10).
  3. What does the input look like? One list per GPU, or one flat list? Already sorted? How many GPUs and intervals in total? Assume up to about a million intervals.
  4. Can one GPU’s own intervals overlap? That would mean two jobs share one GPU. Merging handles it either way, but the “at least k” stage counts busy intervals per GPU, so ask.
  5. What should come out? A sorted list of (start, end) pairs that don’t touch each other. For our example: [(4, 5), (9, 10)].

Out of scope: time zones, recurring reservations and live updates. Mention live updates as the follow-up you expect.

Say it like this: “I’ll use half-open intervals, so a job ending at 10 and one starting at 10 leave no gap. I’ll answer inside a window [lo, hi), because outside all jobs the GPUs are idle forever.”

Plan before code

Say the pattern, the complexity and the test plan in one breath, then write:

“Union of all busy intervals, then the gaps inside the window are the idle times. Sort all N intervals, O(N log N), merge in one pass. I’ll test it against a brute force that checks every integer time.”

A brute force here means the slowest, most obviously correct version: for every whole minute in the window, check every interval. It is too slow for a million intervals but perfect for checking small random cases. When you use it to check the real solution, it is called an oracle.

Pacing for a 45–60-minute screen

Round lengths aren’t stated in these reports, so this assumes 60 minutes; compress for 45.

MinutesWhatDone when
0–5Clarify the one ambiguity; say pattern and complexitythe interviewer agrees with the model
5–20Core solution + 2 hand-written testsgreen
20–30Brute-force oracle + random testgreen on a few thousand cases
30–50Follow-ups (stages 2–4)each with a test
50–60Complexity, edge cases you’d addsaid before being asked

The brute-force step looks like a luxury in a short screen. It isn’t. For interval and graph problems, the off-by-one bugs are exactly what a ten-line brute force catches, and writing it takes five minutes.

Solution in stages

All code is Python 3.13. The stages and every sketch below passed their tests, including random comparisons against brute force, when run on 2026-10-12. The example outputs quoted for our three GPUs were also produced by running this code on 2026-10-12.

Stage 1: when is every GPU idle?

The idea: every GPU is idle exactly when no GPU is busy. So take the union of all busy intervals (glue together everything that overlaps or touches) and report the gaps inside the window.

def all_idle(busy_by_gpu, lo, hi):
    spans = sorted(iv for gpu in busy_by_gpu for iv in gpu)
    idle, cursor = [], lo
    for s, e in spans:
        if s > cursor:
            idle.append((cursor, min(s, hi)))
        cursor = max(cursor, e)
        if cursor >= hi:
            break
    if cursor < hi:
        idle.append((cursor, hi))
    return [(s, e) for s, e in idle if s < e]

cursor is the end of the busy union so far. A start beyond it opens a gap. The comparison is s > cursor, not >=: that is the half-open rule, so touching intervals leave no gap.

Follow our example through it. Sorted, the spans are (0,2) (2,4) (5,7) (6,8) (7,9):

SpanCursor beforeWhat happensCursor after
(0, 2)0starts at the cursor, no gap2
(2, 4)2touches, no gap (half-open)4
(5, 7)4starts after the cursor: gap (4, 5)7
(6, 8)7overlaps8
(7, 9)8overlaps9
end9cursor is before hi = 10: gap (9, 10)—

Result: [(4, 5), (9, 10)], which matches the timeline.

Stage 2: lists already sorted, many GPUs

Sorting all N intervals ignores a gift: each GPU’s list is already in order. A k-way merge combines k sorted lists into one sorted stream by keeping the next item of each list in a heap (a priority queue that always hands back the smallest item). With G GPUs, it yields intervals in start order in O(N log G) time with O(G) extra memory. It also streams: it reads one interval at a time, so it works when the lists don’t fit in memory.

import heapq

def all_idle_merged(busy_by_gpu, lo, hi):
    merged = heapq.merge(*busy_by_gpu)          # lazily yields intervals in start order
    idle, cursor = [], lo
    for s, e in merged:
        if s >= hi:
            break
        if s > cursor:
            idle.append((cursor, s))
        cursor = max(cursor, e)
    if cursor < hi:
        idle.append((cursor, hi))
    return idle

On our example it returns the same [(4, 5), (9, 10)]. Say it like this: “With G sorted lists I don’t need to re-sort; a heap merge costs N log G instead of N log N and uses memory for G items, not N.”

Stage 3: at least k GPUs idle

A union can’t answer this, because it throws away how many GPUs are busy. You need a count over time. The standard tool is a sweep line: turn every interval into two events, +1 when a job starts and −1 when it ends, sort the events by time, and walk them in order while keeping a running count of busy GPUs.

Sorting the tuples (t, -1) before (t, +1) processes ends before starts at the same instant. That is the half-open rule again.

def at_least_k_idle(busy_by_gpu, lo, hi, k):
    g = len(busy_by_gpu)
    events = sorted([(s, +1) for gpu in busy_by_gpu for s, _ in gpu] +
                    [(e, -1) for gpu in busy_by_gpu for _, e in gpu])
    out, busy, prev = [], 0, lo
    for t, d in events + [(hi, 0)]:
        t = min(max(t, lo), hi)
        if t > prev and g - busy >= k:
            if out and out[-1][1] == prev:
                out[-1] = (out[-1][0], t)        # glue touching pieces
            else:
                out.append((prev, t))
        prev = max(prev, t)
        busy += d
    return out

This counts busy intervals, so it assumes one GPU’s own intervals don’t overlap (clarifying question 4). If they can, merge each GPU’s list first.

On our example, with k = 2 the answer is [(0, 6), (8, 10)]: from minute 0 to 6, at least two of the three GPUs are idle at every moment. With k = 3 it falls back to stage 1’s [(4, 5), (9, 10)], which is a useful sanity check to say out loud.

Stage 4: the earliest slot for a job on k GPUs for d minutes

This is the follow-up that catches people. Take a job that needs 2 GPUs for 3 minutes. Stage 3 just said that 2 GPUs are idle at every moment of [0, 6), so it is tempting to answer “start at minute 0”.

That is wrong. A job needs the same k GPUs for its whole duration. Look at the timeline again. From 0 to 2, GPU 0 is busy and GPUs 1 and 2 are free. From 2 to 4, GPU 1 is busy and GPUs 0 and 2 are free. Two GPUs are always idle, but no single pair stays idle for all of [0, 3). (The smallest version of this counterexample is three GPUs where GPU 0 is busy on [0, 2) and GPU 1 on [2, 4): two GPUs are idle at every moment of [0, 4), yet no pair is idle for all of it.)

The fix rests on one observation. An optimal start is either the window start or the moment some job ends. If a start works, sliding it earlier keeps it working until it hits one of those moments. So try those candidate times in order. At each candidate t, count the GPUs whose own busy list has nothing overlapping [t, t + d), which a binary search in that GPU’s sorted list answers.

import bisect

def earliest_start(busy_by_gpu, k, d, lo=0):
    def free_at(gpu, t):                         # is this GPU idle for all of [t, t+d)?
        i = bisect.bisect_right(gpu, (t, float("inf")))   # first interval starting after t
        if i and gpu[i - 1][1] > t:                        # one that started at or before t
            return False
        return i == len(gpu) or gpu[i][0] >= t + d

    sorted_gpus = [sorted(gpu) for gpu in busy_by_gpu]
    candidates = sorted({lo} | {e for gpu in sorted_gpus for _, e in gpu if e > lo})
    for t in candidates:                         # an optimal start is lo or some busy end
        chosen = [i for i, gpu in enumerate(sorted_gpus) if free_at(gpu, t)]
        if len(chosen) >= k:
            return t, chosen[:k]
    return None

Our example, k = 2 and d = 3: the candidates are 0, 2, 4, 7, 8 and 9. At minute 0 only GPU 2 is free for [0, 3). At minute 2, GPU 0 is free until 6 and GPU 2 until 5, so the answer is start at minute 2 on GPUs 0 and 2. The function returns (2, [0, 2]).

The free_at check relies on each GPU’s intervals not overlapping each other; with overlaps, merge first. Cost: C candidates × G GPUs × log n, at most O(N × G log n). Say that, and say the next step if it is too slow: sweep the candidates in order and keep each GPU’s next busy start up to date as you go, instead of searching again.

Say it like this: “‘k idle at every moment’ isn’t enough. The job needs the same k GPUs throughout. Here is a three-GPU counterexample, so I’ll search candidate start times instead.”

The same playbook on the other four screens

Each card has the full sketch, a worked example and tests. Here is the pattern and the one question to ask. The terms in the table are explained in the four short sections right after it. In the cost column, n is the number of rows or tasks, L the longest row, V the number of nodes and E the number of edges.

ScreenPatternAsk firstCore cost
Pad ragged arrays (infra-095)max length, fill, maskright or left padding? return a mask? pad to a multiple of 8?O(n × L) output
Schedule on limited resources (infra-096)greedy: shortest job firsttotal completion time, or makespan? dependencies?O(n log n)
Simulate until it repeats (infra-101)cycle detection on stateswhat is the state: just the program counter, or registers too?O(steps) time and memory
Detect and break pod cycles (infra-102)three-state DFS; remove an edge per cyclewhich edge may break, and what does it cost?O((V + E) × cycles)

Padding ragged arrays

A ragged list is a list of rows with different lengths. Models need a rectangle, so you pad: find the longest row, fill the shorter rows with a filler value, and return a mask, a same-shaped grid of true/false that says which cells are real. Here is the vectorized version, because the NVIDIA candidate says interviewers wanted “performance-aware” code:

import numpy as np

def pad_numpy(rows, fill=0):
    lengths = np.fromiter((len(r) for r in rows), dtype=np.int64, count=len(rows))
    width = int(lengths.max()) if len(rows) else 0
    mask = np.arange(width) < lengths[:, None]          # (n, width) via broadcasting
    out = np.full((len(rows), width), fill, dtype=np.int64)
    if width:                                           # nothing to copy for [] or all-empty rows
        out[mask] = np.concatenate([np.asarray(r, dtype=np.int64) for r in rows])
    return out, mask

Boolean-mask assignment fills row by row in order, which is why concatenate lines up with the mask.

Scheduling jobs on machines

If the goal is the smallest sum of completion times on m identical machines with no dependencies, run the shortest job first (called SPT, shortest processing time), each on the machine that frees up first. That is optimal. The proof is an exchange argument: if a longer job runs just before a shorter one, swapping them lowers the sum, so only sorted order can’t be improved. In tests run for this page on 2026-10-12, SPT matched a brute force over every assignment on 300 random instances (up to 6 jobs, 3 machines). If the goal is makespan (when the last job finishes), the problem is NP-hard: no known algorithm solves every case quickly. Say so and offer longest-job-first as a heuristic.

def spt_schedule(durations, m):
    free = [(0, i) for i in range(m)]
    total, plan = 0, []
    for job, d in sorted(enumerate(durations), key=lambda x: x[1]):
        t, machine = heapq.heappop(free)
        total += t + d
        plan.append((job, machine, t, t + d))
        heapq.heappush(free, (t + d, machine))
    return total, plan

Simulating until execution repeats

You write a tiny interpreter: a list of instructions, a program counter (pc, the index of the next instruction) and some registers (named variables, here one called acc). Hash the full state, not just the program counter. If the accumulator changes on each lap, the same program counter does not mean a repeat.

def run_until_repeat(program, regs=None, max_steps=1_000_000):
    pc, regs, seen = 0, dict(regs or {"acc": 0}), {}
    for step in range(max_steps):
        if not 0 <= pc < len(program):
            return ("halt", step, regs)
        state = (pc, tuple(sorted(regs.items())))
        if state in seen:
            return ("loop", seen[state], step - seen[state])   # loop start, loop length
        seen[state] = step
        op, arg = program[pc]
        if op == "add":
            regs["acc"] += arg
        elif op == "jmp":
            pc += arg
            continue
        elif op == "jnz":
            if regs["acc"]:
                pc += arg
                continue
        pc += 1
    raise RuntimeError("step budget exhausted without a repeat")

Detecting and breaking dependency cycles

A three-state DFS is depth-first search that colours each node white (not visited), grey (on the current path) or black (finished). Reaching a grey node again closes a cycle. Using only two states (visited or not) wrongly calls a diamond, where two paths lead to the same node, a cycle. Detect a cycle this way, remove the cheapest edge on it, and repeat. Removing the fewest edges overall (called the minimum feedback arc set) is NP-hard, so say the greedy result has no cycles but is not guaranteed minimal, and ask what “cost” means for a pod dependency. The code and a worked example are on the infra-102 card.

What to say out loud on each

The code for these screens is short, so the spoken part carries more of the signal than in a long practical round. A sentence or two per screen, in the order you would say it:

Padding. “The output is n by the longest row, so memory is n times L whatever I do; the cost to watch is one long row making every row pay for it. I’ll return a mask with the matrix, because whoever consumes this (an attention kernel, a loss) needs to know which cells are real.” An attention kernel is the GPU code at the heart of a language model, and a loss is the score used during training; both must skip padding. Then ask about left versus right padding. Text-generating models (called decoder-only models) write new words at the end of each row, so for generation they are usually padded on the left, which lines up the newest word at the end of every row. An infra interviewer at a GPU company may probe that detail.

Scheduling. “Before I write anything: total completion time or the time the last task finishes? They are different problems.” If it is total completion time, give the exchange argument in one breath: any schedule that runs a longer task before a shorter one on the same machine can swap them and lower the sum, so sorted order is optimal on one machine, and handing the next-shortest task to whichever machine frees up first extends that to m machines. If there are dependencies between tasks, say that list scheduling over a topological order (an order where every task comes after the tasks it depends on) is a heuristic, not an optimum, and ask how large the inputs are.

Simulation. “A deterministic machine with finite state must either halt or revisit a state, and the first revisited state is where the loop starts. So the state I hash has to be everything the next step depends on.” Then say what happens if a register is unbounded: the state space is infinite, the program may run forever without repeating, and the step budget is what stops you. The Anthropic poster’s report is that the round was finishable in about 50 minutes with early bugs (Blindfirst-hand), so leave time for those bugs.

Dependency cycles. “Detecting a cycle is linear. Breaking all cycles with the fewest removed edges is NP-hard, so I’ll do it greedily and tell you what that costs.” Then ask whether some dependencies are soft. In a pod or job graph the useful output is usually not a repaired graph but a report: the cycle, in order, so a human can decide which dependency was a mistake. Kahn’s algorithm (repeatedly remove nodes that nothing points to) gives a cheap second answer: the nodes left with nonzero in-degree are on a cycle or downstream of one.

Verification

Every one of these problems has a brute force that fits in ten lines. For the interval stages it is “check every integer time”: for minute t, a GPU is idle if no interval contains t. Then compare the fast answer with the brute force on thousands of small random inputs. This is called randomized testing against an oracle.

def brute_idle_count(busy, t):
    return sum(not any(s <= t < e for s, e in gpu) for gpu in busy)

def test_random_against_brute_force():
    rng = random.Random(3)
    for _ in range(3000):
        busy = random_gpus(rng)                      # 1-4 GPUs, integer intervals on [0, 25)
        lo, hi = rng.randint(0, 3), 20
        expect = runs([brute_idle_count(busy, t) == len(busy) for t in range(lo, hi)], lo)
        assert all_idle(busy, lo, hi) == expect
        assert all_idle_merged(busy, lo, hi) == expect
        k = rng.randint(1, len(busy))
        assert at_least_k_idle(busy, lo, hi, k) == runs(
            [brute_idle_count(busy, t) >= k for t in range(lo, hi)], lo)
        d = rng.randint(1, 4)
        want = next((t for t in range(0, 60) if sum(
            all(not (s < t + d and t < e) for s, e in gpu) for gpu in busy) >= k), None)
        got = earliest_start(busy, k, d)
        assert (got[0] if got else None) == want

runs turns a list of booleans into (start, end) pairs, and random_gpus builds 1–4 GPUs with random integer intervals. Notice that the stage 4 brute force checks the same GPUs for the whole job: a GPU counts only if none of its intervals overlaps [t, t + d).

Hand-written cases to add:

  • an empty GPU list;
  • an interval entirely outside the window;
  • touching intervals, like [0, 2) and [2, 4) in our example;
  • the “same k GPUs” counterexample above.

While this page was being written, the first draft of that counterexample test had a wrong expected value; the brute force is what showed that the test, not the code, was wrong.

Say it like this: “I’ll trust the fast version once it agrees with the slow obvious version on a few thousand random cases.”

Complexity and performance

StageTimeExtra memory
1O(N log N) to sort, O(N) to mergeO(N)
2O(N log G)O(G)
3O(N log N)O(N)
4O(C × G × log n), C ≤ N + 1 candidatesO(N)

N is the total number of intervals, G the number of GPUs, and n the longest per-GPU list. C is the number of candidate start times: the window start plus every interval end, so at most N + 1.

What these numbers mean in practice: for large N, stage 1’s time is almost all sorting. So the k-way merge (when the lists are already sorted) or a vectorized sort matters more than tidying the loop. Stage 4 is the only one that multiplies by G. With thousands of GPUs, that is where the “keep each GPU’s next busy start up to date” improvement pays off.

Small-team version

These are screening puzzles. Few companies of 50–500 people will ask you to write them at work. But three of the patterns do show up in AI infrastructure that a small team runs: padding in batch embedding, cycle checks in job graphs, and idle-time checks on GPUs.

Padding is a real cost in batch embedding

An embedding is a list of numbers that represents a piece of text, used for search. A tokenizer first splits each text into tokens (roughly ¾ of a word each). When you embed documents in batches on your own GPU or CPU, every text in a batch is padded to the longest one. The padded cells still cost compute. The wasted fraction is

Padding waste in one batch
waste = 1 − Σ len_i ÷ (n × max_i len_i)
len_i
token length of text i in the batch
n
texts in the batch
Worked example

Assumed batch: 31 texts of 46 tokens and one of 256. Waste = 1 − (31 × 46 + 256) ÷ (32 × 256) = 1 − 1,682 ÷ 8,192 ≈ 79%.

So one long text in a batch of short ones can waste about 79% of the work. Sorting texts by length before batching removes most of it. Check whether your library already does: the sentence-transformers version in this site’s lab environment (6.1.0) sorts inputs by length inside encode before batching, which was verified by reading its source on 2026-10-12. If you call a hosted embedding API, this is the provider’s problem, and you pay per input token, not per padded token.

In money, with assumed numbers: a self-hosted backfill that takes 10 GPU-hours with sorted batches takes about 49 unsorted, so about $98 instead of $20. The hosted default is cheaper still at small scale: embedding 1M chunks of 500 tokens costs about $10. Self-host only when volume, data residency or a model the API doesn’t offer makes that $10 the wrong comparison.

The arithmetic behind the numbers (for a Staff-level follow-up)
  • Waste: the batch pads 32 × 256 = 8,192 slots for 31 × 46 + 256 = 1,682 real tokens, so 1 − 1,682 ÷ 8,192 ≈ 79% is padding. The padded batch does 8,192 ÷ 1,682 ≈ 4.9× the needed work.
  • Self-hosted cost: assume time scales with padded tokens. 10 GPU-hours sorted × 4.9 ≈ 49 GPU-hours unsorted. At an assumed $2 per GPU-hour, that is about $98 against $20.
  • Hosted cost: 1M chunks × 500 tokens = 500M tokens. With text-embedding-3-small at $0.02 per million tokens (list price on OpenAI’s pricing page, fetched 2026-10-11), 500 × $0.02 = $10.

Cycles and intervals: use the engine you already have

  • Build: almost nothing. A validation step that rejects a job graph with a cycle before it runs (a three-state DFS, as in the cicd-engine lab) and a check that a reservation window is free.
  • Buy or borrow: the workflow engine (your CI system, a managed scheduler, or an open-source DAG runner) that already detects cycles and orders tasks. A DAG (directed acyclic graph) is a dependency graph with no cycles. Writing your own DAG runner is the classic small-team overbuild.
  • Skip: a custom GPU reservation system. With a handful of GPUs, a shared calendar or your cluster scheduler’s quotas is enough. The “same k GPUs for d minutes” stage is a real problem only when you schedule multi-GPU jobs often, which is the planned GPU-scheduler lab’s territory.

Revisit when you run enough self-hosted batch jobs that GPUs sit idle between them. Then the interval problem becomes a utilization report you actually need.

How to practise

Five patterns cover this family:

  • merge and sweep intervals;
  • greedy with an exchange argument;
  • k-way merge with a heap;
  • cycle detection, on graphs and on state machines;
  • padding with masks.

For each, do one timed 30-minute rep, writing the brute force and random test every time. Ten reps across a week is a better use of time than a long problem list, because these screens are a small part of the loops they appear in.

Senior vs Staff

Short screens

Senior

  • Recognizes the pattern, asks the one modelling question, and gets correct code with tests quickly.
  • States complexity and handles the boundary convention consistently.

Staff

  • Spots when a follow-up changes the model (k idle GPUs at every moment versus the same k GPUs for d minutes) and says so before coding.
  • Says which variants are NP-hard (makespan, minimum edges to break all cycles) and offers a defensible heuristic with its limits.

At Staff the screen is short, so the difference shows in judgment: the counterexample you raise, the objective you pin down, and the brute force you write without being asked.

Follow-ups

Not reported; a natural next push (Fireworks idle intervals): busy intervals now arrive as a live stream.

Keep each GPU’s intervals in a sorted structure, and keep the changes in the global busy count in a balanced tree keyed by time; answering “idle now?” is then a counter. In Python, a sorted list with bisect is fine for the interview.

Not reported; a natural next push (NVIDIA scheduling): the objective is makespan, not total completion time.

Say it is NP-hard for two or more machines, offer longest-processing-time first onto the least-loaded machine, and offer an exact search only for small n.

Reported title (Together AI, PracHub): detect cycles and break them. Which edge do you remove?

The title doesn’t say (PracHubaggregator · 2026). Ask for a cost per edge (an optional dependency, a soft ordering). Remove the cheapest edge on each detected cycle and re-run, and say the result has no cycles but is not guaranteed minimal.

Not reported; a natural next push (Anthropic simulation): the state space is too large to store every state.

Use Floyd’s or Brent’s cycle detection. Both walk the sequence of states with two pointers moving at different speeds, so they need O(1) memory, at the cost of re-running the simulation. That is fine when a step is deterministic and cheap. Brent’s finds the loop length directly.

Not reported; a natural next push (NVIDIA padding): the arrays are ragged in two dimensions.

Compute the max along each axis, allocate once, and copy each block into its corner; return a mask with the same shape. Ask whether truncation to a maximum length is allowed, which bounds memory.

Not reported; a natural next push (Fireworks idle intervals): return which GPUs are idle in each window, not just when.

Carry a set of busy GPU ids through the sweep instead of a counter: add the id on a start event, remove it on an end event, and emit the complement whenever the set changes. The output grows to O(N × G) in the worst case, so ask whether the caller needs every window or only the first one that fits a job, which is stage 4 again.

Common mistakes

  • Mixing interval conventions. Using < in one comparison and <= in another makes touching intervals behave differently in different places; pick half-open and say it.
  • Answering “k idle at every moment” when the job needs the same k GPUs. The counterexample is three GPUs and two intervals, and our example’s naive answer (minute 0) is wrong for the same reason.
  • Optimizing the wrong objective. Total completion time and makespan have different algorithms and different hardness.
  • Hashing only the program counter. A loop that changes a register then looks like a repeat when it isn’t.
  • Recursive DFS on a large graph in Python. The default recursion limit is about a thousand frames, so a long chain crashes; use an explicit stack.
  • Spending the whole screen on stage 1. The NVIDIA candidate called the onsite coding “more speed-driven” than the screen (Acedfirst-hand · 2025). A correct sort-and-merge in fifteen minutes leaves room for the follow-up where the real signal is; a polished one in forty does not.
  • Skipping the brute force. For these problems it is the cheapest correctness argument you can make.

Prove it with a lab

Build Your Own CI/CD EngineProves itProof labgo

dag.go has ValidateDAG (three-state DFS that reports a cycle) and TopoSort (Kahn's algorithm, which also errors when a cycle leaves nodes unsorted). Extend it to return the cycle's stages and to remove the cheapest edge, and you have answered the Together AI screen in Go.

Build Your Own Embedding PipelineBackgroundProof labpython

Batched encoding of texts of different lengths. Its measured rows show how much batching per call buys; sort a mixed-length workload by length first and watch padding stop eating that gain.

Questions in this family

5 reported questions share this underlying problem. 5 have an answer card. Each one links to its own page with sources and confidence.

Sources