Given a block of text, return the k most frequent words with their counts. For example, for "the cat sat, the cat ran, the end" and k = 2, return "the" with 3 and "cat" with 2.
Coding rounds · Intermediate 1
Short answer
Lower-case the text, split it into words with a regular expression, count with collections.Counter and call most_common(k). Counting is O(n) time for n words and O(u) memory for u unique words. most_common(k) uses a heap, so it costs about O(u log k) and does not sort everything.
Deeper answer
First clarify what a word is. Ask whether case matters, whether punctuation should be removed, and whether "don't" is one word. Ask how large the text is and what to return when k is larger than the number of unique words.
Then say the steps. Extract words with re.findall(r"[a-z']+", text.lower()), which lower-cases the text, drops punctuation and keeps apostrophes. Count and rank in one line: Counter(words).most_common(k). Without Counter, use a dict with counts[word] = counts.get(word, 0) + 1 and then sorted(counts.items(), key=lambda item: -item[1])[:k].
Counting is O(n). A full sort is O(u log u), where u is the number of unique words. Test empty text, k of zero, ties and text with only punctuation. Say that most_common keeps first-seen order for ties, and ask if ties need alphabetical order. For a very large file, read line by line and update the same Counter.
What a strong answer covers
- Clarifies what counts as a word: case, punctuation and apostrophes
- Extracts words with a regular expression, not a plain split on spaces
- Counts with Counter or a dict
- Gets the top k with most_common instead of sorting by hand
- States O(n) time and memory that grows with unique words
Answer it out loud in the mock interview about 2.5 min
Follow-ups to expect
- How would you break ties so the result is the same on every run?
- How does this change if the text is a 10 GB file?
- How would you ignore common words such as "the" and "is"?
Common mistakes
- Splitting on spaces only, so "cat." and "cat" are counted as different words
- Forgetting to lower-case the text
- Sorting every word when only the top k are needed
Learn it
- An embedding API accepts at most 100 texts per request. Split a list of texts into batches of that size. For example, 250 texts become three batches of 100, 100 and 50.
- Implement beam search: given a function that returns next-token probabilities for a partial sequence, return the most likely sequence found with a given beam width. For example, if the first token is A with 0.6 or B with 0.4, the best token after A has 0.5, and C after B has 0.9, then greedy search ends at 0.30 and a beam of width 2 finds B C at 0.36.
- Given a tokenised query and a small list of tokenised documents, score each document with BM25, using k1 = 1.5 and b = 0.75. For example, with the documents cat sat mat, dog sat and cat cat ran far away, the query cat should score the third document highest (about 0.58), the first next (about 0.49) and the second 0.
- Implement one merge step of byte-pair encoding training: given words split into symbols with their counts, find the most frequent adjacent pair and merge it everywhere. For example, with low 5, lower 2, newest 6 and widest 3, the pairs (e, s) and (s, t) both appear 9 times, and merging (e, s) turns newest into n e w es t.
- Write a function that splits a list of tokens into chunks of a fixed size, where each chunk shares some tokens with the one before it. For example, tokens 1 to 10 with size 4 and overlap 1 should give 1 to 4, 4 to 7 and 7 to 10.
- Build a confusion matrix for a classifier with k classes, given integer true labels and predicted labels. For example, true labels 0, 0, 1, 2, 2, 2 and predictions 0, 1, 1, 2, 2, 0 give the rows (1, 1, 0), (0, 1, 0) and (1, 0, 2), with true classes as rows.
- Given a matrix of document vectors and one query vector, return the k documents with the highest cosine similarity. For example, with documents (1, 0), (0, 1) and (1, 1), query (1, 0) and k = 2, return document 0 with score 1.0, then document 2 with score about 0.71.
- Remove duplicates from a list of email addresses and keep the order in which each address first appeared. For example, a@x.com, b@x.com, a@x.com, c@x.com becomes a@x.com, b@x.com, c@x.com.
- Flatten a nested JSON object into one level, joining the keys with dots. For example, a user object with name Asha and an address object with city Pune becomes user.name = Asha and user.address.city = Pune.
- Group the words in a list that are anagrams of each other. For example, listen, silent, enlist, cat, act, dog becomes three groups: listen, silent and enlist; cat and act; and dog alone.
- Implement softmax so that it does not overflow on large inputs. For example, the logits 1, 2, 3 should give about 0.09, 0.24, 0.67, and the logits 1000, 1001, 1002 should give the same answer, not NaN.
- Implement k-fold cross-validation without a library: return the train and validation indices for each fold. For example, 10 rows and k = 3 should give validation folds of sizes 4, 3 and 3, and every row should be in a validation fold exactly once.
- Implement k-means clustering in NumPy: given n points and k, return the centroids and a cluster label for each point. For example, the points 1, 2, 10 and 11 with k = 2 should end with centroids 1.5 and 10.5.
- Implement a k-nearest-neighbours classifier in NumPy: given labelled training points and a query point, predict the class of the query. For example, with class 0 points near (0, 0), class 1 points near (5, 5) and k = 3, the query (0.5, 0.5) should be class 0.
- Implement linear regression trained with batch gradient descent in NumPy. For example, on data generated from y = 2x + 3 with a little noise, the weight should end close to 2 and the bias close to 3.
- Write one training step of logistic regression in NumPy: given X, y, the weights and a learning rate, return the loss and the updated weights. For example, with all weights at zero, every predicted probability is 0.5 and the loss is ln 2, about 0.693.
- Explain a least-recently-used cache and implement a small one with get and put. For example, with capacity 2, after put a, put b, get a, put c, the key b is removed because it was used least recently.
- Given a list of GPU booking slots as start and end hours, merge the slots that overlap. For example, 9 to 10, 9.5 to 11 and 13 to 14 becomes 9 to 11 and 13 to 14.
- Write min-max scaling and standard scaling for a feature matrix, and show how to apply them to train and test data without leakage. For example, a training column 1, 2, 3 and a test value 4 gives a min-max test value of 1.5, because the minimum and range come from training only.
- Write a simple check that compares a reference window and a current window of one numeric feature and flags drift. For example, if the reference has mean 100 and standard deviation 10, and 400 current rows have mean 102, the shift is 4 standard errors and should be flagged.
- Implement one-hot encoding with a fit step and a transform step, and handle a category at prediction time that was not in the training data. For example, fit on red, green, red, blue, then transform green and purple: with columns blue, green, red, green becomes (0, 1, 0) and purple becomes all zeros.
- A table of user profile updates has user_id, plan and updated_at, with several rows per user. Keep only the latest row for each user. For example, if user 1 has rows from January and March, keep the March row.
- From an orders table with city, order_id and amount, return the 2 largest orders in each city. For example, if Pune has orders of 500, 900 and 700, keep the 900 and 700 rows.
- A 40 GB CSV of transactions does not fit in memory. Compute the average amount per city with pandas. For example, the result should be one row per city with its mean amount, the same as if the whole file had been loaded.
- You have an orders table and a customers table that share customer_id. Join them and list the orders that have no matching customer. For example, if order 3 has customer_id 99 and no customer has that id, order 3 should be in the result.
- A sales table has one row per store and month with a sales value. Turn it into a wide table with one row per store and one column per month. For example, rows S1 Jan 10 and S1 Feb 20 become one S1 row with Jan = 10 and Feb = 20.
- From a transactions table with customer_id, date and amount, compute a 7-day rolling average of daily spend for each customer. For example, a customer who spends 100, 200 and 300 on three days in a row has a rolling average of 200 on the third day.
- A 20 GB server log has one request per line with date, time, method, path and status code. Count the 500 errors per path without loading the file into memory. For example, three lines with status 500, two for /predict and one for /health, give /predict 2 and /health 1.
- Given two lists of 0 and 1, the true labels and the predictions, compute precision, recall and F1 without a library. For example, labels 1, 1, 1, 0, 0 and predictions 1, 1, 0, 1, 0 give precision 2/3, recall 2/3 and F1 2/3.
- Given, for each test question, the ranked list of retrieved ids and the set of relevant ids, compute recall at k and mean reciprocal rank. For example, if the only relevant document is at position 2, recall at 1 is 0, recall at 3 is 1, and the reciprocal rank is 0.5.
- Combine two ranked lists of document ids, one from keyword search and one from vector search, into one list with reciprocal rank fusion. For example, the lists a, b, c and b, d, a with the constant 60 should give the order b, a, d, c.
- Write a function that calls a model API and retries with exponential backoff when the call fails with a rate-limit or server error. For example, with 4 tries and a 1 second base, it waits about 1, 2 and 4 seconds between tries and then raises the last error.
- Compute ROC AUC from a list of model scores and a list of 0 and 1 labels, without a library. For example, scores 0.1, 0.4, 0.35, 0.8 with labels 0, 0, 1, 1 give 0.75, because 3 of the 4 pairs of one positive and one negative are ranked correctly.
- Implement single-head scaled dot-product self-attention in NumPy for one sequence. For example, an input of 4 tokens with 8 features each should return 4 output vectors, and each row of the attention weights should sum to 1.
- Write a rate limiter that allows each user at most 3 requests in any 60 second window. For example, requests at seconds 0, 10 and 20 are allowed, a request at second 30 is rejected, and a request at second 60 is allowed again.
- From an events table with user_id and event_date, compute daily active users and a 7-day moving average of that number. For example, if two different users have events on 1 November, the daily active users for that day is 2, even if one of them has five events.
- You join an orders table to a payments table on order_id to report revenue, and the total is too high because the row count grew. Explain why and fix it. For example, an order of 100 that was paid in two parts appears twice, so its amount is counted as 200.
- You have a users table with signup_date and an events table with user_id and event_date. Compute weekly retention by signup cohort: for each signup week, the share of users active in week 0, week 1, week 2 and so on. For example, if 3 users signed up in one week and 2 of them were active the following week, week 1 retention for that cohort is 67 percent.
- From an orders table with order_id, customer_id, order_date and amount, show each order with the running total of that customer's spend so far. For example, a customer with orders of 100, 50 and 25 gets running totals of 100, 150 and 175.
- From an employees table with name, department and salary, return the second highest salary in each department. For example, if engineering has salaries 100, 100, 90 and 80, the answer for engineering is 90.
- Given a vector of logits, sample one token id using a temperature and top-p (nucleus) sampling. For example, if the probabilities after temperature are 0.5, 0.3, 0.15 and 0.05 and top-p is 0.7, only the first two tokens can be chosen, with probabilities 0.625 and 0.375.
- Write a train and test split that keeps the class balance the same in both parts, without a library. For example, with 80 rows of class 0, 20 rows of class 1 and a test share of 0.2, the test set should hold 16 rows of class 0 and 4 rows of class 1.
- Given a list of integers and a target, return every unique pair of values that adds up to the target. For example, for 2, 7, 4, 5, 7, 2 and target 9, return the pairs 2 and 7, and 4 and 5.
- A model is asked to return JSON with a sentiment label and a score from 0 to 1 for a product review. Parse and validate the reply, and say what you do when it is malformed. For example, a reply wrapped in a code fence should parse, and a reply with sentiment "happy" should be rejected.