Implement a Phone Directory

Pattern: Insert, search and prefix

medium

For every prefix of the typed query, list the contacts that start with it, sorted and without repeats, or '0' if there are none. Put the contacts in a trie; the matches for a prefix are all words under its node, collected in letter order.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a list of contacts and a query string s, return, for each prefix s[0..i], the sorted list of distinct contacts starting with it, or the list ["0"] if there is none. The catalogue has no practice link for this one.

Think first

  • How are all contacts with a given prefix found in a trie?
  • How do you get them sorted?
  • What happens after the first prefix with no match?

Hints

    Brute force, and why it fails

    For each prefix, filter and sort the contact list: O(|s| × n × L + sorting).

    The key insight

    Each prefix is one more step down the trie, and its subtree holds exactly the matches.

    Dry run

    Contacts geeikistest, geeksforgeeks, geeksfortest; query geeips. g, ge, gee: all three.

    Step 1 of 2

    The plan

    insert all contacts
    node = root
    for each character: node = node.child (or none)
      collect the subtree's words in letter order, or ["0"]
    

    Complexity

    Time
    O(total letters + output)
    Space
    O(total letters)

    Each prefix's list is read off its subtree.

    Edge cases

    • Duplicate contacts.
    • A query longer than every contact.
    • One contact.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        private static class Node {
            Node[] next = new Node[26];
            boolean end;
        }
    
        public List<List<String>> displayContacts(String[] contact, String s) {
            Node root = new Node();
            for (String c : contact) {
                Node n = root;
                for (char ch : c.toCharArray()) {
                    if (n.next[ch - 'a'] == null) n.next[ch - 'a'] = new Node();
                    n = n.next[ch - 'a'];
                }
                n.end = true;                       // duplicates land on the same node, so they appear once
            }
            List<List<String>> out = new ArrayList<>();
            Node n = root;
            StringBuilder prefix = new StringBuilder();
            for (char ch : s.toCharArray()) {
                prefix.append(ch);
                n = n == null ? null : n.next[ch - 'a'];   // once the path breaks, no longer prefix can match
                List<String> found = new ArrayList<>();
                if (n != null) collect(n, prefix, found);
                if (found.isEmpty()) found.add("0");
                out.add(found);
            }
            return out;
        }
    
        private void collect(Node n, StringBuilder word, List<String> found) {   // letters in order give sorted output
            if (n.end) found.add(word.toString());
            for (int c = 0; c < 26; c++)
                if (n.next[c] != null) {
                    word.append((char) ('a' + c));
                    collect(n.next[c], word, found);
                    word.deleteCharAt(word.length() - 1);
                }
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> next;
        vector<bool> isEnd;
    
        vector<vector<string>> displayContacts(vector<string>& contact, string s) {
            next.assign(1, vector<int>(26, 0));     // node 0 is the root; 0 also means "no child"
            isEnd.assign(1, false);
            for (const string& c : contact) {
                int n = 0;
                for (char ch : c) {
                    if (next[n][ch - 'a'] == 0) {
                        next[n][ch - 'a'] = static_cast<int>(next.size());
                        next.push_back(vector<int>(26, 0));
                        isEnd.push_back(false);
                    }
                    n = next[n][ch - 'a'];
                }
                isEnd[n] = true;                    // duplicates land on the same node, so they appear once
            }
            vector<vector<string>> out;
            int n = 0;
            string prefix;
            for (char ch : s) {
                prefix += ch;
                n = n == -1 ? -1 : next[n][ch - 'a'];   // once the path breaks, no longer prefix can match
                if (n == 0) n = -1;
                vector<string> found;
                if (n != -1) collect(n, prefix, found);
                if (found.empty()) found.push_back("0");
                out.push_back(found);
            }
            return out;
        }
    
        void collect(int n, string& word, vector<string>& found) {   // letters in order give sorted output
            if (isEnd[n]) found.push_back(word);
            for (int c = 0; c < 26; c++)
                if (next[n][c] != 0) {
                    word.push_back(static_cast<char>('a' + c));
                    collect(next[n][c], word, found);
                    word.pop_back();
                }
        }
    };

    Python

    class Solution:
        def displayContacts(self, contact: list[str], s: str) -> list[list[str]]:
            root = {}
            for c in contact:
                node = root
                for ch in c:
                    node = node.setdefault(ch, {})
                node["$"] = True                    # duplicates land on the same node, so they appear once
    
            def collect(node, word, found):         # letters in order give sorted output
                if "$" in node:
                    found.append(word)
                for ch in sorted(k for k in node if k != "$"):
                    collect(node[ch], word + ch, found)
    
            out, node = [], root
            for i, ch in enumerate(s):
                node = node.get(ch) if node is not None else None   # once the path breaks, nothing longer matches
                found = []
                if node is not None:
                    collect(node, s[:i + 1], found)
                out.append(found or ["0"])
            return out

    Common mistakes

    • Repeating duplicates.
    • Searching again from the root for each prefix.

    Similar problems