Longest Word in Dictionary through Deleting
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
Longest Word in Dictionary through Deleting
Given a string
s and a string dictionary dictionary, return the longest string in the dictionary that can be formed by deleting some characters of the given string s.Examples
Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
Output: "apple"
Approach 1
Level I: Two Pointers (Standard Search)
Intuition
Iterate through each word in the dictionary. Use two pointers to check if the word is a subsequence of
s. Keep track of the longest word found (using lexicographical order for ties).⏱ O(N * L) where N is dict size.💾 O(1).
Approach 2
Level III: Trie (Index-based Subsequence Search)
Intuition
Store
s in a way that allows fast subsequence checks. For each character a-z, store a list of indices where it appears in s. For any word, use binary search to find the smallest valid index for the next character. A Trie of words can also be used to explore multiple words simultaneously.⏱ O(N * L * log S).💾 O(S).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.