Top K Most Viewed Profiles With Alphabetical Tie Breaks
Last updated: November 29, 2026
Quick Overview
Given a list of profile view events (each a member id string) and an integer k, return the k most viewed member ids, ordered by view count descending and then by id ascending for ties.
0
0
0 solved
Given a list of profile view events (each a member id string) and an integer k, return the k most viewed member ids, ordered by view count descending and then by id ascending for ties.
A quick screen question modeled on the 'Who viewed your profile' and trending creators surfaces. The interviewer checks counting with a hash map, correct tie ordering, and whether you can explain when a size-k heap beats a full sort.
What the Interviewer Expects
- Counts views with a hash map or Counter
- Gets ordering right: count descending, id ascending
- Uses heapq.nsmallest with a composite key or a size-k heap
- Compares O(n log k) heap against O(n log n) sort
- Handles k larger than the number of distinct ids
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How do you do this over a sliding 24 hour window?
- How would you compute approximate top-k in a stream with bounded memory?
- How would you merge top-k results from many shards?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: views list of ids, k >= 0. Output: up to k ids. Ties on count are broken by lexicographically smaller id first. If there are fewer than k distinct ids, return all of them....
High-Level Design
Count with Counter. Then select the k smallest items under the key (-count, id), which is the same as the largest counts with ascending id ties. heapq.nsmallest keeps a heap of size k internally...