![]() |
VOOZH | about |
Given a string s and two words w1 and w2 that are present in S. The task is to find the minimum distance between w1 and w2. Here, distance is the number of steps or words between the first and the second word.
Examples:
Input : s = "geeks for geeks contribute practice", w1 = "geeks", w2 = "practice"
Output : 1
There is only one word between the closest occurrences of w1 and w2.Input : s = "the quick the brown quick brown the frog", w1 = "quick", w2 = "frog"
Output : 2
A simple approach is to consider every occurrence of w1. For every occurrence of w1, find the closest w2 and keep track of the minimum distance.
Implementation:
1
Complexity Analysis:
An efficient solution is to find the first occurrence of any element, then keep track of the previous element and current element. If they are different and the distance is less than the current minimum, update the minimum.
Implementation:
1
Complexity Analysis:
An efficient solution is to store the index of word1 in (lastpos) variable if word1 occur again then we update (lastpos) if word1 not occur then simply find the difference of index of word1 and word2.
Implementation:
1
Complexity Analysis: