KatInterview

Reverse Trie for Ending Pattern Queries

Data Structure DesignAuto-graded · 18 test cases
MediumAuto-gradedData Structure Designtriestring-matchingdata-structures

Last updated

Tests understanding of tries and the insight that suffix matching becomes prefix matching when strings are reversed.

Reverse Trie for Ending Pattern Queries

Build a data structure that stores strings and efficiently answers whether any stored string ends with a given pattern.

Your structure must support two operations:

  • Adding a new string to the collection
  • Checking if any string in the collection ends with a specific pattern

Both operations should run in time proportional to the length of the input string or pattern.

Implement the EndingMatcher class:

  • EndingMatcher(): Creates an empty matcher.
  • void add_word(str word): Adds word to the collection.
  • bool matches_ending(str pattern): Returns true if at least one word in the collection ends with pattern, otherwise returns false.

Constraints

  • 1 <= word.length, pattern.length <= 2,000
  • All strings contain only printable ASCII characters
  • Matching is case-sensitive
  • At most 100,000 operations total
  • Total characters across all added words does not exceed 1,000,000

Behavior Notes

  • A word matches its own ending (adding "hello" means matches_ending("hello") returns true)
  • Querying an empty collection returns false
  • Case matters: "Test" and "test" are different patterns
  • Words can be added multiple times (duplicates are allowed but don't change query results)

Examples

Example 1

Input: run_suffix_index(['insert', 'insert', 'insert', 'has_suffix', 'has_suffix', 'has_suffix', 'has_suffix', 'has_suffix'], [['surveillance'], ['guidance'], ['reconnaissance'], ['ance'], ['lance'], ['surveil'], ['e'], ['drone']])

Output: [None, None, None, True, True, False, True, False]

Example 2

Input: run_suffix_index(['has_suffix', 'insert', 'has_suffix', 'insert', 'has_suffix', 'has_suffix'], [['x'], ['x'], ['x'], ['Radar'], ['radar'], ['Radar']])

Output: [False, None, True, None, False, True]

Example 3

Input: run_suffix_index(['insert', 'insert', 'has_suffix', 'has_suffix', 'has_suffix'], [['target'], ['market'], ['target'], ['ket'], ['tar']])

Output: [None, None, True, True, False]

Hints

Hint 1

Think about how prefix matching works with tries. Can you transform suffix matching into prefix matching?

Hint 2

If you reverse a word, its suffix becomes a prefix of the reversed word.

Hint 3

Store reversed words in a trie. Then checking for a suffix becomes checking if the reversed pattern exists as a prefix in your trie.