Skip to main content

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.

Coding rounds · Intermediate 1

Short answer

Sort by the timestamp, then drop duplicates on the id and keep the last one: df.sort_values("updated_at").drop_duplicates("user_id", keep="last"). The sort costs O(n log n). Make sure updated_at is a real datetime, and decide what to do with ties and missing timestamps.

Deeper answer

First clarify what latest means. Ask which column defines it, whether two rows for one user can share the same timestamp, and whether updated_at can be missing. Check the type: timestamps stored as text can sort in the wrong order.

The steps are: convert with pd.to_datetime(df["updated_at"]), then run df.sort_values("updated_at").drop_duplicates("user_id", keep="last"). After an ascending sort, the last row for each user is the newest one. For ties, add a second sort key, such as sort_values(["updated_at", "version"]), so the result is the same on every run. An alternative that avoids a full sort is df.loc[df.groupby("user_id")["updated_at"].idxmax()], which needs a unique index.

Watch missing timestamps: sort_values puts them last, so with keep="last" a row with no timestamp would win. Pass na_position="first" or drop those rows before sorting. Test a user with one row, tied timestamps and a missing timestamp, and check that the row count equals df["user_id"].nunique(). Say that this matches ROW_NUMBER() with ORDER BY updated_at DESC in SQL.

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

Tables with pandas

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.