Top 30 AI & ML Interview Questions and Answers
30 multiple-choice questions on AI & ML, of the kind that come up in a technical interview, drawn from 30 bites in the AI & ML library. Answer them here or read straight down. Every question carries the correct option, why it is correct, and a link to the bite it came from.
Artificial intelligence, machine learning, and data science
30 questions. Pick an answer, or open “Show the answer” to read it.
Answers are graded in your browser. Quiz progress is not saved, and no XP or streak is earned here. The app keeps score.
Question 1 of 30
When converting a large list of flat dictionaries to a pandas DataFrame, which method is the idiomatic one-shot approach for aligning keys and avoiding repeated DataFrame growth?
Show the answer
Answer: c · Pass the list of dicts directly to pd.DataFrame so the constructor aligns the dictionary keys in one operation
Passing the list directly to pd.DataFrame is the idiomatic approach for flat row-oriented dictionaries: it aligns the union of keys and fills missing values with NaN. Repeatedly growing a DataFrame can cause unnecessary copying, while the exact performance of alternatives depends on the data and pandas version.
Read the full bite: Most efficient way to convert list of dicts to pandas DataFrame
Question 2 of 30
For a DataFrame with a string index, which call raises an error and why?
Show the answer
Answer: d · df.iloc['x'], because iloc requires integer positions not labels
iloc is strictly positional and rejects a string label, raising a TypeError. df.loc['x'] and df.iloc[0] both work correctly on a string-indexed frame.
Question 3 of 30
A pandas DataFrame has 5% missing values in customer_age, completely at random. When is dropna the better choice over fillna?
Show the answer
Answer: c · When generating a quick aggregate report and the remaining 95% of data is sufficient
The card states that dropna is safe for a quick aggregate report when data is missing completely at random and the remaining sample is still large enough. Option A describes the opposite scenario: when age is predictive, dropping rows discards valuable labeled outcomes and reduces model performance, so imputation is preferred instead.
Read the full bite: Describe strategies for handling missing values in pandas DataFrames
Question 4 of 30
Which query pattern correctly identifies customers who have never placed an order?
Show the answer
Answer: b · LEFT JOIN orders then filter WHERE orders.customer_id IS NULL
B uses the correct anti-join pattern: LEFT JOIN preserves all customers and IS NULL keeps only those with no matching orders. D is not an anti-join, and A can be unsafe when the subquery contains NULL customer IDs because SQL three-valued logic can suppress expected rows.
Read the full bite: Find customers who have not placed any orders
Question 5 of 30
Which approach correctly handles the full response lifecycle when fetching JSON from a REST API in production using Python's requests?
Show the answer
Answer: c · Verify the status with r.raise_for_status() before parsing with r.json()
Calling r.raise_for_status() before trusting r.json() raises an HTTPError for unsuccessful responses before application code treats their bodies as successful payloads. r.json() parses the response body independently and can also raise a JSON decoding error when the body is not valid JSON; timeouts and connection errors need separate handling.
Read the full bite: How do you fetch JSON from a REST API and parse it?
Question 6 of 30
Why is a violinplot generally preferred over a bar plot when exploring house prices across neighborhoods?
Show the answer
Answer: a · It preserves the full distribution, revealing features like bimodality and outliers that a bar plot's single statistic would obscure.
The card states that bar plots collapse a continuous distribution into a single estimate like the mean, hiding variance, multimodality, and extreme values, whereas violinplots reveal the full distribution shape. Option D actually describes the key limitation of a bar plot, not an advantage of a violinplot.
Read the full bite: Which plot visualizes a continuous versus categorical variable and why?
Question 7 of 30
During EDA, a heatmap reveals a strong positive correlation between daily ice cream sales and sunscreen sales. What is the most appropriate next step before making causal business recommendations?
Show the answer
Answer: d · Investigate potential confounders such as outdoor temperature and examine partial correlations before making causal recommendations.
The card emphasizes that a strong heatmap correlation should prompt a search for confounders such as temperature and further analysis like partial correlation, not a causal conclusion. Option B is wrong because heatmap color intensity reflects linear association, not causal strength, which is a key red flag mentioned.
Read the full bite: Explain correlation vs causation and heatmap limitations in EDA
Question 8 of 30
A data scientist chooses Z-score standardization over Min-Max scaling before training a logistic regression model with gradient descent. What is the primary statistical reason for this choice?
Show the answer
Answer: b · Z-score standardization centers features at mean zero with unit variance, ensuring weight updates proceed at comparable rates during gradient descent.
Z-score standardization places features on comparable scales so gradient descent updates all weights at similar rates and no feature dominates the loss surface. The Min-Max distractor is tempting but incorrect because bounding values to [0, 1] does not equalize variances, and high-variance features can still compress the signal of others.
Question 9 of 30
When a categorical feature has thousands of unique values, which approach avoids the dimensionality and memory issues of one-hot encoding while keeping predictive signal?
Show the answer
Answer: d · Target encoding, which replaces each category with the mean of the target variable for that category
Target encoding collapses a high-cardinality categorical feature into a numeric statistic such as a target mean, avoiding one sparse column per category. Compute the statistic out-of-fold for training data and from training data only for validation or test data, with smoothing where appropriate, to reduce target leakage. Label and ordinal encoding can impose a false order on nominal categories.
Read the full bite: Why avoid one-hot encoding for high cardinality and what are alternatives?
Question 10 of 30
In fraud detection with 1% fraud prevalence, a model labels every transaction as legitimate and achieves 99% accuracy. What is the key lesson?
Show the answer
Answer: a · Accuracy can be misleading because it ignores the rare positive class entirely
The card describes the accuracy paradox, where a trivial classifier achieves 99% accuracy on imbalanced fraud data while catching zero actual fraud, proving accuracy can hide complete failure on the minority class. Option C is tempting because 99% sounds excellent, but it wrongly rewards a model that is entirely useless for the business goal of detecting fraud.
Read the full bite: Why is accuracy misleading for fraud detection, and what metrics instead?
Question 11 of 30
Which description best captures how K-Means iteratively forms its final clusters?
Show the answer
Answer: d · It initializes K centroids, then repeatedly assigns points to the nearest centroid and recomputes each centroid as the cluster mean until stable.
K-Means uses Lloyd's algorithm to repeatedly assign observations to the nearest centroid and update each centroid to the cluster mean until convergence. Option B is tempting because random initialization is correct, but the algorithm is not a single-pass assignment; without iterative refinement it would not minimize within-cluster variance.
Read the full bite: How does K-Means clustering work and how do you choose K?
Question 12 of 30
You run an experiment and obtain p = 0.03. Which statement correctly interprets this p-value?
Show the answer
Answer: c · If the null hypothesis were true, there is a 3% probability of observing data at least this extreme.
A p-value assumes the null hypothesis is true and quantifies the probability of seeing data at least this extreme under that assumption; it does not measure the probability that the null is false, that the alternative is true, or that the result occurred by chance.
Read the full bite: What is a p-value? Interpret p = 0.03 at alpha = 0.05.
Question 13 of 30
Which hypothesis pair best tests whether a green signup button increases registrations compared to blue?
Show the answer
Answer: b · H0: The registration conversion rate for green equals that for blue; H1: The registration conversion rate for green is strictly greater than that for blue.
The correct answer frames H0 as no difference and H1 as a directional increase in the specific metric, matching the one-tailed nature of the business question. Option A is tempting because it uses 'no difference,' but it wrongly uses a two-tailed alternative that ignores the directional ask and wastes statistical power.
Read the full bite: What are your null and alternative hypotheses for this A/B test?
Question 14 of 30
Which approach best demonstrates a sound framework for measuring e-commerce user engagement?
Show the answer
Answer: a · Use DAU/MAU, adoption, retention, and stickiness tied to conversion and churn
Among these choices, A is the best framework because it connects engagement measures to business outcomes instead of treating page views as success. For an e-commerce product, apply that principle to the journey: product views and search, add-to-cart, checkout, purchase, repeat purchase, conversion, revenue or margin, and retention. DAU/MAU can remain a supporting habit signal.
Read the full bite: What metrics track e-commerce user engagement and how do you prioritize them?
Question 15 of 30
Why does replacing sigmoid with ReLU in a deep network reduce vanishing gradients?
Show the answer
Answer: c · ReLU has a derivative of 1 for positive inputs, so it does not shrink gradients there
ReLU's unit derivative in its active region avoids the sub-one multiplications that cause sigmoid's gradients to vanish across depth. ReLU is unbounded above, does not normalize, and does not amplify gradients beyond one.
Question 16 of 30
Why is HSV often preferred over RGB for segmenting a colored object across a scene with mixed sunlight and shadow?
Show the answer
Answer: b · Hue stays relatively stable under lighting changes, so color separates from brightness
HSV isolates hue from value, so a color keeps its hue under varying illumination, easing thresholding. Both spaces cover the same color gamut, so the capacity claim is false.
Question 17 of 30
How should a healthy production ML lifecycle be structured from start to finish?
Show the answer
Answer: c · As an iterative loop starting with business problem framing and continuing through post-deployment monitoring
The correct answer is B because the card describes the lifecycle as an end-to-end engineering process that begins with business goal definition and requires continuous monitoring and feedback loops after deployment. The most tempting distractor is D because treating packaging as the final step omits critical monitoring, retraining, and validation stages that keep a production model healthy.
Read the full bite: Describe the key stages of a typical ML lifecycle
Question 18 of 30
Which property of one-hot vectors prevents a model from inferring that 'excellent' and 'outstanding' are similar?
Show the answer
Answer: a · They are mutually orthogonal, giving every pair zero cosine similarity
A is correct: one-hot vectors are mutually orthogonal, so their cosine similarity is zero and they provide no geometric signal that related words are similar. High dimensionality is a separate practical drawback.
Question 19 of 30
An e-commerce site sees search users convert at 5% and non-search users at 2%. What is the best next step to estimate the true incremental impact of search?
Show the answer
Answer: a · Match searchers to similar non-searchers using device, landing page, and prior sessions, then compare rates
Matching on confounders like device and landing page isolates selection bias, which is why the example shows the true incremental lift drops to roughly 25% after propensity matching. Running a two-sample t-test on the raw rates assumes the groups are comparable and would incorrectly validate an inflated, non-causal difference.
Read the full bite: How would you validate that search users are more likely to purchase?
Question 20 of 30
A photography platform archives original images for future editing and serves compressed previews. Which strategy best preserves fidelity while optimizing delivery?
Show the answer
Answer: d · Store originals in a lossless format and serve previews as lossy JPEG to reduce bandwidth.
Lossless storage preserves bit-exact originals for future editing and avoids generational degradation, while lossy JPEG cuts preview sizes for faster web delivery. Option C is tempting because PNG guarantees exact pixels, but serving previews losslessly wastes bandwidth without perceptible quality gains over a well-compressed lossy image.
Read the full bite: What is the difference between lossy and lossless image compression?
Question 21 of 30
Which scenario would trigger an automated MLOps deployment but typically not a traditional DevOps pipeline?
Show the answer
Answer: b · Production monitoring detecting drift in input data distributions
The card states that MLOps deployments add triggers like data drift detection, unlike DevOps pipelines that react to code commits, dependency patches, or infrastructure changes. The GPU driver update is a tempting distractor because a common misconception is that MLOps is simply DevOps plus GPUs.
Read the full bite: What are the primary differences between traditional DevOps and MLOps?
Question 22 of 30
Which statement best describes how histogram equalization remaps grayscale intensities?
Show the answer
Answer: d · It applies the cumulative distribution function to redistribute intensities toward a uniform histogram.
Histogram equalization uses the cumulative distribution function of the original histogram to remap intensities so the output approximates a uniform distribution, maximizing global contrast. The first option describes linear contrast stretching, which merely rescales the minimum and maximum values without considering the frequency of each intensity level.
Read the full bite: Describe a grayscale histogram and its use in exposure and equalization
Question 23 of 30
When training a large transformer, training loss falls while validation loss rises. Which action most directly addresses the root cause?
Show the answer
Answer: b · Apply early stopping or add regularization like weight decay
The divergence signals overfitting, where the model memorizes training noise instead of generalizable patterns. Early stopping and regularization directly combat this, whereas longer training or more parameters typically worsens the gap, and a lower learning rate does not directly fix memorization.
Read the full bite: Validation loss increases while training loss decreases: what is this?
Question 24 of 30
A deployed fraud model degrades. Using immutable lineage best practices, what is the most reliable way to isolate data drift from a code bug?
Show the answer
Answer: a · Reproduce the exact training run by combining the manifest's commit SHA, dataset hash, and locked dependencies, then verify the metrics match production logs
Reproducing the full training context from the manifest proves the model still yields the same metrics, confirming that production degradation is due to data drift rather than a code bug. Option B is tempting because it uses the exact dataset, but swapping in the latest code introduces a new variable and breaks the lineage chain needed for a valid comparison.
Read the full bite: Why version code, data, and models in MLOps?
Question 25 of 30
A monthly subscriber cancels mid-cycle but retains access until month-end. Which approach reflects a rigorous churn definition for this user?
Show the answer
Answer: a · Waiting until the billing period ends or a reactivation window passes
A rigorous definition ties churn to the actual end of access or the close of a defined renewal window, not just the intent signal. Counting the cancellation click immediately is the naive error highlighted in the card, because the user may still revert and the revenue is still active through the billing period.
Read the full bite: How do you define churn for a subscription service?
Question 26 of 30
How are the intrinsic parameters fx and fy in K derived from physical camera properties?
Show the answer
Answer: a · They equal the focal length divided by pixel width and height respectively
fx and fy convert the physical focal length into pixel units by dividing by pixel width and height, making C correct. A is a common misconception because K stores focal length in pixel units, not millimeters, and D is wrong since distortion is modeled outside the idealized pinhole matrix.
Read the full bite: Explain the pinhole camera model and intrinsic matrix K
Question 27 of 30
An e-commerce company notices prediction accuracy dropping on a model whose serving code hasn't changed. What is the most appropriate first step in a mature MLOps setup?
Show the answer
Answer: a · Trigger the CT pipeline to validate data, train, evaluate against the champion, and promote if blessed
When model performance decays but serving code is unchanged, the CT pipeline should validate data, retrain, and evaluate before promotion. Option D is wrong because it bypasses evaluation gates and data validation, and B is wrong because models are separate deployable units from serving code.
Read the full bite: Explain ML pipelines and typical CI/CD/CT components
Question 28 of 30
A checkout A/B test shows significantly higher conversion but slightly lower AOV. What is the strongest basis for a launch recommendation?
Show the answer
Answer: d · Estimate net revenue and ensure the AOV decline is within a pre-specified non-inferiority margin
The right framework classifies conversion as a success metric and AOV as a guardrail requiring non-inferiority, then uses net revenue to judge the business outcome. Treating AOV as a co-success metric that must significantly increase is a tempting error that causes unnecessary conservatism and missed wins.
Read the full bite: How would you recommend launching a checkout flow with mixed A/B metrics?
Question 29 of 30
In full BPTT, what is the primary reason memory usage grows linearly with sequence length T?
Show the answer
Answer: c · All intermediate hidden states from the forward pass must be kept for the backward pass.
During BPTT the backward pass flows through every time step, so every forward hidden state must be retained, yielding O(T) memory. Option D repeats the common misconception that training memory is constant like inference memory, while option A confuses unrolling with parameter duplication.
Read the full bite: Explain BPTT and its computational and memory challenges for long sequences
Question 30 of 30
A marketing team debates predicting exact spend versus High/Medium/Low tiers. What most strongly determines whether regression or classification is the better framing?
Show the answer
Answer: a · Whether the downstream campaign action requires a ranked list and continuous segmentation or a hard gate into fixed segments.
The campaign action dictates whether you need a ranked continuous score or a discrete gate, making B correct. D is tempting but dangerous because choosing classification solely for yes/no simplicity ignores the information loss from binarizing a continuous signal and may mismatch flexible budget allocation.
Could you explain these out loud?
That is what an interview actually tests. Tezvyn gives you questions like these with what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.