893334. Longest Valid Word with All Prefixes

Medium

Longest Valid Word with All Prefixes

Summary

Given a list of words, find the longest word that has all its prefixes as valid English words. For example, if the input is ["apple", "banana", "app", "appl"], the output should be "apple" because it's the longest word that has all its prefixes ("app" and "") as valid English words.

Detailed Explanation

To solve this problem, we can iterate through each word in the list. For each word, we check if all its prefixes are valid English words. If a prefix is not valid, we immediately move on to the next word. If a word has all its prefixes as valid English words and it's the longest so far, we update our result.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty string result to store the longest valid word.
  2. Iterate through each word in the input list.
  3. For each word, iterate from its first character to its last character (inclusive).
  4. For each prefix, check if it's a valid English word. We can do this by checking if the prefix is present in our dictionary of valid words.
  5. If a prefix is not valid, break out of the inner loop and move on to the next word.
  6. If a word has all its prefixes as valid English words and it's longer than our current result, update result.
  7. Return result.

Time complexity: O(N*M), where N is the number of words in the input list and M is the maximum length of a word.

Space complexity: O(M), where M is the maximum length of a word.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class Main {
    public static String longestValidWord(String[] dictionary) {
        String result = "";
        for (String word : dictionary) {
            boolean isValid = true;
            for (int i = 0; i < word.length(); i++) {
                if (!isValid(word.substring(0, i + 1))) {
                    isValid = false;
                    break;
                }
            }
            if (isValid && word.length() > result.length()) {
                result = word;
            }
        }
        return result;
    }

    public static boolean isValid(String word) {
        // implement your dictionary lookup logic here
        // for example, you can use a HashSet to store the valid words
        Set<String> dictionary = new HashSet<>(Arrays.asList(dictionary));
        return dictionary.contains(word);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.