Uber L5A Interview Experience

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-03-18

Problem Statement

Design a system to track the Top K most frequent elements from a data stream, under limited memory constraints.

📌 Requirements:

✅ Functional Requirements:

1.The system should support continuous ingestion of elements (streaming input).
2.It should always be able to return the top K most frequent elements seen so far.
3.The system should use limited memory and not store the entire stream.
4.Operations supported:
•insert(element: T) — Process a new element in the stream.
•getTopK() -> List<T> — Return top K frequent elements.

⚠️ Non-Functional Requirements:

•Handle very large streams (possibly unbounded).
•Should be memory efficient (cannot store all elements or counts for all).
•Should support real-time updates (low latency insertions).
•Thread safety (optional depending on system complexity).

🧠 Constraints:

•K is much smaller than the total unique elements.
•Limited RAM (e.g., fixed-size heap or map).
•The stream may include integers, strings, or custom types (with hashing support).

💡 LLD Concepts Involved:

•Min-Heap / Priority Queue
•HashMap for frequency tracking
•Space-efficient algorithms (e.g., Count-Min Sketch for approximation)
•Possibly use eviction strategies (e.g., if memory bound is exceeded)

🛠️ Approach (Exact if possible, else Approximate):

✅ Approach 1: HashMap + Min-Heap (if number of distinct elements is manageable)

•Use a HashMap to track frequency of elements.
•Use a Min-Heap of size K to keep the current top K.
•On each insertion:
•Increment frequency in HashMap.
•If element is in heap, reheapify.
•If not in heap and frequency > min, replace the heap root.

✅ Approach 2: Count-Min Sketch (Approximate, good for memory efficiency)

•Use Count-Min Sketch to approximate frequencies using multiple hash functions.
•Maintain a Min-Heap of size K.
•Periodically query frequencies and update heap accordingly.
•Greatly reduces memory footprint with tradeoff in accuracy.

📦 Data Structures:

•class StreamProcessor<T>
•insert(element: T): void
•getTopK(): List<T>

🔁 Sample Usage:

1python 2CopyEdit 3sp = StreamProcessor(k=3) 4sp.insert("apple") 5sp.insert("banana") 6sp.insert("apple") 7sp.insert("cherry") 8sp.insert("banana") 9sp.insert("banana") 10top_k = sp.getTopK() # → ['banana', 'apple', 'cherry']


Solution

Comments