Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Example 1:
Input: words = ["w","wo","wor","worl","world"] Output: "world" Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
Example 2:
Input: words = ["a","banana","app","appl","ap","apply","apple"] Output: "apple" Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
Constraints:
1 <= words.length <= 10001 <= words[i].length <= 30words[i] consists of lowercase English letters.Problem summary: Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words. If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string. Note that the word should be built from left to right with each additional character being added to the end of a previous word.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Trie
["w","wo","wor","worl","world"]
["a","banana","app","appl","ap","apply","apple"]
longest-word-in-dictionary-through-deleting)implement-magic-dictionary)longest-word-with-all-prefixes)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #720: Longest Word in Dictionary
class Trie {
private Trie[] children = new Trie[26];
private boolean isEnd = false;
public void insert(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
}
node.isEnd = true;
}
public boolean search(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null || !node.children[idx].isEnd) {
return false;
}
node = node.children[idx];
}
return true;
}
}
class Solution {
public String longestWord(String[] words) {
Trie trie = new Trie();
for (String w : words) {
trie.insert(w);
}
String ans = "";
for (String w : words) {
if (trie.search(w)
&& (ans.length() < w.length()
|| (ans.length() == w.length() && w.compareTo(ans) < 0))) {
ans = w;
}
}
return ans;
}
}
// Accepted solution for LeetCode #720: Longest Word in Dictionary
type Trie struct {
children [26]*Trie
isEnd bool
}
func (t *Trie) insert(w string) {
node := t
for i := 0; i < len(w); i++ {
idx := w[i] - 'a'
if node.children[idx] == nil {
node.children[idx] = &Trie{}
}
node = node.children[idx]
}
node.isEnd = true
}
func (t *Trie) search(w string) bool {
node := t
for i := 0; i < len(w); i++ {
idx := w[i] - 'a'
if node.children[idx] == nil || !node.children[idx].isEnd {
return false
}
node = node.children[idx]
}
return true
}
func longestWord(words []string) string {
trie := &Trie{}
for _, w := range words {
trie.insert(w)
}
ans := ""
for _, w := range words {
if trie.search(w) && (len(ans) < len(w) || (len(ans) == len(w) && w < ans)) {
ans = w
}
}
return ans
}
# Accepted solution for LeetCode #720: Longest Word in Dictionary
class Trie:
def __init__(self):
self.children: List[Optional[Trie]] = [None] * 26
self.is_end = False
def insert(self, w: str):
node = self
for c in w:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
def search(self, w: str) -> bool:
node = self
for c in w:
idx = ord(c) - ord("a")
if node.children[idx] is None:
return False
node = node.children[idx]
if not node.is_end:
return False
return True
class Solution:
def longestWord(self, words: List[str]) -> str:
trie = Trie()
for w in words:
trie.insert(w)
ans = ""
for w in words:
if trie.search(w) and (
len(ans) < len(w) or (len(ans) == len(w) and ans > w)
):
ans = w
return ans
// Accepted solution for LeetCode #720: Longest Word in Dictionary
struct Trie {
children: [Option<Box<Trie>>; 26],
is_end: bool,
}
impl Trie {
fn new() -> Self {
Trie {
children: Default::default(),
is_end: false,
}
}
fn insert(&mut self, w: &str) {
let mut node = self;
for c in w.chars() {
let idx = (c as usize) - ('a' as usize);
if node.children[idx].is_none() {
node.children[idx] = Some(Box::new(Trie::new()));
}
node = node.children[idx].as_mut().unwrap();
}
node.is_end = true;
}
fn search(&self, w: &str) -> bool {
let mut node = self;
for c in w.chars() {
let idx = (c as usize) - ('a' as usize);
if node.children[idx].is_none() || !node.children[idx].as_ref().unwrap().is_end {
return false;
}
node = node.children[idx].as_ref().unwrap();
}
true
}
}
impl Solution {
pub fn longest_word(words: Vec<String>) -> String {
let mut trie = Trie::new();
for w in &words {
trie.insert(w);
}
let mut ans = String::new();
for w in words {
if trie.search(&w) && (ans.len() < w.len() || (ans.len() == w.len() && w < ans)) {
ans = w;
}
}
ans
}
}
// Accepted solution for LeetCode #720: Longest Word in Dictionary
class Trie {
children: (Trie | null)[] = new Array(26).fill(null);
isEnd: boolean = false;
insert(w: string): void {
let node: Trie = this;
for (let i = 0; i < w.length; i++) {
const idx: number = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[idx] === null) {
node.children[idx] = new Trie();
}
node = node.children[idx]!;
}
node.isEnd = true;
}
search(w: string): boolean {
let node: Trie = this;
for (let i = 0; i < w.length; i++) {
const idx: number = w.charCodeAt(i) - 'a'.charCodeAt(0);
if (node.children[idx] === null || !node.children[idx]!.isEnd) {
return false;
}
node = node.children[idx]!;
}
return true;
}
}
function longestWord(words: string[]): string {
const trie = new Trie();
for (const w of words) {
trie.insert(w);
}
let ans = '';
for (const w of words) {
if (trie.search(w) && (ans.length < w.length || (ans.length === w.length && w < ans))) {
ans = w;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Store all N words in a hash set. Each insert/lookup hashes the entire word of length L, giving O(L) per operation. Prefix queries require checking every stored word against the prefix — O(N × L) per prefix search. Space is O(N × L) for storing all characters.
Each operation (insert, search, prefix) takes O(L) time where L is the word length — one node visited per character. Total space is bounded by the sum of all stored word lengths. Tries win over hash sets when you need prefix matching: O(L) prefix search vs. checking every stored word.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.