Sort Table by Price Descending & Take Top-K

Basics
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:

nameprice
Desk200
Chair200
Lamp50
Monitor350
Parameter: 2

Expected Output:

nameprice
Monitor350
Chair200

Explanation: Monitor (350) is #1; Chair and Desk tie at 200, so 'Chair' beats 'Desk' alphabetically.

Example 2: k Larger Than Row Count

Input:

nameprice
Pen5
Book15
Parameter: 5

Expected Output:

nameprice
Book15
Pen5

Explanation: Returns all available rows sorted properly when k > len(df).

Constraints & Edge Cases

  • Break price ties by name ascending.
  • Pass ascending=[False, True] to sort_values(['price', 'name'], ...).
  • Reset the index with drop=True.

Constraints & Evaluation Criteria

  • Break price ties by `name` ascending.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
4 products, k=2
Expected Output / Criteria
Highest priced 2 rows