Skip to main content

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.

Coding rounds · Intermediate 2

Short answer

In fit, build a dictionary from each training category to a column index, in sorted order. In transform, make a zero matrix of n rows by that many columns and set one cell per row. An unseen category has no index, so its row stays all zeros or goes to a reserved unknown column. Cost is O(n).

Deeper answer

Clarify first: is it one column of strings or several, how many distinct values exist, and what should happen with an unseen value: raise an error, ignore it, or map it to an unknown bucket?

Fit builds the mapping once from the training data, for example {v: i for i, v in enumerate(sorted(set(values)))}. Sorting makes the column order the same on every run. Transform creates out = np.zeros((n, len(mapping))) and for each row looks up j = mapping.get(v). If j exists, set out[row, j] = 1. If not, leave the row as zeros, or add one extra column at fit time for unknown values. The mapping must be saved with the model, so training and serving use the same columns.

Test that every known row sums to 1, that an unseen value does not crash, and that the output width is the same for any input. Interviewers watch for a new fit on the prediction data, which changes the column order, and for a KeyError on a new category.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Feature engineering

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.