Implement ROW_NUMBER, RANK and DENSE_RANK in Plain Python
Last updated: November 29, 2026
Quick Overview
Without pandas or SQL, write a Python function that takes a list of row dictionaries, a partition key and an order key, and returns each row annotated with its ROW_NUMBER, RANK and DENSE_RANK within its partition.
Meta
November 29, 20260
0
0 solved
Without pandas or SQL, write a Python function that takes a list of row dictionaries, a partition key and an order key, and returns each row annotated with its ROW_NUMBER, RANK and DENSE_RANK within its partition.
Meta data engineering and infra screens sometimes ask candidates to reimplement a SQL primitive to check they truly understand its semantics. The interviewer wants the three tie behaviors exactly right, a stable result for ties, and linear-ithmic complexity.
What the Interviewer Expects
- Groups rows by partition key in one pass
- Sorts each group by the order key with a stable sort
- Assigns row_number as position, rank as position of first tie, dense_rank as count of distinct values seen
- Preserves the original row order in the output
- States time and space complexity
Key Topics to Cover
How to Approach This
- Clarify the schema and expected output format before writing queries.
- Use CTEs (WITH clauses) to break complex queries into readable steps.
- Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
- Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
- For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
- How would you support multiple order keys with mixed ascending and descending directions?
- How would you implement NTILE(4) on top of this?
- How would you do this over a stream that does not fit in memory if rows arrive sorted by partition key?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice SQL ProblemsSample Answer
Clarify the Data
Input: a list of dicts such as {"page": "A", "post": "p1", "score": 17}. Output: the same rows, in the same order, each with row_number, rank, dense_rank added. Order is descending by default....
Approach
Bucket row indexes by partition. Sort each bucket by the order key; Python's sort is stable even with reverse=True, so ties keep their input order. Walk the sorted bucket: when the value changes, `r...