This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.
Category: Build & Trace
CD0063 Merge Accounts Union-Find
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-account chain comfortably.
Fill the 4 blanks in the skeleton below. Then trace the
parentandrankarrays aloud on a small chain, and give the total running time in terms ofaccounts and
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
Figure 1: The input and output contract plus the four input shapes the hidden checks probe. The question-marked box is the whole exercise.
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:unionreceives 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](https://intvml.com/wp-content/uploads/2026/11/CD0063-merge-accounts-union-find-review-map.jpg)
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): Iffind(5)walks the path 5, 4, 3, 2, 1, 0, how many hops should a secondfind(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 shouldunionreturn the second time it sees two accounts that are already connected?Blank 4 (Group and Emit): After the last union, isparent[owner]guaranteed to equal the root ofowner? 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 contentCD0061 CV Splitters From Scratch
This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.
CD0059 Gaussian Naive Bayes
LinkedIn’s feed-integrity team keeps a Gaussian naive Bayes baseline for spam and bot detection because it is fast to retrain and easy to audit. Every score it emits decomposes into a class prior plus one additive term per feature, so a reviewer can see which signal pushed an account toward the bot class. In this round you implement
GaussianNBfrom scratch in NumPy. Importing anything fromsklearnis forbidden, and so isscipy.stats.norm.fit(X, y)receives a matrix of shapeand labels of any dtype. It must store the sorted labels in
classes_, the per-classclass_count_andclass_prior_(count divided by, with no smoothing), and per-class, per-feature maximum-likelihood means
theta_and variancesvar_. It must also setepsilon_tovar_smoothingtimes the largest per-feature variance of the full training matrix, and floor every entry ofvar_at it._joint_log_likelihoodreturns thematrix of log prior plus summed Gaussian log-densities.
predictreturns labels taken fromclasses_, andpredict_probareturns posterior rows that each sum to 1.Three edges are graded: a feature that is constant within a class, a class seen exactly once, and a 600-feature input whose density product underflows. Fill the 4 blanks, trace the array shape after each line, and verify against a hand-computed two-class fixture.
Skeleton Code (Fill Blanks 1-4):
01 import numpy as np 02 03 04 class GaussianNB: 05 # Gaussian naive Bayes: maximum-likelihood fit, log-space scoring 06 07 def __init__(self, var_smoothing=1e-9): 08 self.var_smoothing = var_smoothing 09 10 def fit(self, X, y): 11 X = np.asarray(X, dtype=np.float64) # (n_samples, n_features) 12 y = np.asarray(y) # (n_samples,) 13 n_samples, n_features = X.shape 14 self.classes_ = np.unique(y) # (n_classes,), sorted 15 n_classes = len(self.classes_) 16 self.class_count_ = np.zeros(n_classes) 17 self.class_prior_ = np.zeros(n_classes) 18 self.theta_ = np.zeros((n_classes, n_features)) # per-class means 19 self.var_ = np.zeros((n_classes, n_features)) # per-class variances 20 for class_idx, label in enumerate(self.classes_): 21 X_class = X[y == label] # (n_class_samples, n_features) 22 # TODO (Blank 1): fill row class_idx of class_count_, class_prior_, 23 # theta_ and var_ (maximum-likelihood estimates) 24 ... 25 # TODO (Blank 2): set epsilon_ from var_smoothing and the per-feature 26 # variances of X, then floor var_ at epsilon_ 27 ... 28 return self 29 30 def _joint_log_likelihood(self, X): 31 X = np.asarray(X, dtype=np.float64) # (n_queries, n_features) 32 # TODO (Blank 3): log prior + sum over features of the Gaussian 33 # log-density, shape (n_queries, n_classes) 34 joint_log_likelihood = ... 35 return joint_log_likelihood 36 37 def _decide(self, X): 38 joint_log_likelihood = self._joint_log_likelihood(X) # (n_queries, n_classes) 39 # TODO (Blank 4): labels = top-scoring class label per row, 40 # proba = posterior rows that each sum to 1 41 labels = ... 42 proba = ... 43 return labels, proba 44 45 def predict(self, X): 46 return self._decide(X)[0] # (n_queries,) 47 48 def predict_proba(self, X): 49 return self._decide(X)[1] # (n_queries, n_classes)
Figure 1: the public contract. The inputs and outputs of
fit,predict, andpredict_probaare fixed, the four question-marked steps are yours to write, and the three graded edges at the bottom decide the score.Progressive Hints (Free · Zero Spoilers)1Inspection Checklist (Where to Look)
(1) Per-Class Statistics: Every stored statistic must be a finite number for a class with a single training row, and the priors must sum to 1.
(2) Floor Scale: Ask which matrix the floor is measured on (the full training set or one class), and what it evaluates to when every column is constant.
(3) Log-Space Scoring: Each class score is a sum of logarithms; no density is exponentiated or multiplied before the final normalization.
(4) Row Normalization: Probability rows must sum to 1 even when every joint log-likelihood in the row sits below.
2Visual Review Map (Figure 2)

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shapes it must produce; the operations that reach them are the exercise.
3Interviewer Nudge & Line Focus
Pin the input shape, output shape, and numerical range of each blank before writing the NumPy call:
Blank 1 (Per-Class Statistics): Under maximum likelihood, does the variance divide byn_corn_c - 1, and what number does each choice produce for a class with one row? Which of the two results can a laternp.maximumnever repair?Blank 2 (Variance Floor): If one feature is a follower count with variance nearand another is a ratio in
, should the floor be absolute or relative to the data? What does your
epsilon_evaluate to when every column of the training matrix is constant?Blank 3 (Joint Log-Likelihood):theta_is(n_classes, n_features)and the queries are(n_queries, n_features). Where must each array gain a new axis so the difference broadcasts to(n_queries, n_classes, n_features), and which axis do you then sum away?Blank 4 (Labels + Posterior): If both entries of a row are about, what does
np.expreturn for each, and what is0 / 0? Which per-row constant can you subtract without changing the normalized result, and doesnp.argmaxreturn a label or a column index?Answer
Login to view more contentCD0053 Int8 Quantization
This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.