Interview questions · Meta
Implement string and basic ML algorithms
This question evaluates proficiency in algorithmic string processing and implementation of foundational machine learning models, covering skills such as designing an efficient distinct-character substring algorithm, implementing binary logistic regression training and prediction, and building a multinomial Naive Bayes text classifier.
You are given three implementation tasks that mix algorithms and basic machine learning models.
Task 1: Longest substring with all distinct characters
Given a string s consisting of ASCII characters, find the length of the longest contiguous substring in which all characters are distinct (no character appears more than once within that substring).
- Input: a single string
s. - Output: an integer representing the maximum length of any substring of
sthat has all unique characters.
Example:
s = abcabcbb→ the answer is3(one such substring isabc).s = bbbbb→ the answer is1(any singleb).s = ""(empty string) → the answer is0.
Constraints (typical):
0 <= len(s) <= 10^5- Expected time:
O(n)wheren = len(s) - Expected extra space:
O(min(n, alphabet_size))
Implement a function with a signature similar to:
int longestDistinctSubstringLength(const string& s)(C++), orint longest_distinct_substring_length(string s)(Python-style pseudocode).
Task 2: Implement binary logistic regression from scratch
Implement a binary logistic regression classifier without using any machine learning libraries.
Design a class LogisticRegression that supports:
-
Constructor: takes at least:
learning_rate: floatnum_iterations: int
-
fit(X, y):
Xis ann x dnumeric matrix of features (e.g., list of lengthn, each element a length-dlist of floats).yis a length-nlist/array of labels, each label is either0or1.- Initialize weights and bias (e.g., to zeros).
- Train using batch gradient descent to minimize the logistic (cross-entropy) loss:
- Model: for each sample
i, computez_i = w · x_i + b, then probability of class 1 isp_i = sigmoid(z_i) = 1 / (1 + exp(-z_i)). - Loss over the dataset:
- Model: for each sample
- Update `w` and `b` with gradient descent for `num_iterations` steps.
-
No regularization is required.
-
predict_proba(X):
- Given a feature matrix
X, return a list/array of predicted probabilitiesp_ifor class1for each row.
- Given a feature matrix
-
predict(X):
- Given
X, first compute probabilities withpredict_proba, then convert to labels0or1using threshold0.5.
- Given
Constraints (typical):
n(number of samples) up to about10^4.d(number of features) up to about10^2.- Number of iterations up to around
10^4.
You may implement in any language, but do not use built-in ML training utilities.
Task 3: Implement a multinomial Naive Bayes text classifier
Implement a multinomial Naive Bayes classifier for text classification.
Assume:
- Training data:
docs_train, a list of documents, where each document is represented as a list of token strings, e.g.[["this", "movie", "is", "great"], ["awful", "film"], ...]. - Training labels:
y_train, a list of integers wherey_train[i]is the class index fordocs_train[i](values in{0, 1, ..., C-1}). - Test data:
docs_test, same format asdocs_trainbut without labels.
Design a class NaiveBayes that supports:
- fit(docs_train, y_train):
- Build a vocabulary of all tokens seen in
docs_train. - Let
Cbe the number of classes. - Estimate class prior probabilities:
- Build a vocabulary of all tokens seen in
- For each class
cand tokenwin the vocabulary, estimate conditional probabilities with Laplace smoothing (add-one smoothing):
where `V` is the vocabulary size.
-
Store log probabilities (
log P(y = c)andlog P(w | y = c)) to avoid underflow. -
predict(docs_test):
- For each document, treat it as a bag of words.
- For each class
c, compute the log posterior up to a constant:
- Predict the class
cwith the highest log score. - Ignore tokens not in the training vocabulary (or handle them with an appropriate strategy such as skipping them).
Constraints (typical):
- Number of documents up to a few
10^4. - Vocabulary size up to a few
10^4. - Must be efficient in both time and memory.
Focus on correctly implementing the core training (fit) and prediction (predict) logic; you do not need to handle file I/O or text preprocessing (assume tokenization is already done).
Community answers
Nothing here yet.
Join in on CSWork →