KatInterview

642. Design Search Autocomplete System

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of this problem is to design a data structure that can efficiently perform two main operations:

Solution

Design Search Autocomplete System in Python

class AutocompleteSystem:

    def __init__(self, sentences: List[str], times: List[int]):
        self.root = {}
        self.current_input = []
        self.current_node = self.root

        for sentence, time in zip(sentences, times):
            self._insert(sentence, time)

    def _insert(self, sentence: str, time: int):
        node = self.root
        for char in sentence:
            if char not in node:
                node[char] = {}
            node = node[char]
            self._update_hot_list(node, sentence, time)
        node['#_times'] = time  # Using a special key for times

    def _update_hot_list(self, node: dict, sentence: str, time: int):
        if 'hot_list' not in node:
            node['hot_list'] = []

        found = False
        for i, (t, s) in enumerate(node['hot_list']):
            if s == sentence:
                node['hot_list'][i] = (-time, sentence)
                found = True
                break
        
        if not found:
            node['hot_list'].append((-time, sentence))
        
        node['hot_list'].sort()

        if len(node['hot_list']) > 3:
            node['hot_list'].pop()

    def input(self, c: str) -> List[str]:
        if c == '#':
            sentence = "".join(self.current_input)
            
            # Find old times
            node = self.root
            for char in sentence:
                if char not in node:
                    node[char] = {}
                node = node[char]
            
            new_time = node.get('#_times', 0) + 1
            node['#_times'] = new_time
            
            # Update hot lists
            node = self.root
            for char in sentence:
                node = node[char]
                self._update_hot_list(node, sentence, new_time)

            # Reset
            self.current_input = []
            self.current_node = self.root
            return []
        else:
            self.current_input.append(c)
            if self.current_node is not None:
                self.current_node = self.current_node.get(c, None)
            
            if self.current_node is None:
                return []
            
            hot_list = self.current_node.get('hot_list', [])
            return [s for t, s in hot_list]

Design Search Autocomplete System in Java

class AutocompleteSystem {

    // Pair class to hold sentence and its frequency, comparable for sorting.
    class Pair implements Comparable<Pair> {
        String sentence;
        int times;

        Pair(String sentence, int times) {
            this.sentence = sentence;
            this.times = times;
        }

        @Override
        public int compareTo(Pair other) {
            if (this.times == other.times) {
                return this.sentence.compareTo(other.sentence);
            }
            return Integer.compare(other.times, this.times);
        }
    }

    // TrieNode for the prefix tree.
    class TrieNode {
        Map<Character, TrieNode> children = new HashMap<>();
        int times = 0; // Frequency of sentence ending at this node
        List<Pair> hotList = new ArrayList<>(); // Top 3 sentences through this node
    }

    private TrieNode root;
    private TrieNode currentNode;
    private StringBuilder currentInput;

    // Updates the hot list of a node with a new or updated sentence.
    private void updateHotList(TrieNode node, String sentence, int newTimes) {
        boolean found = false;
        for (Pair p : node.hotList) {
            if (p.sentence.equals(sentence)) {
                p.times = newTimes;
                found = true;
                break;
            }
        }
        if (!found) {
            node.hotList.add(new Pair(sentence, newTimes));
        }

        Collections.sort(node.hotList);

        if (node.hotList.size() > 3) {
            node.hotList.remove(3);
        }
    }

    // Inserts a sentence into the Trie and updates hot lists along the path.
    private void insert(String sentence, int times) {
        TrieNode node = root;
        for (char c : sentence.toCharArray()) {
            node.children.putIfAbsent(c, new TrieNode());
            node = node.children.get(c);
            updateHotList(node, sentence, times);
        }
        node.times = times;
    }

    public AutocompleteSystem(String[] sentences, int[] times) {
        root = new TrieNode();
        currentNode = root;
        currentInput = new StringBuilder();

        for (int i = 0; i < sentences.length; i++) {
            insert(sentences[i], times[i]);
        }
    }
    
    public List<String> input(char c) {
        if (c == '#') {
            // End of sentence. Add/update it in the system.
            String sentence = currentInput.toString();
            
            // Find the node to get old times, create path if needed.
            TrieNode node = root;
            for (char ch : sentence.toCharArray()) {
                node.children.putIfAbsent(ch, new TrieNode());
                node = node.children.get(ch);
            }
            int newTimes = node.times + 1;
            node.times = newTimes;
            
            // Update hot lists along the path with the new frequency.
            node = root;
            for (char ch : sentence.toCharArray()) {
                node = node.children.get(ch);
                updateHotList(node, sentence, newTimes);
            }

            // Reset for the next input.
            currentInput.setLength(0);
            currentNode = root;
            return new ArrayList<>();
        } else {
            currentInput.append(c);
            if (currentNode != null) {
                currentNode = currentNode.children.get(c);
            }

            if (currentNode == null) {
                return new ArrayList<>();
            }

            List<String> result = new ArrayList<>();
            for (Pair p : currentNode.hotList) {
                result.add(p.sentence);
            }
            return result;
        }
    }
}

Design Search Autocomplete System in C++

class AutocompleteSystem {
private:
    struct TrieNode {
        unordered_map<char, TrieNode*> children;
        int times = 0;
        // We store pairs of {-times, sentence} to sort by times descending, then sentence ascending.
        vector<pair<int, string>> hot_list;
    };

    TrieNode* root;
    TrieNode* current_node;
    string current_input;

    void insert(const string& s, int times) {
        TrieNode* node = root;
        for (char c : s) {
            if (node->children.find(c) == node->children.end()) {
                node->children[c] = new TrieNode();
            }
            node = node->children[c];
            update_hot_list(node, s, times);
        }
        node->times = times;
    }

    void update_hot_list(TrieNode* node, const string& s, int t) {
        bool found = false;
        for (auto& p : node->hot_list) {
            if (p.second == s) {
                p.first = -t;
                found = true;
                break;
            }
        }
        if (!found) {
            node->hot_list.push_back({-t, s});
        }

        sort(node->hot_list.begin(), node->hot_list.end());

        if (node->hot_list.size() > 3) {
            node->hot_list.pop_back();
        }
    }

public:
    AutocompleteSystem(vector<string>& sentences, vector<int>& times) {
        root = new TrieNode();
        current_node = root;
        current_input = "";

        for (int i = 0; i < sentences.size(); ++i) {
            insert(sentences[i], times[i]);
        }
    }
    
    vector<string> input(char c) {
        if (c == '#') {
            // End of sentence. Update the Trie.
            TrieNode* node = root;
            for (char ch : current_input) {
                if (node->children.find(ch) == node->children.end()) {
                    node->children[ch] = new TrieNode();
                }
                node = node->children[ch];
            }
            int new_times = node->times + 1;
            insert(current_input, new_times);
            
            // Reset for the next input
            current_input = "";
            current_node = root;
            return {};
        }

        current_input += c;
        if (current_node) {
            if (current_node->children.find(c) == current_node->children.end()) {
                current_node = nullptr;
            } else {
                current_node = current_node->children[c];
            }
        }
        
        if (!current_node) {
            return {};
        }

        vector<string> result;
        for (const auto& p : current_node->hot_list) {
            result.push_back(p.second);
        }
        return result;
    }
};

Design Search Autocomplete System in TypeScript

class AutocompleteSystem {
    private root: TrieNode;
    private currentNode: TrieNode | null;
    private currentInput: string;

    constructor(sentences: string[], times: number[]) {
        this.root = new TrieNode();
        this.currentNode = this.root;
        this.currentInput = "";

        for (let i = 0; i < sentences.length; i++) {
            this.insert(sentences[i], times[i]);
        }
    }

    private insert(sentence: string, times: number): void {
        let node = this.root;
        for (const char of sentence) {
            if (!node.children.has(char)) {
                node.children.set(char, new TrieNode());
            }
            node = node.children.get(char)!;
            this.updateHotList(node, sentence, times);
        }
        node.times = times;
    }

    private updateHotList(node: TrieNode, sentence: string, newTimes: number): void {
        let found = false;
        for (const pair of node.hotList) {
            if (pair.sentence === sentence) {
                pair.times = newTimes;
                found = true;
                break;
            }
        }
        if (!found) {
            node.hotList.push({ sentence, times: newTimes });
        }

        node.hotList.sort((a, b) => {
            if (a.times === b.times) {
                return a.sentence.localeCompare(b.sentence);
            }
            return b.times - a.times;
        });

        if (node.hotList.length > 3) {
            node.hotList.pop();
        }
    }

    input(c: string): string[] {
        if (c === '#') {
            const sentence = this.currentInput;
            
            let node = this.root;
            for (const char of sentence) {
                if (!node.children.has(char)) {
                    node.children.set(char, new TrieNode());
                }
                node = node.children.get(char)!;
            }
            const newTimes = node.times + 1;
            node.times = newTimes;

            node = this.root;
            for (const char of sentence) {
                node = node.children.get(char)!;
                this.updateHotList(node, sentence, newTimes);
            }

            this.currentInput = "";
            this.currentNode = this.root;
            return [];
        } else {
            this.currentInput += c;
            if (this.currentNode) {
                this.currentNode = this.currentNode.children.get(c) || null;
            }

            if (!this.currentNode) {
                return [];
            }
            return this.currentNode.hotList.map(p => p.sentence);
        }
    }
}

interface HotPair {
    sentence: string;
    times: number;
}

class TrieNode {
    children: Map<string, TrieNode>;
    times: number;
    hotList: HotPair[];

    constructor() {
        this.children = new Map();
        this.times = 0;
        this.hotList = [];
    }
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.