Skip to main content

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.

Coding rounds · Intermediate 1

Short answer

Sort by amount descending, then take the first n rows of each group: df.sort_values("amount", ascending=False).groupby("city").head(2). It keeps all columns. The sort makes it O(n log n). Use rank with method="dense" instead when tied values should all be kept.

Deeper answer

First clarify the output. Ask whether you want whole rows or only the values, what to do with ties at the cut-off, and whether a city with fewer than n orders should still appear. Check for missing amounts.

The main approach is df.sort_values("amount", ascending=False).groupby("city").head(2). After the sort, head(2) keeps the first two rows of every city and keeps every column. A city with one order returns one row. Ties are cut at exactly two rows, by sort order. When ties must all be kept, filter on a rank: df[df.groupby("city")["amount"].rank(method="dense", ascending=False) <= 2]. If only the values are needed, df.groupby("city")["amount"].nlargest(2) returns a Series.

The sort costs O(n log n). Test a city with one order, tied amounts and a missing amount, which sort_values puts last. Say that this is the pandas form of ROW_NUMBER() OVER (PARTITION BY city ORDER BY amount DESC) in SQL, and add a second sort column such as order_id when the result must be the same on every run.

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.