Top Two Comments per Post by Likes with Recency Tie-Break

Last updated: November 29, 2026

Quick Overview

Given comments and comment likes as pandas DataFrames, return the top two visible comments for each post ranked by unique likes, breaking ties by newest comment first.

Meta
Data Manipulation (SQL/Python)
Software Engineer
Meta
November 29, 2026
Software Engineer
Online Assessment
Data Manipulation (SQL/Python)
Medium

0

0

0 solved


Given comments and comment likes as pandas DataFrames, return the top two visible comments for each post ranked by unique likes, breaking ties by newest comment first.

Ranked comment previews appear under posts throughout Facebook and Instagram, and Meta Python assessments use this to test top-N-per-group logic. The grader looks for deduplicated like counts, correct handling of zero-like comments, and a fully deterministic ordering.

What the Interviewer Expects
  • Filters hidden comments before ranking
  • Deduplicates likes on comment and user before counting
  • Keeps zero-like comments via a left join and fillna
  • Sorts by post, likes desc, created_at desc, id and uses cumcount for position
  • Returns at most k rows per post
Key Topics to Cover
top-N per group
groupby cumcount
deduplication
left join
deterministic ordering
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
  • How would the result change if you used rank(method='min') instead of cumcount, and when would you want that?
  • How would you weight likes from friends of the viewer more heavily?
  • How would you do this in SQL with a window function?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice SQL Problems
Sample Answer
Clarify the Data
  • comments: comment_id, post_id, author_id, created_at, is_hidden.
  • likes: comment_id, user_id, possibly with duplicate rows from client retries.

Only visible comments compete. A c...

Approach

Count unique (comment_id, user_id) pairs per comment, left-join counts onto visible comments with 0 for missing, then sort by post_id, likes descending, newest first, then comment_id as the fina...


Submit Your Answer
Markdown supported