Open In App

Minimum distance between the given two words

Last Updated : 23 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list of words followed by two words, the task is to find the minimum distance between the given two words in the list of words.

Examples:

Input: S = { "the", "quick", "brown", "fox", "quick"}, word1 = "the", word2 = "fox"
Output: 3
Explanation: Minimum distance between the words "the" and "fox" is 3

Input: S = {"geeks", "for", "geeks", "contribute",  "practice"}, word1 = "geeks", word2 = "practice"
Output: 2
Explanation: Minimum distance between the words "geeks" and "practice" is 2

Approach: Follow the steps to solve this problem:

  • Initialize the variables d1 = -1, d2 = -1 and ans = INTEGER MAXIMUM.
  • Traverse the string and check:
    • If, s[i] is word1 then update d1 = i.
    • If, s[i] is word2 then update d2 = i.
    • If, d1 != -1 and d2 != -1, then update ans = min(ans, abs(d1-d2)).
  • After traversing the string, return ans.

Below is the implementation of the above approach.

C++
// C++ code to find the minimum distance
// between the given two words
#include <bits/stdc++.h>
using namespace std;

// Function to return shortest distance
int shortestDistance(vector<string>& s, 
string word1, string word2) {
    int d1 = -1, d2 = -1;
    int ans = INT_MAX;

    // Traverse the string
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == word1)
            d1 = i;
        if (s[i] == word2)
            d2 = i;
        if (d1 != -1 && d2 != -1)
            ans = min(ans, abs(d1 - d2));
    }

    // Return the answer
    return ans;
}

int main() {
    vector<string> S
        = { "the", "quick", "brown", "fox", "quick" };

    string word1 = "the", word2 = "fox";

    cout << shortestDistance(S, word1, word2);

    return 0;
}
Java
// Java code to find the minimum distance
// between the given two words

import java.util.*;

class GfG {

    // Function to return shortest distance
    static int shortestDistance(ArrayList<String> s, 
    String word1, String word2) {
        int d1 = -1, d2 = -1;
        int ans = Integer.MAX_VALUE;

        // Traverse the string
        for (int i = 0; i < s.size(); i++) {
            if (s.get(i).equals(word1))
                d1 = i;
            if (s.get(i).equals(word2))
                d2 = i;
            if (d1 != -1 && d2 != -1)
                ans = Math.min(ans, Math.abs(d1 - d2));
        }

        // Return the answer
        return ans;
    }

    public static void main(String[] args) {
        ArrayList<String> S = 
        new ArrayList<>(Arrays.asList("the", 
        "quick", "brown", "fox", "quick"));

        String word1 = "the", word2 = "fox";

        System.out.println(shortestDistance(S, word1, word2));
    }
}
Python
# Python code to find the minimum distance
# between the given two words

# Function to return shortest distance
def shortestDistance(s, word1, word2):
    d1 = -1
    d2 = -1
    ans = float('inf')

    # Traverse the string
    for i in range(len(s)):
        if s[i] == word1:
            d1 = i
        if s[i] == word2:
            d2 = i
        if d1 != -1 and d2 != -1:
            ans = min(ans, abs(d1 - d2))

    # Return the answer
    return ans

if __name__ == "__main__":
    S = ["the", "quick", "brown", "fox", "quick"]

    word1 = "the"
    word2 = "fox"

    print(shortestDistance(S, word1, word2))
C#
// C# code to find the minimum distance
// between the given two words

using System;
using System.Collections.Generic;

class GfG {

    // Function to return shortest distance
    static int shortestDistance(List<string> s, 
    string word1, string word2) {
        int d1 = -1, d2 = -1;
        int ans = int.MaxValue;

        // Traverse the string
        for (int i = 0; i < s.Count; i++) {
            if (s[i] == word1)
                d1 = i;
            if (s[i] == word2)
                d2 = i;
            if (d1 != -1 && d2 != -1)
                ans = Math.Min(ans, Math.Abs(d1 - d2));
        }

        // Return the answer
        return ans;
    }

    static void Main(string[] args) {
        List<string> S = new List<string> 
        { "the", "quick", "brown", "fox", "quick" };

        string word1 = "the", word2 = "fox";

        Console.WriteLine(shortestDistance(S, word1, word2));
    }
}
JavaScript
// JavaScript code to find the minimum distance
// between the given two words

// Function to return shortest distance
function shortestDistance(s, word1, word2) {
    let d1 = -1, d2 = -1;
    let ans = Number.MAX_VALUE;

    // Traverse the string
    for (let i = 0; i < s.length; i++) {
        if (s[i] === word1)
            d1 = i;
        if (s[i] === word2)
            d2 = i;
        if (d1 !== -1 && d2 !== -1)
            ans = Math.min(ans, Math.abs(d1 - d2));
    }

    // Return the answer
    return ans;
}

let S = ["the", "quick", "brown", "fox", "quick"];

let word1 = "the", word2 = "fox";

console.log(shortestDistance(S, word1, word2));

Output
3

Time Complexity: O(n*m), where n is number of strings and m is size of maximum string.
Auxiliary Space: O(1)


Next Article

Similar Reads