algoadvance

Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no such string, return an empty string.

Example 1:

Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
Output: "apple"

Example 2:

Input: s = "abpcplea", dictionary = ["a","b","c"]
Output: "a"

Constraints:

Clarifying Questions

  1. Should we consider only the exact characters and their sequence in the string s when forming the words from the dictionary?
    • Yes, the characters in the word formed must appear in the same order as they appear in s.
  2. If there is a tie in the longest word length, should we return the one that comes first lexicographically?
    • Yes, return the smallest lexicographical order if there’s more than one result.

Strategy

  1. Define a helper function is_subsequence(str1, str2) to check if str2 can be formed by deleting some characters from str1. This can be done using two pointers.
  2. Sort the dictionary first by the length of the words in descending order. For words with the same length, sort them lexicographically in ascending order.
  3. Iterate through the sorted dictionary and check if the current word is a subsequence of the given string s using the helper function.
  4. Return the first word that satisfies the subsequence condition since the dictionary is sorted with priority rules mentioned.

Time Complexity

Code

def findLongestWord(s, dictionary):
    def is_subsequence(x, y):
        it = iter(x)
        return all(c in it for c in y)
    
    # Sort the dictionary by length descending, lexically ascending
    dictionary.sort(key=lambda x: (-len(x), x))
    
    for word in dictionary:
        if is_subsequence(s, word):
            return word
    
    return ""

# Example usage:
s = "abpcplea"
dictionary = ["ale","apple","monkey","plea"]
print(findLongestWord(s, dictionary))  # Output: "apple"

This approach ensures we efficiently find the longest word that can be formed by deleting characters from s, considering both length and lexicographical order.

Try our interview co-pilot at AlgoAdvance.com