Counter That Returns Any Top or Bottom Trending Key in Constant Time

Last updated: November 29, 2026

Quick Overview

Design a structure with inc(key), dec(key), get_max_key() and get_min_key(), all in O(1). dec on a key with count 1 removes it, and the getters return any key with the extreme count or an empty string.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Design a structure with inc(key), dec(key), get_max_key() and get_min_key(), all in O(1). dec on a key with count 1 removes it, and the getters return any key with the extreme count or an empty string.

Trending hashtag widgets need both the hottest and coldest tracked terms instantly as counts tick up and down. This is a known hard Meta design question: the interviewer wants the doubly linked list of count buckets and careful pointer surgery at bucket boundaries.

What the Interviewer Expects
  • Reject heaps and sorted maps because they are O(log n)
  • Use a doubly linked list of buckets sorted by count
  • Store the set of keys in each bucket
  • Create and delete neighbor buckets only when needed
  • Use sentinels to remove special cases
  • Prove counts change by exactly one, which keeps neighbors adjacent
Key Topics to Cover
Doubly linked list
Hash map
Bucketing
Data structure design
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you return all keys tied for the max?
  • What if inc can add an arbitrary amount instead of one?
  • How would you support get_kth_largest_count efficiently?
Sharpen Your Skills on Codemia

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

Practice DSA Problems
Sample Answer
Requirements
  • inc(key) adds 1, inserting the key with count 1 if new.
  • dec(key) subtracts 1, removing the key at 0; ignore unknown keys.
  • get_max_key and get_min_key return any extreme key, or "" when...
High-Level Design

Because counts move by exactly one, a key only ever jumps to an adjacent bucket. Maintain a doubly linked list of buckets in increasing count order, between head and tail sentinels, and a map from key...


Submit Your Answer
Markdown supported