Coders Crushby Napplied AI
Back to DSA Problems
HardTries

Autocomplete System

Implement autocomplete

Solution Approach

Track frequency of sentences. For each input, find top 3 matches by frequency and lexicographic order.

Implementation
class AutocompleteSystem:
    def __init__(self, sentences, times):
        self.trie = {}
        self.current = ""
        self.freq = {}
        
        for s, t in zip(sentences, times):
            self.freq[s] = t
    
    def input(self, c):
        if c == "#":
            self.freq[self.current] = self.freq.get(self.current, 0) + 1
            self.current = ""
            return []
        
        self.current += c
        res = sorted([s for s in self.freq if s.startswith(self.current)], 
                     key=lambda x: (-self.freq[x], x))
        return res[:3]
Complexity Analysis

Time Complexity

O(n*log n)

Space Complexity

O(n)
Complexity
Time:O(n*log n)
Space:O(n)
Asked at
GoogleAmazon
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless