Solving Leetcode Interviews in Seconds with AI: Longest Word in Dictionary
Introduction
In this blog post, we will explore how to solve the LeetCode problem "720" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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.
Explanation
Here's a solution to find the longest word that can be built one character at a time from other words in the given dictionary, prioritizing lexicographical order in case of ties.
Approach: Sort the words lexicographically. Iterate through the sorted words, using a set to keep track of the words that can be built. A word can be built if its prefix (excluding the last character) exists in the set. Keep track of the longest built word encountered so far, updating when a longer or lexicographically smaller word is found.
Complexity:
- Runtime: O(n log n + n m), where n is the number of words and m is the average length of a word. The n log n comes from sorting the array and nm from iterating through words and checking prefixes.
- Storage: O(n), to store the set of built words.
Code
def longestWord(words):
words.sort()
built = set()
longest = ""
for word in words:
if len(word) == 1 or word[:-1] in built:
built.add(word)
if len(word) > len(longest):
longest = word
elif len(word) == len(longest) and word < longest:
longest = word
return longest