Skip to main content

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.

Coding rounds · Intermediate 2

Short answer

Group the row indices by class. Shuffle each group with a seeded generator, send the first share of each group to test and the rest to train, then shuffle the combined train indices. Every class keeps its proportion. Cost is O(n), or O(n log n) if you sort to group.

Deeper answer

Clarify first: is this classification with a single label per row, what is the test share, and is a fixed seed wanted so the split can be repeated? Ask about very small classes, because a class with one row cannot be in both parts.

Work with indices, not copies of the data. For each class c, take idx = np.flatnonzero(y == c), shuffle it with rng.shuffle(idx), and send the first round(len(idx) * test_share) indices to test and the rest to train. Join the parts and shuffle the train indices once more, so the rows are not ordered by class. Then slice features and labels with the same index arrays so they stay aligned.

Test that train and test do not overlap, that together they cover every row, and that the class shares match within one row. Interviewers watch for a plain random split that leaves a rare class out of the test set, for no seed, and for rounding that gives a small class zero test rows.

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

Cross-validation and leakage

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.