Implement n-gram model and select n
RunwayMachine Learning Engineer · Technical ScreenLast updated
This interview question evaluates core ML concepts, assumptions, math intuition, training/evaluation trade-offs, and practical failure modes in a realistic interview setting. A strong answer for Implement n-gram model and select n states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Implement an n-gram language model class with fit and generate methods. The fit(file_path, n) method should read a text file, tokenize consistently, build n-gram and (n− 1)-gram frequency counts, and compute conditional probabilities with smoothing (e.g., add-k or Kneser–Ney). The generate(start_tokens, max_len, sampling_strategy) method should sample next tokens according to learned probabilities (e.g., multinomial, top-k, or temperature) to produce text. Discuss how to select the optimal n given data size and domain: propose validation procedures (e.g., train/validation split), metrics (perplexity), regularization/backoff or interpolation, and analyze the time/space complexity and memory footprint for different n values.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.