AlgoMaster Logo

Longest Word in Dictionary

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

The brute force approach involves iterating through each word and checking if all its prefixes exist in the given list. We can achieve this by using a HashSet to store all words and checking if each prefix of a word exists in the set. If so, keep track of the longest valid word encountered so far.

Steps:

  • Insert all words into a HashSet for fast look-up.
  • Iterate over each word. For each word, check if all of its prefixes exist using the HashSet.
  • If all prefixes of a word exist, compare it with the current longest word and update if necessary.
  • In cases where two valid words have the same length, choose the lexicographical smaller one.

Code:

2. Trie-based Approach

Intuition:

A Trie is an efficient data structure to store and retrieve words, especially useful in prefix queries. By inserting all words into a Trie, we can efficiently check if a word can be built by other words. We traverse the Trie to find the deepest node that represents a complete buildable word, which will be our answer.

Steps:

  • Insert all words into the Trie and mark the end of each complete word.
  • Perform a depth-first search (DFS) on the Trie, keeping track of the longest word that can be constructed step-by-step.
  • Continue traversal only if the current path represents a complete word until that node.

Code: