For each word in the dictionary, we check if it is a subsequence of s using Two Pointers. We update the result based on the length and lexicographical order.
res = "".- For each
wordindictionary:i = 0(forword),j = 0(fors).- While
i < len(word)andj < len(s):- If
word[i] == s[j],i += 1. j += 1.
- If
- If
i == len(word)(subsequence found):- If
len(word) > len(res)or (len(word) == len(res)andword < res):res = word.
- If
- Return
res.
- Time Complexity: O(N * M) where N is dictionary size and M is avg length of s.
- Space Complexity: O(1).
def find_longest_word(s, dictionary):
res = ""
for word in dictionary:
i = 0
for char in s:
if i < len(word) and word[i] == char:
i += 1
if i == len(word):
if len(word) > len(res) or (len(word) == len(res) and word < res):
res = word
return res