Search⌘ K
AI Features

Solution: Longest Word With All Prefixes

Understand how to use trie data structures to find the longest word in a list such that every prefix of the word is also in the list. Learn to build a trie, validate words by checking prefix completeness, and select the lexicographically smallest longest word. This lesson helps you apply tries for prefix-related string problems with optimized time and space complexity.

Statement

You are given an array of strings, words. Your task is to find the longest string in words such that every prefix of this string is also present in words.

A prefix of a string is any leading substring. For example, the prefixes of "apple" are "a", "ap", "app", and "appl".

  1. If multiple valid strings have the same maximum length, return the lexicographically smallest one.

  2. If no such string exists, return an empty string "".

Constraints:

  • ...