← Uber Interview Insights

Uber·Machine Learning Engineer·Onsite - Coding / Algorithms·Senior

SeniorPrefer not to say
Jul 2026

Summary

Uber MLE onsite coding round where you pick one of four ML primitives to implement from scratch in Python/NumPy, no sklearn allowed. The math derivation is graded as hard as the code, which I did not fully appreciate going in.

Questions Asked (7)

Q1

Implement linear regression using gradient descent from scratch in NumPy, including the MSE loss and the gradient update rule. Be ready to derive the gradient on a whiteboard before writing any code.

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

They really do make you derive it first.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by deriving the gradient of MSE with respect to weights and bias on the whiteboard, then implement gradient descent in NumPy with vectorized operations. Emphasize the importance of feature scaling and monitoring convergence to ensure stable training.

Pro tip: Mention that you would standardize features before gradient descent to avoid slow convergence, and that you'd track the loss curve to detect divergence or oscillation.

1. Derive the gradient

On the whiteboard, write the MSE loss function and compute its partial derivatives with respect to weights and bias, showing each step clearly.

2. Initialize parameters

Initialize weights (e.g., zeros or small random values) and bias to zero, and set hyperparameters like learning rate and number of iterations.

3. Implement gradient descent loop

In NumPy, compute predictions, loss, gradients, and update parameters iteratively, using vectorized operations for efficiency.

4. Monitor convergence

Track the loss over iterations and optionally check gradient norm to ensure the algorithm is converging; adjust learning rate if needed.

5. Validate and discuss trade-offs

Test on a small dataset, compare with closed-form solution, and discuss trade-offs like learning rate selection and feature scaling.

Key Points to Mention

  • MSE loss function and its gradient derivation
  • Vectorized implementation for efficiency
  • Feature scaling (standardization) for faster convergence
  • Learning rate selection and its impact on convergence
  • Convergence monitoring and stopping criteria
  • Comparison with closed-form solution (normal equation)

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q2

Implement logistic regression with mini-batch gradient descent from scratch. Explain the binary cross-entropy loss and justify the gradient. Also handle numerical stability issues like sigmoid overflow and log(0).

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

The clipping stuff is easy to forget under pressure.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clearly defining the logistic regression model and binary cross-entropy loss, then derive the gradient with respect to weights. Implement mini-batch gradient descent with numerical stability techniques, and explain each design choice. Finally, discuss trade-offs and potential pitfalls.

Pro tip: Emphasize that numerical stability is not just about avoiding errors but also about ensuring correct gradient behavior; for example, using the log-sum-exp trick or a stable sigmoid implementation can prevent silent performance degradation.

1. Define Model and Loss

State the logistic regression hypothesis: p(y=1|x) = sigmoid(w^T x + b). Define binary cross-entropy loss: L = -[y log(p) + (1-y) log(1-p)].

2. Derive Gradient

Compute the gradient of the loss with respect to weights and bias. Show that ∂L/∂w = (p - y) x and ∂L/∂b = (p - y), justifying via chain rule.

3. Implement Mini-Batch Gradient Descent

Describe the algorithm: initialize weights, shuffle data, split into mini-batches, compute gradients on each batch, update weights with learning rate. Mention convergence checks.

4. Address Numerical Stability

Explain techniques: stable sigmoid (e.g., piecewise), log-sum-exp trick for log(1-p), clipping probabilities to avoid log(0), and using logits directly in loss computation.

5. Discuss Trade-offs and Extensions

Mention trade-offs: batch size vs. convergence speed, learning rate selection, regularization. Optionally, discuss extensions like L2 regularization or momentum.

Key Points to Mention

  • Binary cross-entropy is convex, ensuring convergence to global minimum with proper learning rate.
  • Gradient derivation: ∂L/∂w = (σ(w^T x + b) - y) x, which is intuitive and computationally efficient.
  • Mini-batch gradient descent balances computational efficiency and convergence stability.
  • Numerical stability: use logits in loss (e.g., softplus) to avoid overflow/underflow.
  • Avoid log(0) by adding epsilon or using stable implementations.
  • Regularization (L1/L2) can be added to prevent overfitting, especially with high-dimensional data.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q3

Build a Markov chain text generator: first a function that builds a frequency map from a corpus (word to next-word counts), then a function that generates text by always picking the most frequent next word.

Algorithms & Data Structures
Author's notes

The sanitisation step ate way more time than I expected.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clarifying the problem: define what a 'word' is (e.g., tokenization), whether to include punctuation, and how to handle the end of the corpus. Then outline the two functions: one to build the frequency map (a dictionary of dictionaries) and one to generate text by always picking the most frequent next word, handling ties and unknown words. Finally, discuss potential improvements like smoothing or using a more sophisticated model.

Pro tip: Mention that always picking the most frequent next word leads to deterministic, repetitive output, and that in practice you'd sample from the distribution or use beam search; this shows you understand the limitations and can think beyond the basic implementation.

1. Clarify requirements and edge cases

Ask about tokenization (e.g., split on whitespace, handle punctuation), case sensitivity, and how to handle the end of the corpus (e.g., add a special END token). Also consider empty corpus or unseen starting words.

2. Design the frequency map builder

Iterate through the tokenized corpus, and for each word, update a dictionary mapping the word to a dictionary of next-word counts. Use a defaultdict or similar for efficiency.

3. Design the text generator

Given a starting word, repeatedly look up the most frequent next word from the frequency map. Handle ties (e.g., pick the first or random among max) and stop when reaching an END token or max length.

4. Analyze complexity and potential improvements

Discuss time and space complexity: building the map is O(N) where N is corpus size; generation is O(L * V) where L is length and V is vocabulary size if naive max search. Suggest optimizations like storing max next word during map building or using a heap.

5. Test with examples and discuss limitations

Walk through a small example to verify correctness. Mention that greedy selection leads to repetitive loops and that real-world systems use probabilistic sampling or neural models.

Key Points to Mention

  • Tokenization and preprocessing steps (lowercasing, punctuation handling)
  • Data structure choice: dictionary of dictionaries for frequency map
  • Handling ties when multiple next words have the same max frequency
  • Time and space complexity of both functions
  • Edge cases: empty corpus, unseen starting word, end-of-corpus token
  • Limitations of greedy selection and alternatives like random sampling

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q4

Given N rider coordinates and a target K, find K pickup locations on a grid that minimize the total L1 distance from each rider to its nearest pickup point.

Algorithms & Data StructuresTechnical Trade-offsSystem Design
Author's notes

I knew the median trick for K=1 but fumbled explaining why it generalizes poorly to K>1.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clarifying the problem constraints and objective, then propose a solution using k-median clustering with L1 distance, leveraging the separability of L1 into x and y coordinates. Discuss algorithmic approaches (e.g., local search, approximation algorithms) and trade-offs between optimality and scalability, and consider system design aspects for real-time deployment.

Pro tip: Emphasize that L1 distance allows independent optimization of x and y coordinates, which can simplify the problem and enable efficient algorithms. Also, relate the solution to Uber's real-world needs, such as dynamic pickup location optimization and large-scale data processing.

1. Clarify Requirements and Constraints

Ask about the size of N, the grid dimensions, whether K is fixed, and if there are constraints like pickup capacity or time windows. Confirm the objective: minimize sum of L1 distances from each rider to nearest pickup.

2. Formulate as k-Median Problem

Recognize this as the k-median problem with L1 distance. Explain that it's NP-hard, so exact solutions are impractical for large N; thus, approximation or heuristic methods are needed.

3. Propose Algorithmic Approaches

Discuss options: local search (e.g., k-means style with L1), approximation algorithms (e.g., primal-dual), or leveraging separability of L1 to solve 1D k-median on x and y coordinates independently (if pickup points can be anywhere).

4. Analyze Trade-offs and Scalability

Compare time complexity, solution quality, and scalability. For large-scale data, consider distributed algorithms or sampling. Mention that L1 separability may not hold if pickups must be on grid points, requiring integer programming or heuristics.

5. Consider System Design and ML Integration

Discuss how to deploy the solution in a real-time system: data pipelines, incremental updates, and potential ML models to predict rider demand. Address evaluation metrics and A/B testing.

Key Points to Mention

  • k-median clustering with L1 distance
  • NP-hardness and need for approximation/heuristics
  • Separability of L1 distance into x and y coordinates
  • Local search algorithms (e.g., Lloyd's algorithm adapted for L1)
  • Scalability considerations for large N (distributed computing, sampling)
  • Real-world application at Uber: dynamic pickup location optimization

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q5

Implement multi-head self-attention as a PyTorch nn.Module from scratch, without calling nn.MultiheadAttention. Handle the reshape from (B, T, D) to (B, H, T, D_head), scaled dot-product scores, softmax, and the output projection.

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

The .contiguous() before the final view is the kind of thing that bites you silently in an interview.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by defining the module's __init__ to create linear projections for Q, K, V, and output, along with the number of heads and head dimension. Then implement the forward pass by projecting the input, reshaping to (B, H, T, D_head), computing scaled dot-product attention with masking, and finally projecting the concatenated heads back to the original dimension.

Pro tip: Mention that you would use a single linear layer for Q, K, V projections (or separate ones) and emphasize the importance of contiguous() before view() to avoid runtime errors. Also, discuss the trade-off between using einsum vs. explicit reshape and matmul for clarity and performance.

1. Define the module and projections

In __init__, store embed_dim, num_heads, and head_dim. Create nn.Linear layers for query, key, value, and output projections.

2. Project and reshape inputs

In forward, apply the linear projections to get Q, K, V of shape (B, T, D). Reshape them to (B, H, T, D_head) by splitting the last dimension and permuting.

3. Compute scaled dot-product attention

Compute scores = Q @ K.transpose(-2, -1) / sqrt(D_head). Apply optional mask, then softmax over the last dimension to get attention weights.

4. Apply attention and concatenate heads

Multiply attention weights by V to get output of shape (B, H, T, D_head). Transpose and reshape back to (B, T, D).

5. Output projection and return

Apply the final linear projection to the concatenated heads and return the result. Optionally return attention weights if needed.

Key Points to Mention

  • Scaling factor 1/sqrt(D_head) to prevent softmax saturation
  • Reshape from (B, T, D) to (B, H, T, D_head) using view and permute, ensuring contiguity
  • Masking (e.g., causal mask) applied before softmax to prevent attending to future tokens
  • Softmax over the last dimension (T) to get attention weights
  • Concatenation of heads and final output projection
  • Efficiency considerations: using batched matmul, avoiding loops, and handling variable sequence lengths

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q6

How would you add L2 regularization to both linear and logistic regression, and what changes in the gradient update?

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

Standard follow-up.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by defining L2 regularization as adding a penalty term λ||w||² to the loss function, then explain how this modifies the gradient by adding 2λw. For both linear and logistic regression, the weight update becomes w := w - α(∇L + 2λw), while the bias term is typically not regularized. Emphasize that this shrinks weights, reduces overfitting, and is equivalent to a Gaussian prior in a Bayesian framework.

Pro tip: Mention that L2 regularization is also known as weight decay and that in practice, the regularization strength λ is tuned via cross-validation; also note that the bias term is usually excluded from regularization because it doesn't contribute to overfitting.

1. Define L2 Regularization

Explain that L2 regularization adds a penalty term λ||w||² to the loss function, where λ controls the strength of regularization. This discourages large weights and helps prevent overfitting.

2. Modify the Loss Function

For linear regression, the regularized loss is MSE + λ||w||². For logistic regression, it is log-loss + λ||w||². Note that the bias term is typically not included in the penalty.

3. Derive the Gradient Update

Compute the gradient of the regularized loss: ∇L_reg = ∇L + 2λw. For linear regression, ∇L = (1/m) Xᵀ(Xw - y); for logistic regression, ∇L = (1/m) Xᵀ(σ(Xw) - y). The update rule becomes w := w - α(∇L + 2λw).

4. Discuss the Effect on Learning

Explain that the added term 2λw shrinks weights toward zero, reducing model complexity. This is equivalent to a Gaussian prior on weights in a Bayesian framework. Mention that λ is a hyperparameter tuned via cross-validation.

5. Address Practical Considerations

Note that feature scaling is important because L2 penalizes all weights equally. Also, mention that the bias term is usually not regularized, and that L2 is also known as weight decay or ridge regression.

Key Points to Mention

  • L2 regularization adds λ||w||² to the loss function, where λ is the regularization strength.
  • The gradient of the L2 penalty is 2λw, so the weight update becomes w := w - α(∇L + 2λw).
  • The bias term is typically not regularized because it doesn't contribute to overfitting.
  • L2 regularization is equivalent to a Gaussian prior on weights in a Bayesian framework.
  • Feature scaling is important because L2 penalizes all weights equally.
  • λ is a hyperparameter tuned via cross-validation, and L2 is also known as weight decay or ridge regression.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q7

Why does scaling attention scores by the square root of the head dimension matter?

Technical Trade-offsAlgorithms & Data Structures
Author's notes

Keeps the dot products from getting large as head_dim grows, which would push softmax into saturation and kill the gradients.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Explain that scaling by sqrt(d_k) prevents the dot products from growing too large in magnitude, which would push the softmax into regions with tiny gradients. Then connect this to training stability and the mathematical reasoning behind the variance of dot products.

Pro tip: Mention that without scaling, the softmax becomes saturated and gradients vanish, but also note that scaling is not strictly necessary if other normalization techniques are used—showing awareness of trade-offs.

1. Define the problem

State that in scaled dot-product attention, queries and keys are d_k-dimensional vectors, and their dot product can have high variance if not scaled.

2. Analyze variance

Explain that if query and key components are independent with mean 0 and variance 1, the dot product has mean 0 and variance d_k, so its standard deviation is sqrt(d_k).

3. Explain softmax saturation

Describe how large magnitude dot products cause the softmax to saturate, leading to extremely small gradients and hindering learning.

4. Show the fix

Scaling by 1/sqrt(d_k) normalizes the variance back to 1, keeping the softmax inputs in a reasonable range and preserving gradient flow.

5. Connect to practice

Mention that this scaling is a key component of the Transformer architecture and contributes to stable training, but also note that other techniques like layer normalization can mitigate similar issues.

Key Points to Mention

  • Variance of dot product grows with dimension d_k
  • Softmax saturation leads to vanishing gradients
  • Scaling by 1/sqrt(d_k) normalizes variance to 1
  • Preserves gradient flow during backpropagation
  • Empirical evidence from Transformer training stability
  • Trade-offs: scaling is not the only solution; normalization layers can also help

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.