LeetCode 1858. Longest Word With All Prefixes Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1858. Longest Word With All Prefixes

Description

Given an array of strings words, find the longest string in words such that every prefix of it is also in words.

  • For example, let words = ["a", "app", "ap"]. The string "app" has prefixes "ap" and "a", all of which are in words.

Return the string described above. If there is more than one string with the same length, return the lexicographically smallest one, and if no string exists, return "".

 

Example 1:

Input: words = ["k","ki","kir","kira", "kiran"]
Output: "kiran"
Explanation: "kiran" has prefixes "kira", "kir", "ki", and "k", and all of them appear in words.

Example 2:

Input: words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
Output: "apple"
Explanation: Both "apple" and "apply" have all their prefixes in words.
However, "apple" is lexicographically smaller, so we return that.

Example 3:

Input: words = ["abc", "bc", "ab", "qwe"]
Output: ""

 

Constraints:

  • 1 <= words.length <= 105
  • 1 <= words[i].length <= 105
  • 1 <= sum(words[i].length) <= 105
  • words[i] consists only of lowercase English letters.

Solutions

Solution 1: Trie

We define a Trie where each node has two attributes: a child node array children of length 26, and a flag isEnd indicating whether the node marks the end of a word.

We iterate over words, and for each word w, we traverse from the root node. If the child node array of the current node does not contain the first character of w, we create a new node, then continue traversing the next character of w. After traversing all characters of w, we set the isEnd flag of the current node to \texttt{true}.

Next, we iterate over words again, and for each word w, we traverse from the root node. If the isEnd field of a node in the child node array is \texttt{false}, it means some prefix of w is not in words, and we return \texttt{false}. Otherwise, we continue traversing the next character of w, and after traversing all characters, we return \texttt{true}.

The time complexity is O(∑_{w ∈ words} |w|), and the space complexity is O(∑_{w ∈ words} |w|), where |w| is the length of word w.

PythonJavaC++GoTypeScriptRustJavaScriptC#
class Trie: __slots__ = ["children", "is_end"] def __init__(self): self.children: List[Trie | None] = [None] * 26 self.is_end: bool = False def insert(self, w: str) -> None: node = self for c in w: idx = ord(c) - ord("a") if not node.children[idx]: 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") 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 (len(w) > len(ans) or len(w) == len(ans) and w < ans) and trie.search(w): ans = w return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !