Book Title Prefix and Anagram Search

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement search_book_titles(titles, query), which receives a list of catalog title strings titles and a single-word search string query, and returns every relevant title from the catalog.

Break each title into words by splitting on whitespace (title.split()). A title is relevant when at least one of its words matches query case-insensitively under any of the following rules:

  1. Whole-word match: the word has the exact same characters in the exact same sequence as query (ignoring letter case).
  2. Prefix match: the word begins with query (ignoring letter case).
  3. Anagram match: rearranging the characters of query yields the word (ignoring letter case, with identical character counts).

Formatting and ordering rules:

  • Return matching titles exactly as they appear in titles (do not alter capitalization or surrounding/repeated spaces).
  • Emit each distinct title string at most once, even if multiple words in a title match or the exact same string appears several times in titles (strings that differ in casing or spacing, such as "Dune" and "dune", count as distinct titles).
  • Order the returned titles by their first appearance in titles.

Also consider how a single-call scan compares against preprocessing titles into an index when serving high-volume traffic.

Examples

Example 1

Input:  titles = ["Silent Harbor", "Harbor of Stars", "Winter Gale", "Silent Harbor"], query = "harb"
Output: ["Silent Harbor", "Harbor of Stars"]

"Harbor" starts with "harb" ignoring case, so both "Silent Harbor" and "Harbor of Stars" match in input order. "Winter Gale" has no matching word, and the duplicate "Silent Harbor" at index 3 is skipped because it was already included.

Example 2

Input:  titles = [" Crimson Tide ", "Golden Dawn", "TIDE Runner"], query = "tide"
Output: [" Crimson Tide ", "TIDE Runner"]

Splitting on whitespace extracts "Tide" and "TIDE", both equal to "tide" ignoring case. Each matched title string is returned unchanged, including the leading and trailing spaces in " Crimson Tide ".

Example 3

Input:  titles = ["Trace of Amber", "Cart Wheel", "React Patterns", "Terra Firma"], query = "crate"
Output: ["Trace of Amber", "React Patterns"]

Lowercasing and sorting "crate" produces ['a', 'c', 'e', 'r', 't']. Both "Trace" and "React" have that exact 5-letter multiset, whereas "Cart" has length 4 and "Terra" sorts to ['a', 'e', 'r', 'r', 't'].

Constraints

  • 0 <= len(titles) <= 3 * 10^4
  • 0 <= len(titles[i]) <= 200
  • 1 <= len(query) <= 100, and query contains no whitespace characters.

Step-by-step walkthrough

  1. Understand the three matching rules

    We are given a list of titles and a single query string. We need to return every title where at least one word (token) matches query (ignoring case) under any of three rules:

    1. Whole-word match: the token equals query ("Tide" matches "tide").
    2. Prefix match: the token starts with query ("Harbor" starts with "harb").
    3. Anagram match: the token is an anagram of query — meaning both words contain the exact same characters with the exact same counts, just in a possibly different order ("Trace" and "React" match "crate").

    Right away, notice a neat simplification: any string equal to query also starts with query. So Rule 1 is automatically handled by startswith, leaving just two checks per token:

    • Does lower_token.startswith(normalized_query)?
    • Or do lower_token and normalized_query have the same length and the same letter counts?
  2. Clarify tokenization, casing, and deduplication

    Before writing code, let's lock down four small behavioral details:

    • Splitting into words: title.split() splits on whitespace and ignores leading, trailing, or repeated spaces (" Crimson Tide " -> ["Crimson", "Tide"] with no bogus empty tokens).
    • Preserve original casing in the output: Lowercasing is strictly for comparison; if " Crimson Tide " matches "tide", we return " Crimson Tide " untouched.
    • At most once, in input order: If "Book of Books" has two matching tokens ("Book" and "Books"), it appears once. If "Silent Harbor" appears twice in titles, it appears once at its first position. Distinct strings like "Emma" and "emma" are different titles and can both appear.
  3. Why permutation brute force fails, and how canonical sorting fixes it

    Checking anagrams by generating every permutation of an m-letter query creates m! candidate strings — for a 10-letter query, 10! = 3,628,800 permutations! On the other extreme, checking set(lower_token) == set(normalized_query) is fast but wrong, because sets discard duplicate letters: set("aab") and set("abb") are both {'a', 'b'}, yet "aab" and "abb" are not anagrams.

    Instead, sorting a word's lowercase characters places identical letters side by side into one canonical signature:

    "crate" --lower & sort-->  ['a', 'c', 'e', 'r', 't']
    "Trace" --lower & sort-->  ['a', 'c', 'e', 'r', 't']   (equal -> anagram!)
    "Terra" --lower & sort-->  ['a', 'e', 'r', 'r', 't']   (different -> not an anagram)
    "aab"   --lower & sort-->  ['a', 'a', 'b']
    "abb"   --lower & sort-->  ['a', 'b', 'b']             (counts preserved -> not equal!)
    

    Better still, we sort normalized_query once before scanning titles, and for each token we check len(lower_token) == len(normalized_query) in O(1) time before calling sorted(lower_token) — so tokens of any other length skip sorting completely.

  4. Code the single-token matcher

    Let's turn those two checks into a clean helper token_matches:

    from typing import List
    
    
    def token_matches(
        token: str,
        normalized_query: str,
        sorted_query_chars: List[str],
    ) -> bool:
        """Check whether one title word matches the query by exact, prefix, or anagram rule."""
        lower_token = token.lower()
    
        # Rule 1 (exact match) and Rule 2 (autocomplete prefix):
        # every exact match also starts with normalized_query, so startswith covers both.
        if lower_token.startswith(normalized_query):
            return True
    
        # Rule 3 (anagram match): two words can only be anagrams if their lengths match.
        # Checking length in O(1) first skips sorting almost every non-matching word.
        if len(lower_token) != len(normalized_query):
            return False
    
        return sorted(lower_token) == sorted_query_chars
    
  5. Code the title check and deduplicated scan

    A title is relevant as soon as any word in it matches, so title_matches returns True on the first hit without inspecting the rest of the title. Outside, search_book_titles maintains both a result list (to preserve original order) and a seen_titles hash set (so checking whether an identical title string was already added costs O(1) average time instead of an O(N) list scan):

    from typing import List, Set
    
    
    def title_matches(
        title: str,
        normalized_query: str,
        sorted_query_chars: List[str],
    ) -> bool:
        """Return True as soon as any space-separated word in title matches the query."""
        for token in title.split():
            if token_matches(token, normalized_query, sorted_query_chars):
                return True
        return False
    
    
    def search_book_titles(titles: List[str], query: str) -> List[str]:
        normalized_query = query.lower()
        sorted_query_chars = sorted(normalized_query)
    
        result: List[str] = []
        seen_titles: Set[str] = set()
    
        for title in titles:
            if title in seen_titles:
                continue
            if title_matches(title, normalized_query, sorted_query_chars):
                result.append(title)
                seen_titles.add(title)
    
        return result
    
  6. Trace Example 1 and Example 3

    Let's trace Example 1 (query = "harb") and Example 3 (query = "crate"):

    Example 1: titles = ["Silent Harbor", "Harbor of Stars", "Winter Gale", "Silent Harbor"], query = "harb"
      normalized_query = "harb", sorted_query_chars = ['a', 'b', 'h', 'r']
      0: "Silent Harbor"   -> "Silent" (len 6 != 4), "Harbor" -> "harbor".startswith("harb")! -> add & mark seen
      1: "Harbor of Stars" -> "Harbor" -> "harbor".startswith("harb")! -> add & mark seen
      2: "Winter Gale"     -> "Winter" (len 6 != 4), "Gale" (sorted ['a','e','g','l'] != ['a','b','h','r']) -> skip
      3: "Silent Harbor"   -> already in seen_titles -> skip immediately!
      Result: ["Silent Harbor", "Harbor of Stars"]
    
    Example 3: titles = ["Trace of Amber", "Cart Wheel", "React Patterns", "Terra Firma"], query = "crate"
      normalized_query = "crate", sorted_query_chars = ['a', 'c', 'e', 'r', 't']
      0: "Trace of Amber"  -> "Trace": sorted("trace") == ['a','c','e','r','t']! -> add
      1: "Cart Wheel"      -> "Cart" (len 4 != 5), "Wheel" (sorted ['e','e','h','l','w']) -> skip
      2: "React Patterns"  -> "React": sorted("react") == ['a','c','e','r','t']! -> add
      3: "Terra Firma"     -> "Terra" (sorted ['a','e','r','r','t']), "Firma" (['a','f','i','m','r']) -> skip
      Result: ["Trace of Amber", "React Patterns"]
    
  7. Trade-offs: single-query scan vs prebuilt search index

    The problem also asks us to compare scanning titles directly against preprocessing them:

    • Direct scan (our search_book_titles function): For a single call search_book_titles(titles, query), we must read every title at least once anyway — building an index first would read every title and pay extra sorting/hashing overhead just to use the index once! Direct scanning uses almost zero extra memory and handles constantly changing title lists effortlessly.
    • Prebuilt index (for thousands of queries over a fixed catalog): If titles is static and serves live search-as-you-type traffic, scanning millions of characters per keystroke is too slow. Instead, preprocess titles once into two structures:
    Catalog: [0: "Trace of Harbor", 1: "Harbor Star"]
    
    1. Sorted token array (for exact + prefix via binary search):
       [("harbor", 0), ("harbor", 1), ("of", 0), ("star", 1), ("trace", 0)]
         ^------------------------^
         prefix "harb" lands here in O(m log P) and walks contiguous hits!
    
    2. Anagram hash map (sorted letters -> set of title IDs):
       "acert"  -> {0}      <-- query "crate" sorts to "acert", O(1) lookup!
       "abhorr" -> {0, 1}
       "arst"   -> {1}
    

    Unioning the matching title IDs from both lookups and sorting those IDs restores the exact original title order in milliseconds per query, trading extra RAM and one-time build time (O(T log P)) for fast repeated lookups.

  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def token_matches(
        token: str,
        normalized_query: str,
        sorted_query_chars: List[str],
    ) -> bool:
        """Check whether one title word matches the query by exact, prefix, or anagram rule."""
        lower_token = token.lower()
    
        # Rule 1 (exact match) and Rule 2 (autocomplete prefix):
        # every exact match also starts with normalized_query, so startswith covers both.
        if lower_token.startswith(normalized_query):
            return True
    
        # Rule 3 (anagram match): two words can only be anagrams if their lengths match.
        # Checking length in O(1) first skips sorting almost every non-matching word.
        if len(lower_token) != len(normalized_query):
            return False
    
        return sorted(lower_token) == sorted_query_chars
    
    
    def title_matches(
        title: str,
        normalized_query: str,
        sorted_query_chars: List[str],
    ) -> bool:
        """Return True as soon as any space-separated word in title matches the query."""
        # Stop at the first matching word so a title with multiple hits is accepted once.
        for token in title.split():
            if token_matches(token, normalized_query, sorted_query_chars):
                return True
        return False
    
    
    def search_book_titles(titles: List[str], query: str) -> List[str]:
        # Normalize and sort the query once upfront instead of repeating it per word.
        normalized_query = query.lower()
        # sorted_query_chars: canonical letter list, e.g. ['a', 'c', 'e', 'r', 't'] for "crate"
        sorted_query_chars = sorted(normalized_query)
    
        # result: matching original title strings in their first-seen input order
        result: List[str] = []
        # seen_titles: set of exact title strings already added to result for O(1) deduplication
        seen_titles: Set[str] = set()
    
        for title in titles:
            if title in seen_titles:
                continue
            if title_matches(title, normalized_query, sorted_query_chars):
                result.append(title)
                seen_titles.add(title)
    
        return result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine scanning a shelf of books with two simple stencils for your search word: a "starts-with" stencil that catches both whole-word matches and prefixes at the same time (since "tide" starts with "tide" just as "harbor" starts with "harb"), and an alphabetical letter-tally card for anagrams (words made of the exact same letters in identical quantities, such as "crate" and "trace"). By lowercasing and sorting the query's letters once before touching the shelf, each word on a spine needs only a fast startswith check and — only when its length equals the query's length — a quick sorted-letter comparison.

A naive approach tries generating all m! letter permutations of an m-character query, which explodes to 3,628,800 strings at just 10 letters. Another common shortcut tests set(token) == set(query), which fails whenever letters repeat because sets ignore counts ("aab" and "abb" share the set {'a', 'b'} without being anagrams). Checking if title not in result on a list also degrades deduplication to O(N^2) when thousands of titles match.

Walk through ["Cart Wheel", "Terra Firma", "Trace of Amber"] with query = "crate" to see how fast non-matches are eliminated:

  1. Precompute normalized_query = "crate" (length 5) and sorted_query_chars = ['a', 'c', 'e', 'r', 't'].
  2. "Cart" -> "cart" fails startswith("crate") and has length 4 != 5, so we skip sorting it; "Wheel" has length 5, and sorted("wheel") is ['e', 'e', 'h', 'l', 'w'] != ['a', 'c', 'e', 'r', 't'].
  3. "Terra" -> "terra" has length 5, and sorted("terra") is ['a', 'e', 'r', 'r', 't'] != ['a', 'c', 'e', 'r', 't']; "Firma" sorts to ['a', 'f', 'i', 'm', 'r'].
  4. "Trace" -> "trace" has length 5 and sorted("trace") == ['a', 'c', 'e', 'r', 't'], so "Trace of Amber" matches immediately without even inspecting "of" or "Amber".

Complexity

Let T be the total number of characters across all titles, m be the length of query, and K be the number of tokens whose length equals m.

  • Time: O(m log m + T + K * m log m). Sorting the query once takes O(m log m). Splitting titles, lowercasing tokens, hashing titles in seen_titles, and checking startswith touch each of the T characters a constant number of times (O(T) total), and only the K tokens of exact length m pay O(m log m) to sort their characters.
  • Space: O(m + L) auxiliary working space (where L is the length of the longest single title), plus O(R) references in result and seen_titles for the R distinct titles returned.

Edge cases

  • Empty titles list or zero matches: Returns [].
  • Query longer than a token (query = "harbors" vs "Harbor"): Fails startswith and fails len(lower_token) == len(normalized_query), cleanly returning False.
  • Same distinct letters with different counts ("aab" vs "abb"): Sorted lists ['a', 'a', 'b'] and ['a', 'b', 'b'] differ, avoiding false-positive anagrams.
  • Multiple matching tokens in one title ("Book of Books" for "book"): title_matches returns True on "Book", so the title is appended once.
  • Duplicate title strings in titles (["Silent Harbor", "Winter Gale", "Silent Harbor"]): seen_titles skips the second "Silent Harbor" while preserving first-seen order; "Emma" and "emma" remain distinct strings and can both be returned.
  • Leading, trailing, or repeated spaces (" Crimson Tide "): title.split() extracts ["Crimson", "Tide"] cleanly while returning the original spaced title string unchanged.
  • Substring that is not a prefix ("arb" vs "Harbor"): Rejected because Rule 2 requires startswith, not substring containment (in).

Common mistakes

  • Using normalized_query in lower_token instead of startswith: Wrongly matches substrings in the middle or end of words (such as "arb" inside "Harbor").
  • Comparing set(lower_token) == set(normalized_query) for anagrams: Ignores character multiplicities and falsely matches "aab" with "abb".
  • Returning lowercased or whitespace-normalized titles: Mutates the user-visible catalog string instead of returning the exact element from titles.
  • Deduplicating with list(set(result)): Destroys the required original input order.
  • Not breaking after the first matching token in a title: Appends "Book of Books" twice when two words in the same title match query.

Alternative approaches

  • Character frequency array / Counter instead of sorting (O(m) per same-length token): Building a 26-integer count tuple (for ASCII letters) or collections.Counter runs in O(m) instead of O(m log m), though for normal English word lengths (m <= 15) Python's C-level sorted() is actually faster due to smaller constant overhead.
  • Preprocessed catalog index (TitleIndex) for high-throughput query serving: Store unique titles once by integer ID, keep a sorted list of (lower_token, title_id) pairs so binary search (repeatedly halving a sorted array to jump to the first entry >= normalized_query in O(m log P) time over P tokens) finds the contiguous block of prefix matches, and keep a dictionary mapping "".join(sorted(lower_token)) to set of title_ids for O(1) anagram lookup:

```python import bisect from collections import defaultdict from typing import Dict, List, Set

class TitleIndex: def init(self, titles: List[str]) -> None: self.titles: List[str] = [] seen: Set[str] = set() token_pairs: List[tuple] = [] self.anagram_to_ids: Dict[str, Set[int]] = defaultdict(set)

      for title in titles:
          if title in seen:
              continue
          seen.add(title)
          title_id = len(self.titles)
          self.titles.append(title)
          for token in title.split():
              lower_token = token.lower()
              token_pairs.append((lower_token, title_id))
              self.anagram_to_ids["".join(sorted(lower_token))].add(title_id)

      token_pairs.sort()
      self.sorted_tokens = [pair[0] for pair in token_pairs]
      self.token_title_ids = [pair[1] for pair in token_pairs]

  def search(self, query: str) -> List[str]:
      q = query.lower()
      matched_ids = set(self.anagram_to_ids.get("".join(sorted(q)), set()))
      idx = bisect.bisect_left(self.sorted_tokens, q)
      while idx < len(self.sorted_tokens) and self.sorted_tokens[idx].startswith(q):
          matched_ids.add(self.token_title_ids[idx])
          idx += 1
      return [self.titles[i] for i in sorted(matched_ids)]

```

Follow-up questions

  • At what query volume does building an upfront search index outperform scanning every title, and how would you support live catalog insertions? Building TitleIndex over P tokens takes O(T log P) time, roughly equal to log2(P) full scans (~20 queries on a million-word catalog), so preprocessing wins whenever a catalog serves dozens or millions of queries. If titles are inserted and deleted continuously, replace the flat sorted array (where inserts cost O(P) shifting) with a trie (a character-by-character prefix tree where every word sharing a prefix shares the same path from the root) alongside the anagram dictionary so inserts and prefix lookups both run in O(word_length) time plus output size.
  • Suppose exact word matches must appear ahead of prefix matches, and prefix matches ahead of anagrams—how would you modify the algorithm? Assign each rule a priority tier (0 for exact lower_token == normalized_query, 1 for prefix lower_token.startswith(normalized_query), 2 for anagram), compute the minimum tier across all tokens in each title, and sort matching titles by (best_tier, first_seen_index). Notice that ranking makes Rule 1 distinct from Rule 2 again instead of collapsing both into startswith.
  • How would you generalize the search function to handle multi-token queries where every query word must match the title? Split query on spaces into individual query tokens, find the set of matching title_ids for each query word using the single-word rules, and intersect those sets (set.intersection) so returned titles match all query words. Clarify with the interviewer whether a single title word is allowed to satisfy two query words (for example, query "harb harbor" against "Silent Harbor"); if not, verify on each candidate title that every query word can be paired with its own distinct token in that title.

Follow-up questions

Similar questions

More Enigma interview questions

All 1 Enigma questions →