Level: Mid-Level
Round: Phone Screen · Type: Coding · Difficulty: 7/10 · Duration: 60 min · Interviewer: Unfriendly
Topics: Data Structures, Hash Table, System Design, Concurrency
Location: San Francisco, CA
Interview date: 2025-12-31
I had a technical phone interview where I was asked to implement a Counter class. The elements inserted into the counter have an expiration time set during initialization.
The class needs to implement three functions:
put(element): Adds an element to the counter.get_count(element): Returns the current valid count of the element in the counter.get_total_count(): Returns the current count of all valid elements in the counter.For example:
counter(window=10) time 1: counter.put(‘a’) time 3: counter.put(‘a’) time 5: counter.put(‘b’) time 6: counter.get_count(‘a’) -> 2 time 6: counter.get_total_count() -> 3 time 12: counter.get_count(‘a’) -> 1 time 12: counter.get_total_count() -> 2
The coding question I got was to implement a Counter class with expiration:
`python class Counter: def init(self, window): self.window = window self.data = {}
def put(self, element):
current_time = time.time()
if element in self.data:
self.data[element].append(current_time)
else:
self.data[element] = [current_time]
def get_count(self, element):
current_time = time.time()
if element not in self.data:
return 0
valid_times = [t for t in self.data[element] if current_time - t <= self.window]
return len(valid_times)
def get_total_count(self):
current_time = time.time()
total_count = 0
for element in self.data:
valid_times = [t for t in self.data[element] if current_time - t <= self.window]
total_count += len(valid_times)
return total_count
`
My approach:
put function adds the element with the current timestamp.get_count function filters the timestamps within the window.get_total_count function iterates through all elements and sums their valid counts.Follow-up: The follow-up question asked about handling a million inputs per second. I suggested using batch aggregation to update the state every second, employing a queue with lazy deletion.