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:
C++
#include <bits/stdc++.h>
#include <sstream>
using namespace std;
void split( const string &s, char delimiter,
vector<string> &words)
{
string token;
stringstream tokenStream(s);
while (getline(tokenStream, token, delimiter))
words.push_back(token);
}
int distance(string s, string w1, string w2)
{
if (w1 == w2)
return 0;
vector<string> words;
split(s, ' ' , words);
int min_dist = words.size() + 1;
for ( int index = 0; index < words.size(); index++)
{
if (words[index] == w1)
{
for ( int search = 0;
search < words.size(); search++)
{
if (words[search] == w2)
{
int curr = abs (index - search) - 1;
if (curr < min_dist)
min_dist = curr;
}
}
}
}
return min_dist;
}
int main( int argc, char const *argv[])
{
string s = "geeks for geeks contribute practice" ;
string w1 = "geeks" ;
string w2 = "practice" ;
cout << distance(s, w1, w2) << endl;
return 0;
}
|
Java
class solution
{
static int distance(String s,String w1,String w2)
{
if (w1 .equals( w2) )
return 0 ;
String words[] = s.split( " " );
int min_dist = (words.length) + 1 ;
for ( int index = 0 ;
index < words.length ; index ++)
{
if (words[index] .equals( w1))
{
for ( int search = 0 ;
search < words.length; search ++)
{
if (words[search] .equals(w2))
{
int curr = Math.abs(index - search) - 1 ;
if (curr < min_dist)
{
min_dist = curr ;
}
}
}
}
}
return min_dist;
}
public static void main(String args[])
{
String s = "geeks for geeks contribute practice" ;
String w1 = "geeks" ;
String w2 = "practice" ;
System.out.print( distance(s, w1, w2) );
}
}
|
Python3
def distance(s, w1, w2):
if w1 = = w2 :
return 0
words = s.split( " " )
min_dist = len (words) + 1
for index in range ( len (words)):
if words[index] = = w1:
for search in range ( len (words)):
if words[search] = = w2:
curr = abs (index - search) - 1 ;
if curr < min_dist:
min_dist = curr
return min_dist
s = "geeks for geeks contribute practice"
w1 = "geeks"
w2 = "practice"
print (distance(s, w1, w2))
|
C#
using System;
class solution
{
static int distance( string s, string w1, string w2)
{
if (w1 .Equals( w2) )
return 0 ;
string [] words = s.Split( " " );
int min_dist = (words.Length) + 1;
for ( int index = 0;
index < words.Length ; index ++)
{
if (words[index] .Equals( w1))
{
for ( int search = 0;
search < words.Length; search ++)
{
if (words[search] .Equals(w2))
{
int curr = Math.Abs(index - search) - 1;
if (curr < min_dist)
{
min_dist = curr ;
}
}
}
}
}
return min_dist;
}
public static void Main()
{
string s = "geeks for geeks contribute practice" ;
string w1 = "geeks" ;
string w2 = "practice" ;
Console.Write( distance(s, w1, w2) );
}
}
|
PHP
<?php
function distance( $s , $w1 , $w2 )
{
if ( $w1 == $w2 )
return 0 ;
$words = explode ( " " , $s );
$min_dist = sizeof( $words ) + 1;
for ( $index = 0;
$index < sizeof( $words ) ; $index ++)
{
if ( $words [ $index ] == $w1 )
{
for ( $search = 0;
$search < sizeof( $words ); $search ++)
{
if ( $words [ $search ] == $w2 )
{
$curr = abs ( $index - $search ) - 1;
if ( $curr < $min_dist )
{
$min_dist = $curr ;
}
}
}
}
}
return $min_dist ;
}
$s = "geeks for geeks contribute practice" ;
$w1 = "geeks" ;
$w2 = "practice" ;
echo distance( $s , $w1 , $w2 ) ;
?>
|
Javascript
<script>
function distance(s,w1,w2) {
if (w1 ==( w2) )
return 0 ;
let words = s.split( " " );
let min_dist = (words.length) + 1;
for (let index = 0;
index < words.length ; index ++)
{
if (words[index] == ( w1))
{
for (let search = 0;
search < words.length; search ++)
{
if (words[search] == (w2))
{
let curr = Math.abs(index - search) - 1;
if (curr < min_dist)
{
min_dist = curr ;
}
}
}
}
}
return min_dist;
}
let s = "geeks for geeks contribute practice" ;
let w1 = "geeks" ;
let w2 = "practice" ;
document.write( distance(s, w1, w2) );
</script>
|
Complexity Analysis:
- Time Complexity: O(n2)
- Auxiliary Space: O(n)
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:
C++
#include<bits/stdc++.h>
using namespace std;
int distance(string s, string w1, string w2)
{
if (w1 == w2)
{
return 0;
}
vector<string> words;
istringstream ss(s);
string word;
while (ss >> word)
{
words.push_back(word);
}
int n = words.size();
int min_dist = n + 1;
int prev = 0, i = 0;
for (i = 0; i < n; i++)
{
if (words[i] == w1 || (words[i] == w2))
{
prev = i;
break ;
}
}
while (i < n)
{
if (words[i] == w1 || (words[i] == w2))
{
if ((words[prev] != words[i]) &&
(i - prev) < min_dist)
{
min_dist = i - prev - 1;
prev = i;
}
else
{
prev = i;
}
}
i += 1;
}
return min_dist;
}
int main()
{
string s = "geeks for geeks contribute practice" ;
string w1 = "geeks" ;
string w2 = "practice" ;
cout<<distance(s, w1, w2);
}
|
Java
class GFG {
static int distance(String s, String w1, String w2) {
if (w1.equals(w2)) {
return 0 ;
}
String[] words = s.split( " " );
int n = words.length;
int min_dist = n + 1 ;
int prev = 0 , i = 0 ;
for (i = 0 ; i < n; i++) {
if (words[i].equals(w1) || words[i].equals(w2)) {
prev = i;
break ;
}
}
while (i < n) {
if (words[i].equals(w1) || words[i].equals(w2)) {
if ((!words[prev].equals(words[i])) && (i - prev) < min_dist) {
min_dist = i - prev - 1 ;
prev = i;
} else {
prev = i;
}
}
i += 1 ;
}
return min_dist;
}
public static void main(String[] args) {
String s = "geeks for geeks contribute practice" ;
String w1 = "geeks" ;
String w2 = "practice" ;
System.out.println(distance(s, w1, w2));
}
}
|
C#
using System;
class GFG
{
static int distance(String s, String w1, String w2)
{
if (w1.Equals(w2))
{
return 0;
}
String[] words = s.Split( " " );
int n = words.Length;
int min_dist = n + 1;
int prev = 0, i = 0;
for (i = 0; i < n; i++)
{
if (words[i].Equals(w1) || words[i].Equals(w2))
{
prev = i;
break ;
}
}
while (i < n)
{
if (words[i].Equals(w1) || words[i].Equals(w2))
{
if ((!words[prev].Equals(words[i])) &&
(i - prev) < min_dist)
{
min_dist = i - prev - 1;
prev = i;
}
else
{
prev = i;
}
}
i += 1;
}
return min_dist;
}
public static void Main(String[] args)
{
String s = "geeks for geeks contribute practice" ;
String w1 = "geeks" ;
String w2 = "practice" ;
Console.Write(distance(s, w1, w2));
}
}
|
Python3
def distance(s, w1, w2):
if w1 = = w2 :
return 0
words = s.split( " " )
n = len (words)
min_dist = n + 1
for i in range (n):
if words[i] = = w1 or words[i] = = w2:
prev = i
break
while i < n:
if words[i] = = w1 or words[i] = = w2:
if words[prev] ! = words[i] and (i - prev) < min_dist :
min_dist = i - prev - 1
prev = i
else :
prev = i
i + = 1
return min_dist
s = "geeks for geeks contribute practice"
w1 = "geeks"
w2 = "practice"
print (distance(s, w1, w2))
|
Javascript
<script>
function distance(s,w1,w2)
{
if (w1 == (w2))
{
return 0;
}
let words = s.split( " " );
let n = words.length;
let min_dist = n + 1;
let prev = 0, i = 0;
for (i = 0; i < n; i++)
{
if (words[i] == (w1) || words[i] == (w2))
{
prev = i;
break ;
}
}
while (i < n)
{
if (words[i] == (w1) || words[i] == (w2))
{
if ((words[prev] != (words[i])) && (i - prev) < min_dist) {
min_dist = i - prev - 1;
prev = i;
} else {
prev = i;
}
}
i += 1;
}
return min_dist;
}
let s = "geeks for geeks contribute practice" ;
let w1 = "geeks" ;
let w2 = "practice" ;
document.write(distance(s, w1, w2));
</script>
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(1)
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:
C++
#include <bits/stdc++.h>
using namespace std;
int shortestDistance(vector<string> &s, string word1, string word2)
{
if (word1==word2) return 0;
int ans = INT_MAX;
int lastPos = -1;
for ( int i = 0 ; i < s.size() ; i++)
{
if (s[i] == word1 || s[i] == word2)
{
if (lastPos == -1)
lastPos = i;
else
{
if (s[lastPos]==s[i])
lastPos = i;
else
{
ans = min(ans , (i-lastPos)-1);
lastPos = i;
}
}
}
}
return ans;
}
int main() {
vector<string> s{ "geeks" , "for" , "geeks" , "contribute" ,
"practice" };
string w1 = "geeks" ;
string w2 = "practice" ;
cout<<shortestDistance(s, w1, w2)<< "\n" ;
return 0;
}
|
Java
import java.util.ArrayList;
class Demo {
static int shortestDistance(ArrayList<String> list,
String word1, String word2)
{
if (word1 == word2)
return 0 ;
int ans = Integer.MAX_VALUE;
int lastPos = - 1 ;
for ( int i = 0 ; i < list.size(); i++) {
if (list.get(i) == word1
|| list.get(i) == word2) {
if (lastPos == - 1 )
lastPos = i;
else {
if (list.get(lastPos) == list.get(i))
lastPos = i;
else {
ans = Math.min(ans,
((i - lastPos) - 1 ));
lastPos = i;
}
}
}
}
return ans;
}
public static void main(String arg[])
{
ArrayList<String> list = new ArrayList<>();
list.add( "geeks" );
list.add( "for" );
list.add( "geeks" );
list.add( "contribute" );
list.add( "practice" );
String w1 = "geeks" ;
String w2 = "practice" ;
System.out.println(shortestDistance(list, w1, w2));
}
}
|
Python
def shortestDistance(s, word1, word2):
if (word1 = = word2):
return 0
ans = 1e9 + 7
lastPos = - 1
for i in range ( 0 , len (s)):
if (s[i] = = word1 or s[i] = = word2):
if (lastPos = = - 1 ):
lastPos = i
else :
if (s[lastPos] = = s[i]):
lastPos = i
else :
ans = min (ans, (i - lastPos) - 1 )
lastPos = i
return ans
s = [ "geeks" , "for" , "geeks" , "contribute" , "practice" ]
w1 = "geeks"
w2 = "practice"
print (shortestDistance(s, w1, w2))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static int shortestDistance(List< string > list,
string word1, string word2)
{
if (word1 == word2)
return 0;
int ans = Int32.MaxValue;
int lastPos = -1;
for ( int i = 0; i < list.Count; i++) {
if (list[i] == word1 || list[i] == word2) {
if (lastPos == -1)
lastPos = i;
else {
if (list[lastPos] == list[i])
lastPos = i;
else {
ans = Math.Min(ans,
((i - lastPos) - 1));
lastPos = i;
}
}
}
}
return ans;
}
public static void Main( string [] arg)
{
List< string > list = new List< string >();
list.Add( "geeks" );
list.Add( "for" );
list.Add( "geeks" );
list.Add( "contribute" );
list.Add( "practice" );
string w1 = "geeks" ;
string w2 = "practice" ;
Console.WriteLine(shortestDistance(list, w1, w2));
}
}
|
Javascript
function shortestDistance(s, word1, word2)
{
if (word1==word2)
return 0;
let ans = Number.MAX_SAFE_INTEGER;
let lastPos = -1;
for (let i = 0 ; i < s.length ; i++)
{
if (s[i] == word1 || s[i] == word2)
{
if (lastPos == -1)
lastPos = i;
else
{
if (s[lastPos]==s[i])
lastPos = i;
else
{
ans = Math.min(ans , (i-lastPos)-1);
lastPos = i;
}
}
}
}
return ans;
}
let s=[ "geeks" , "for" , "geeks" , "contribute" , "practice" ];
let w1 = "geeks" ;
let w2 = "practice" ;
console.log(shortestDistance(s, w1, w2));
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
12 Dec, 2022
Like Article
Save Article