BasicsPandasSortingMetaAmazonUber
Problem
Implement top_k_products(df, k) returning the top k rows sorted by price descending, breaking ties by name ascending, with a reset 0-based index.
Why It Matters: Top-K ranking with deterministic tie-breaking is essential for leaderboards, recommendation feeds, and reproducible SQL/Pandas interviews.
Function Signature
import pandas as pd
def top_k_products(df: pd.DataFrame, k: int) -> pd.DataFrame:
Sample Input & Output
Example 1: Top 2 With Price Tie-Break
Input:
| name | price |
|---|---|
| Desk | 200 |
| Chair | 200 |
| Lamp | 50 |
| Monitor | 350 |
Parameter: 2 |
Expected Output:
| name | price |
|---|---|
| Monitor | 350 |
| Chair | 200 |
Explanation: Monitor (350) is #1; Chair and Desk tie at 200, so 'Chair' beats 'Desk' alphabetically.
Example 2: k Larger Than Row Count
Input:
| name | price |
|---|---|
| Pen | 5 |
| Book | 15 |
Parameter: 5 |
Expected Output:
| name | price |
|---|---|
| Book | 15 |
| Pen | 5 |
Explanation: Returns all available rows sorted properly when k > len(df).
Constraints & Edge Cases
- Break price ties by
nameascending. - Pass
ascending=[False, True]tosort_values(['price', 'name'], ...). - Reset the index with
drop=True.
Constraints & Evaluation Criteria
- Break price ties by `name` ascending.
Hints
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
4 products, k=2
Expected Output / Criteria
Highest priced 2 rows