string
two pointers
sort
]
Leetcode 0524. Longest Word in Dictionary through Deleting
https://leetcode.com/problems/longest-word-in-dictionary-through-deleting
This problem is nothing else, but generalization of problem 392. Is Subsequence, but here here we have one main string s
and bunch of substrings we need to look inside. You can see my solution for this problem here
https://leetcode.com/problems/is-subsequence/discuss/678389/Python-3-Solutions%3A-DP-2-pointers-and-follow-up-BS-explained
Let us now iterate over strings d
here and if we found subsequence of s
, we update our ans
: fisrt check length and then lexicographical order.
Complexity: time complexity will be O(mn)
, where m
is number of strings in d
and n
is length of s
. Space complexity is O(n)
.
class Solution:
def isSubsequence(self, s, t):
s_i, t_i = 0, 0
while s_i < len(s) and t_i < len(t):
s_i, t_i = s_i + (s[s_i] == t[t_i]), t_i + 1
return s_i == len(s)
def findLongestWord(self, s, d):
ans = ""
for string in d:
if self.isSubsequence(string, s):
ans = min(ans, string, key = lambda x: (-len(x), x))
return ans
PS: there is also very elegant oneliner for isSubsequence function, which has the same complexity as my function, but works several times faster due to low-level python language optimizations. However, I think nobody expect this code on real interview and it is more for constests trick in my opinion.
return all(c in (t:=iter(t)) for c in s)
If you like the solution, you can upvote it on leetcode discussion section: Problem 0524