Tag: Algo

  • MSD0069 GPU Scheduling Platform

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • CD0063 Merge Accounts Union-Find

    Mode B · Build & Trace 30 Min Pure Python 3 4 Code Blanks

    ByteDance’s account-integrity team works on a deceptively simple question: which user records belong to the same human? This coding screen (reported by candidates who interviewed with the team) distills it into a classic merge task. You receive accounts, a list where each entry is [name, email_1, email_2, ...]. Two accounts belong to the same person if they share at least one email address, either directly or through a chain of other accounts. Return one row per person: the name followed by that person’s unique emails in sorted order.

    The solution must be union-find over email ownership in pure Python, with no imports beyond typing. The interviewer probes three input shapes. The first is a chain, where account A shares an email with B and B shares one with C, but A and C share nothing directly. The second is two people with the same display name who must not be merged. The third is an email repeated inside one account. You also have to argue why path compression plus union by rank makes each operation near-constant amortized, and the code must handle a 10^5-account chain comfortably.

    Fill the 4 blanks in the skeleton below. Then trace the parent and rank arrays aloud on a small chain, and give the total running time in terms of N accounts and E email occurrences.

    Skeleton Code (Fill Blanks 1-4):

    01  from typing import Dict, List
    02
    03
    04  class DisjointSet:
    05      """Union-find over account indices 0 .. n-1."""
    06
    07      def __init__(self, n: int):
    08          self.parent = list(range(n))   # each account starts as its own root
    09          self.rank = [0] * n            # upper bound on each root's tree height
    10
    11      def find(self, x: int) -> int:
    12          # TODO (Blank 2): return the root of x; afterwards every node
    13          #                 visited on the way must point directly at it
    14          ...
    15
    16      def union(self, a: int, b: int) -> bool:
    17          # TODO (Blank 3): link the roots of a and b by rank; return True
    18          #                 on a merge, False if already in one set
    19          ...
    20
    21
    22  def merge_accounts(accounts: List[List[str]]) -> List[List[str]]:
    23      """Merge accounts that share at least one email address.
    24
    25      accounts[i] = [name, email_1, email_2, ...]. Two accounts belong to
    26      the same person iff a chain of shared emails connects them; an equal
    27      name alone never justifies a merge. Returns one row per person:
    28      [name] + that person's unique emails in sorted order.
    29      """
    30      dsu = DisjointSet(len(accounts))
    31      email_owner: Dict[str, int] = {}   # email -> first account index that listed it
    32
    33      for account_id, account in enumerate(accounts):
    34          for email in account[1:]:
    35              # TODO (Blank 1): register the first owner of each email;
    36              #                 connect accounts only through a shared email
    37              ...
    38
    39      # TODO (Blank 4): group every email under its account's root, then
    40      #                 emit [name] + sorted unique emails per group
    41      merged = ...
    42      return merged
    Problem contract for merge_accounts: an input box listing four sample accounts all named Ana flows into a question-marked merge_accounts box covering Blanks 1 to 4, then into an output contract box requiring one row per person with the name plus sorted unique emails; a bottom row lists the four input shapes the hidden checks probe: a chain, a shared display name, a repeated email inside one account, and a 1e5-account chain

    Figure 1: The input and output contract plus the four input shapes the hidden checks probe. The question-marked box is the whole exercise.

    Interactive Python Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the hidden behavioral checks.

    Open in Colab ↗
    Progressive Hints (Free · Zero Spoilers)
    1Inspection Checklist (Where to Look)

    (1) Ownership Key: Blank 1’s dictionary is the only place where accounts get linked. Decide what its key is, when an entry is created, and when an existing entry is reused.
    (2) Root Contract: find(x) returns an index whose parent is itself. Decide what state the nodes you walked through should be left in.
    (3) Link Direction: union receives two account indices that may sit deep inside their trees. Decide which nodes get rewired and which root survives.
    (4) Grouping Key: Blank 4 needs a key that is identical for every account of one person at the moment you group, and each email must appear only once per row.

    2Visual Review Map (Figure 2)
    Visual review map: accounts of type List[List[str]] flow into Blank 1, marked with a question mark and typed as an email_owner Dict[str, int], then into a DisjointSet holding parent and rank integer lists, then into Blank 4, marked with a question mark and typed as merged rows List[List[str]]; Blank 2 typed find(x) returning int and Blank 3 typed union(a, b) returning bool both plug into the DisjointSet, each marked with a question mark

    Figure 2: Each blank shows only its target type and its place in the data flow. The question mark is the step you write.

    3Interviewer Nudge & Line Focus

    Answer each Socratic check before you type the blank:

    Blank 1 (Email Ownership Map): When an email shows up for the second time, which two account indices are now proven to be the same person? If you keyed the dictionary on the display name instead, what would happen to two unrelated people both called Ana?
    Blank 2 (Path-Compressed find): If find(5) walks the path 5, 4, 3, 2, 1, 0, how many hops should a second find(5) cost, and what does that imply about the five nodes you just walked? With Python’s default recursion limit of 1000, is a recursive walk safe on a 100,000-node path?
    Blank 3 (Union by Rank): You merge a rank-2 tree with a rank-1 tree. Which root becomes the child, and does any rank change? What should union return the second time it sees two accounts that are already connected?
    Blank 4 (Group and Emit): After the last union, is parent[owner] guaranteed to equal the root of owner? How many times can one email appear in a group if you iterate a structure whose keys are already unique, rather than the raw account lists?
    Answer
    Login to view more content
  • DL0073 EfficientNet Compound Scaling

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • DL0028 Sliding Window Attention

    Explain the sliding window attention mechanism in transformer architectures.

    A three-panel whiteboard card: a stack of long legal contracts of 16,384 tokens each, a training log where full attention runs out of memory at that length, and a teammate's sticky note proposing sliding window attention with three open questions.

    The Problem: A legal-tech team is fine-tuning a Transformer encoder on 16,384-token contracts. Full self-attention trains fine at 512 tokens but runs out of GPU memory at full contract length, so a teammate proposes sliding window attention with w = 512, and the team has to understand what that change actually does.

    Answer

    Sliding window attention restricts each token’s attention to a fixed-size local neighborhood instead of the whole sequence: token i attends only to tokens within roughly \pm w/2 positions of itself. This turns the dense n \times n attention matrix into a sparse band around the diagonal, cutting cost from O(n^2) to O(n \cdot w) and making Transformers practical for very long documents, at the price of losing direct long-range links within a single layer.

    (1) Local Window: Each token sees itself plus its w nearest neighbors; everything else is masked out before the softmax.
    (2) Linear Scaling in n: Cost per token is constant (w keys), so total compute and memory grow linearly with sequence length.
    (3) Trade-off: Excellent for local patterns, but global context must be recovered by stacking layers, adding global tokens, or mixing with dilated windows.

    Two attention matrices: a fully dense global attention matrix versus a sliding window matrix with attention confined to a band of width five around the diagonal.

    Figure 1: Global attention fills the whole n \times n matrix; the sliding window keeps only a diagonal band of width w.

    Mathematical Formulation:
    A_{ij} = \frac{q_i \cdot k_j}{\sqrt{d_k}} \quad \text{only if } |i - j| \leq \tfrac{w}{2}, \text{ else masked}
    \text{Cost: } O(n^2) \;\rightarrow\; O(n \cdot w), \quad w \ll n

    Where:

    • w is the window size (e.g., 512 in Longformer); tokens outside the window get -\infty scores before softmax.
    • n is the sequence length; with w fixed, memory and compute scale linearly in n.

    How Global Context Survives: Stacking L layers grows the effective receptive field to about L \cdot w tokens, similar to CNNs; Longformer additionally designates a few global tokens (e.g., [CLS], question tokens) that attend to and are attended by everything.

    Log-scale plot comparing n-squared full attention cost against n-times-w sliding window cost, with an annotation showing 32 times fewer computations at sequence length 16 thousand.

    Figure 2: At n = 16{,}384, full attention needs ~268M score computations versus ~8.4M for a 512-wide window, a 32x saving that grows with n.

    Used In: Longformer, BigBird (window + global + random blocks), and many long-document and code models where full O(n^2) attention is infeasible.


    Login to view more content