Algorithm


Problem Name: 720. Longest Word in Dictionary

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 <= 1000
  • 1 <= words[i].length <= 30
  • words[i] consists of lowercase English letters.

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


class Solution {
public:
    string longestWord(vector<string>& words) {
        string res = "";
        unordered_map < int, unordered_set= res.size()) res = s.size() > res.size() ? s : min(s, res);
        }
        return res;
    }
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["w","wo","wor","worl","world"]

Output

x
+
cmd
"world"

#2 Code Example with Javascript Programming

Code - Javascript Programming


const longestWord = function(words) {
  if(words == null || words.length === 0) return ''
  words.sort()
  const s = new Set()
  let res = ''
  for(let i = 0, len = words.length; i < len; i++) {
    const w = words[i]
    if(w.length === 1 || s.has(w.slice(0, w.length - 1))> {
      res = w.length > res.length ? w : res
      s.add(w)
    }
  }
  return res
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["w","wo","wor","worl","world"]

Output

x
+
cmd
"world"

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        for w in sorted(words, key = lambda x: (-len(x), x)):
            if all([True if w[:i] in set(words) - {w} else False for i in range(1, len(w))]): return w  
        return ""
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["a","banana","app","appl","ap","apply","apple"]

Output

x
+
cmd
"apple"

#4 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;

namespace LeetCode
{
    public class _0720_LongestWordInDictionary
    {
        public string LongestWord(string[] words)
        {
            var root = new Trie() { Finished = true };
            foreach (var word in words)
            {
                var current = root;
                foreach (var ch in word)
                {
                    if (current.Children[ch - 'a'] == null)
                        current.Children[ch - 'a'] = new Trie();

                    current = current.Children[ch - 'a'];
                }

                current.Finished = true;
                current.Word = word;
            }

            var result = string.Empty;
            var stack = new Stack < Trie>();
            stack.Push(root);
            while (stack.Count > 0)
            {
                var node = stack.Pop();
                if (node.Finished)
                {
                    if (node.Word.Length >= result.Length)
                        result = node.Word;
                    for (int i = 0; i  <  26; i++)
                    {
                        if (node.Children[i] != null)
                            stack.Push(node.Children[i]);
                    }
                }
            }

            return result;
        }

        public class Trie
        {
            public Trie[] Children = new Trie[26];
            public bool Finished = false;
            public string Word = string.Empty;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
words = ["a","banana","app","appl","ap","apply","apple"]

Output

x
+
cmd
"apple"
Advertisements

Demonstration


Previous
#719 Leetcode Find K-th Smallest Pair Distance Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#721 Leetcode Accounts Merge Solution in C, C++, Java, JavaScript, Python, C# Leetcode