Suppose we have two strings, word0, and word1 and a text. We have to find the smallest distance between any two occurrences of word0 and word1 in the given text. Here the distance is measured in number of words. If they are not present in the text then return -1.
So, if the input is like text = "cat dog abcd dog cat cat abcd dog wxyz", word0 = "abcd", word1 = "wxyz", then the output will be 1, as there is one word "dog" between "abcd" and "wxyz"
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, text, word0, word1): word_list = text.split() ans = len(word_list) L = None for R in range(len(word_list)): if word_list[R] == word0 or word_list[R] == word1: if L is not None and word_list[R] != word_list[L]: ans = min(ans, R - L - 1) L = R return -1 if ans == len(word_list) else ans ob = Solution() text = "cat dog abcd dog cat cat abcd dog wxyz" word0 = "abcd" word1 = "wxyz" print(ob.solve(text, word0, word1))
"cat dog abcd dog cat cat abcd dog wxyz", "abcd", "wxyz"