Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

Machine Learning
  • Supervised Learning: Features, Labels, Classification and Regression
  • NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
  • First Look at a Dataset: 6 Checks Before You Plot or Model
  • Plotting Distributions with seaborn: Histograms, KDE, Counts and log1p
  • Scatter Plots and Pair Plots: See How Two Columns Relate
  • Finding Outliers: Box Plots, Violin Plots and the IQR Rule
  • Correlation and Heatmaps: Covariance, df.corr() and What They Miss
  • Train-Test Split and Data Leakage: Split First, Learn After
  • Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
  • Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
  • Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
  • Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
  • Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
  • Project: Preprocess Rain in Australia from Raw CSV to Model-Ready Data
    Regression
    • Linear Regression and the Cost Function: Draw a Line, Score It
    • Gradient Descent Explained: Feel the Slope, Step Downhill
    • Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
    • Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
    • Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
    • Regularisation with Ridge and Lasso: Put a Price on Big Weights
    Classification and Evaluation
    • Logistic Regression and the Sigmoid: Score, Squash, Decide
    • Logistic Regression in scikit-learn: predict, predict_proba and Softmax
    • Why Accuracy Lies: The Confusion Matrix, Baselines and Type I/II Errors
    • Precision, Recall and F1 Score: Two Questions and One Balance
    • ROC Curve, AUC and Choosing a Classification Threshold
    • Handling Imbalanced Data: class_weight, SMOTE and the Resampling Leak
    • Cross-Validation: KFold, StratifiedKFold, cross_val_score and cross_validate
    Classic Algorithms
    • K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
    • Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
    • Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
    • Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
    • Bagging and Random Forest: Many Shaky Trees, One Steady Answer
    • Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
    • Voting and Stacking: Does a Team of Models Beat the Best One?
    Model Selection and Tuning
    • Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
    • Which Features Matter? Feature Importances, Permutation Importance and SHAP
    • Project: The Classification Master Template, from Raw CSV to a Saved Model
    • K-Means Clustering: Find Groups in Data With No Labels
    • Choosing k for K-Means: the Elbow Method and the Silhouette Score
    • Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
    • Dimensionality Reduction with PCA: 13 Columns Down to 2
    • Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
    • Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
    • Bag of Words with CountVectorizer: Turn Text into Word Counts
    • TF-IDF with TfidfVectorizer: Common Words Fade, Rare Words Speak
    • Build a Text Classifier with TF-IDF and a Pipeline: Naive Bayes vs LinearSVC
    • Why Neural Networks: Pixels, One Neuron and Layers
    • The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
    • Loss and Backpropagation: How Wrong, and Who Is to Blame
    • The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
    • Your First Neural Network with Keras: MNIST Digits at 97.7%
    • The Same Network in PyTorch: DataLoader, nn.Module and the Five-Line Training Loop
    • Convolutional Neural Networks (CNN) Basics: Filters, Feature Maps and Pooling
    • Embeddings: Words as Vectors, Cosine Similarity and nn.Embedding
    • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
    • Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
    • Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
    • Attention Explained Without the Maths: Query, Key, Value and the Word "it"
    • Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
    • Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
    • Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
    • Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
    • Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
    • When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
    • Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
    • LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
    • Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
    • Serving Open Models: Continuous Batching, vLLM and Cold Starts
      Engineering Basics
      • Python Virtual Environments: One Project, One Toolbox
      • Git and GitHub Fundamentals: Commits, Branches, Push and Pull
      • Testing a FastAPI App with pytest: Three Small Tests
      • Config and Logging Instead of Hard-Coded Values in ML Training
      • SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
      Data and Features in Production
      • Time Splits and Group Splits: Make the Split Match How the Model Is Used
      • Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
      • Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
      • Point-in-Time Correctness: Join Features as of Each Event with merge_asof
      • Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
      • Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
      • Feature Stores: Offline and Online Stores, and When You Actually Need One
      • Data Versioning with DVC: Tie Every Model to the Exact Data That Trained It
      Experiments and Model Quality
      • MLOps in One Picture: Code, Data, Model and the Lifecycle Loop
      • Experiment Tracking with MLflow: Log Params, Metrics and the Model, Then Compare Runs
      • MLflow Model Registry Aliases: Serve the Champion, Ship a New Version and Roll Back in One Line
      • The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
      • Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
      • Slice Evaluation and Fairness Checks: Score the Model Group by Group
      Serving Models
      • Saving and Loading Models with joblib: One Pipeline, One File
      • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
      • Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
      • Docker Essentials for ML: Images, Containers and Volumes with a Model API
      • Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
      • Online, Batch or Streaming? Picking the Serving Pattern for an ML Model
      • A Production FastAPI for an ML Model: Input Limits, /health, /ready and a Model Version
      • Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
      • Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
      • Measuring Latency of an ML API: Timing Inside with OpenTelemetry, Outside with a Load Test and Locust
      • Making ML Inference Fast: ONNX, Micro-Batching and Quantisation, Measured
      • Sizing and Autoscaling an Inference Service: From One Replica to a Replica Count
      Pipelines, CI/CD and Cloud
      • The Training Pipeline as a DAG: Steps, Files, Retries and a Safe Rerun
      • Orchestrating ML Pipelines with Airflow: Schedule, Retries and Backfill
      • Retries and Backoff for Reliable Tasks: Retry What Heals, Wait Longer, Add Jitter, Set Limits
      • CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
      • CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
      • Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
      • IaaS, PaaS, Containers or Serverless? Choosing Where a Model API Runs
      • Kubernetes at a High Level: Pods, a Deployment and a Service for a Model API
      • Managed ML Platforms: What SageMaker, Vertex AI and Azure ML Give You, and Tie You To
      • Deploying a Model API to AWS: ECR, Secrets Manager, CloudWatch and Fargate, Then Teardown
      • Cloud Cost Thinking for ML: Size x Count x Hours x Rate, and Three Decisions Worth Ten Times
      Monitoring and Release
      • Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
      • Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
      • Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
      • A/B Tests for Models: Did the New Model Make Things Better for People?
      • When Labels Arrive Weeks Late: What to Watch Before You Can Grade the Model
      • Retraining Triggers: Schedule, Drift and Performance, Wired to One Retrain Pipeline
      • The User Feedback Loop: Why Thumbs Up Isn't the Truth, and What a Small Random Review Adds
      • Debugging a Model in Production: A Four-Step Runbook, Cheap Checks First
      • Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
      • Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
      • Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
      • Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
      • Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
      • Demand Forecasting, Part 1: The Business Problem, a Price per Mistake and the Line to Beat
      • Recommendations, Part 1: Two Stages, Candidates Then Ranking
      • Demand Forecasting, Part 2: Walk-Forward Backtesting, Ridge vs Boosting and the Slices an Average Hides
      • Recommendations, Part 2: Candidate Generation With Embeddings
      • Demand Forecasting, Part 3: The Nightly Batch Pipeline That Survives a Crash
      • Recommendations, Part 3: The Ranker and Offline Metrics (Recall@k and nDCG)
      • Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
      • Recommendations, Part 4: Serving With FastAPI, a Cache and a Popular Fallback
      • Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
      • Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
      • Ticket Routing, Part 3: Quantise to int8, Host Behind FastAPI and Measure the Server
      • Ticket Routing, Part 4: Canary, Automatic Rollback and "Does Your Small Model Reason?"
      • The ML Engineer Interview Loop: Five Rounds, What Each One Looks For, and a Simple Rubric
      • The Answer Framework for Technical Interviews: Five Moves, Scored Out of 24
      • From Symptom to Pattern: How to Answer "Which Pattern Would You Use?" in an Interview
      • The ML System Design Framework: Eight Steps, in Order, on a Spam Filter
      • ML System Design Interview: Fraud Detection for Card Payments, in Eight Steps with Numbers
      • ML System Design Interview: A Recommendation Feed, From a Score to Beat to Online Guardrails
      • ML System Design Interview: Ad Click Prediction, Sparse Features, Calibration and Late Clicks
      • Interview Answer: How Do You Roll Out a New Model Safely When True Labels Come Weeks Later?
      • Mock ML Engineer Interview, Scored: A Rollout Question Where the Labels Arrive Weeks Late
      • The ML Coding Round: K-Means, Logistic Regression and a Top-k Metric From Scratch
      • The ML Depth Round: Five Questions That Always Come, in Thirty Seconds Each
      • Presenting Your Portfolio: A Six-Section README That Shows Evidence, Not Buzzwords
      • Reading a Job Ad and Shaping Your CV: A Gap List and CV Lines You Can Stand Behind
      • How AI Questions Show Up in an ML Engineer Interview: Your Angle, the Rounds and a Good Answer
      • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
      • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
      • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
      • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
      • Coding Round: Merge Top-k From Sorted Shards, Then Fuse Two Rankings by Place
      • Mock Interview, Scored: 429s at Peak Because One Customer's Batch Job Eats the Capacity
      1. Blog
      2. /
      3. Machine Learning
      4. /
      5. ML Engineer Interviews

      Coding Round: Merge Top-k From Sorted Shards, Then Fuse Two Rankings by Place

      Two coding-round ideas in plain words. Merging three sorted shard lists by sorting all 11 rows gives five rows but only three documents; a small next-best pile with a seen set gives five documents after looking at 7 rows. Then why adding raw scores copies one judge, and how rank fusion lifts d4 to the top by a hair.

      Chaand Sheikh

      ·27 November 2026ML Engineer Interviews

      What you will learn

      • Ask the four questions before merging ranked lists: sorted, repeats, ties, empty lists
      • See why sort-everything-and-cut returns 5 rows but only 3 documents
      • Explain the next-best pile (a heap): one row per list, take the best, refill, skip what you've seen
      • Explain why adding raw scores lets one ranking decide, and what reciprocal rank fusion gives up

      Before you start

      • Hybrid Search: BM25 Plus Dense Embeddings
      • Basic Python lists and sorting

      This one comes from a coding round, but the ideas matter more than the syntax. Idea one: several sorted lists arrive from different shards, and you want the best five overall. Idea two: two rankings of the same documents, and you want one ranking out of them. All the examples here are small and synthetic, made up for illustration.

      Three stacks of exam papers

      Three teachers each hand you a stack of exam papers. Every stack is sorted, highest mark on top, and you need the top five overall. You don't shuffle everything together. You look at the top sheet of each stack, take the highest, and that stack shows you its next sheet. So you only ever compare three sheets.

      In a search system, those stacks are shards, and each shard sends back its own sorted list. Before you start, ask four questions:

      1. Is every list truly sorted?
      2. Can one document sit in two lists?
      3. If scores tie, who goes first?
      4. What if a list is empty?

      Asking these out loud is part of the score. The interviewer wants to see that you know where the edge cases are before you write a line.

      The simple answer goes wrong

      The simple answer: pour all the lists into one pile, sort it, cut at five. With three synthetic lists, eleven rows in all, here is what that gives:

      naive top 5
        d4  0.95000
        a7  0.91000
        c2  0.88000
        c2  0.84000
        d4  0.80000

      You asked for five documents and got three. c2 and d4 sit in two lists, and each copy took a seat. f9 and g6 should have made it, and they're left outside. So sorting everything does extra work, and here it's also wrong.

      The next best pile

      Now the better idea. Each list puts only its top row into a small pile. You take the best one from the pile, and the list it came from slides up its next row, so the pile always holds one row per list. A short note beside the answer tracks the documents you've already taken, so a repeat is skipped.

      Heap merge of three sorted lists with a seen set shard list 1 shard list 2 shard list 3 small pile one row per list take best, refill answer (top 5) d4 0.95 · a7 0.91 c2 0.88 · f9 0.80 g6 0.80 seen set skips c2, d4 repeats 7 of 11 rows looked at Synthetic lists. Textbooks call the pile a heap.
      Only one row per list sits in the pile at any time, and a repeat never takes a seat.

      Walk through it. The best row in the pile is d4 at 0.95, so it goes into the answer, and its list slides up g6. When c2 shows up a second time, it's skipped. Then three rows tie at 0.80, so you pick one fixed rule (for example by name) and use it every time. d4's second copy comes first and gets skipped, then f9 and g6 take the last two seats.

      heap merge top 5
        d4  0.95000
        a7  0.91000
        c2  0.88000
        f9  0.80000
        g6  0.80000
      items touched: 7 of 11

      Five documents, and we stopped after looking at seven of the eleven rows. In a bigger synthetic run with 200,000 rows and no repeats, the merge looked at just 10 rows and gave the same answer as sorting everything. The run also printed timings (sorting everything 96.8 ms, the heap merge 0.05 ms), but those vary between runs, so quote the shape, not the numbers.

      If you want to write it down, the steps fit in a short sketch. This is an illustration written for this article, not the lecture's code:

      # Sketch only: lists are sorted best-first, rows are (doc, score)
      import heapq
      
      def top_k(lists, k):
          pile = [(-rows[0][1], rows[0][0], i, 0) for i, rows in enumerate(lists) if rows]
          heapq.heapify(pile)          # ties break by doc name: one fixed rule
          seen, answer = set(), []
          while pile and len(answer) < k:
              neg, doc, i, j = heapq.heappop(pile)
              if doc not in seen:
                  seen.add(doc)
                  answer.append((doc, -neg))
              if j + 1 < len(lists[i]):
                  nxt_doc, nxt_score = lists[i][j + 1]
                  heapq.heappush(pile, (-nxt_score, nxt_doc, i, j + 1))
          return answer

      Say the assumption out loud: this only stays cheap because the lists arrive sorted. Somebody paid for that sort earlier, on each shard.

      Two judges, two scales

      Second idea. A keyword search and a meaning search give you two rankings of the same documents. Picture two judges at a baking contest: one scores in the twenties, the other scores below one. The obvious move is to add each document's scores:

      sum of raw scores, top 3
        d1  24.40000
        d2  22.28000
        d3  19.00000
      lexical alone, top 3: ['d1', 'd2', 'd3']

      That's exactly the first judge's own top three. The second judge had no say, and d4, the second judge's favourite, doesn't make the top three. The judge with the big scale decides everything. You could rescale, but the spread shifts between searches.

      Compare places, not scores

      So compare places instead. Each list becomes first, second, third, and the scale disappears. Each place earns a small vote of 1 / (60 + place), and the votes add up. The 60 keeps the gaps gentle.

      rrf k=60, top 5
        d4  0.03202
        d2  0.03200
        d1  0.03178
        d5  0.03151
        d6  0.03030

      d4 is fourth with one judge and first with the other, and rises to the top. d3 drops out of the top five, because only one judge knows it. Two honest notes: d4 wins by a hair (0.03202 against 0.03200), so don't call it a strong win. And this method throws away how far ahead a document was, because only the place counts. This is reciprocal rank fusion; the full treatment with BM25 and embeddings is in Hybrid Search: BM25 Plus Dense, Merged With RRF.

      Talking it through

      1. Questions: sorted? repeats? ties? empty lists?
      2. Simple answer and its problem: "I could sort everything, but repeats would take seats, and I'd read every row."
      3. Better idea: one row per list in a small pile, take the best, refill, skip what I've seen, stop at five.
      4. Assumption: the lists arrive sorted.
      5. Rankings: "The scores sit on different scales, so I'll combine places, and I give up how far ahead anything was."

      Follow-ups and a simple rubric

      These answers are design guidance, not measured:

      • One shard is slow? Set a time limit, merge what arrived, and mark the answer as partial.
      • Lots of repeats? Each shard has to send more than five, or you can run short.
      • Why 60? It's a common default, so test it on your own data.
      • How would you catch this breaking again? Keep a slice of exact-code questions in your evaluation set, and compare before and after each change.
      LevelWhat it sounds like
      WeakSorts everything and doesn't notice the repeats
      SolidAsks the questions, explains the pile, combines places correctly
      StrongAlso states the sorted assumption and the tie rule, and names what rank fusion gives up

      The rubric is a suggestion, not any company's official sheet.

      Recap

      IdeaWhat to remember
      Sort and cut5 rows but only 3 documents
      Next best pile5 documents after looking at 7 of 11 rows; sorted lists assumed
      Raw scoresThe big scale wins
      Rank fusionPlaces, not scores; d4 on top by a small margin

      Try it yourself

      On paper, use 10 in place of 60. Work out the votes for d4 (fourth and first) and d2 (second and third). Who comes first now?

      Tried the exercise? Share your answer or ask a question.

      The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

      Join free on Skool

      Keep going in Machine Learning · 154 of 155

      Previous
      A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
      Next post
      Mock Interview, Scored: 429s at Peak Because One Customer's Batch Job Eats the Capacity

      Related course on Udemy

      Machine Learning Engineer: From First Model to ML Engineer

      Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

      Related posts

      The ML Engineer Interview Loop: Five Rounds, What Each One Looks For, and a Simple Rubric

      The rounds you go through for one ML engineer job: recruiter screen, coding, ML depth, ML system design and behavioural. What each round looks for, the follow-up it brings, and a four-check rubric for your own answers.

      The Answer Framework for Technical Interviews: Five Moves, Scored Out of 24

      Good interview answers share one shape: a 30-second answer, the mechanism, the trade-off, the metric and the failure test. Worked on one question about a batch job starving everyone else, with a 24-point example rubric.

      From Symptom to Pattern: How to Answer "Which Pattern Would You Use?" in an Interview

      Start from what you can see, not from the pattern you know. A four-step rule (symptom, cost, metric and failure test, ship first), a symptom table, one worked answer for 429s at peak, and the trap of using a prompt as a lock.

      The ML System Design Framework: Eight Steps, in Order, on a Spam Filter

      One repeatable route through any ML system design question: goal, metric, data, features, model, serving, monitoring and failure. Worked on an email spam filter, with the follow-ups and a three-check rubric.

      On this page

      • Three stacks of exam papers
      • The simple answer goes wrong
      • The next best pile
      • Two judges, two scales
      • Compare places, not scores
      • Talking it through
      • Follow-ups and a simple rubric
      • Recap
      • Try it yourself
      Community · Free to join
      Single logo

      StudyEasy AI Community

      Hosted onSkool

      Learn AI engineering, share what you build, and connect with other learners.

      • Free resources: lesson files, notebooks and code

      • Ask questions and join engineering discussions

      • Meet real people learning and building with AI

      Join free on Skool

      Related course on Udemy

      Machine Learning Engineer: From First Model to ML Engineer

      Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)

      Single logo

      Empowering Education, One Course at a Time

      About
      About usContact usFAQs
      Legal
      Terms of ServicePrivacy Policy

      © 2026 StudyEasy Organization. All rights reserved.