Minimum distance between the given two words Last Updated : 23 Feb, 2025 Comments Improve Suggest changes Like Article Like Report Try it on GfG Practice 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: 3Explanation: Minimum distance between the words "the" and "fox" is 3Input: S = {"geeks", "for", "geeks", "contribute", "practice"}, word1 = "geeks", word2 = "practice"Output: 2Explanation: Minimum distance between the words "geeks" and "practice" is 2Approach: 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)); Output3Time Complexity: O(n*m), where n is number of strings and m is size of maximum string.Auxiliary Space: O(1) Comment More infoAdvertise with us Next Article Minimum distance between the given two words akashjha2671 Follow Improve Article Tags : Strings Greedy Technical Scripter DSA Arrays Technical Scripter 2022 +2 More Practice Tags : ArraysGreedyStrings Similar Reads Find the minimum distance between two numbers Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[]. Examples: Input: arr[] = {1, 2}, x = 1, y = 2Output: Minimum distance between 1 and 15+ min read Distance between two closest minimum Given an array of n integers. Find the minimum distance between any two occurrences of the minimum integer in the array. Examples: Input : arr[] = {5, 1, 2, 3, 4, 1, 2, 1} Output : 2 Explanation: The minimum element 1 occurs at indexes: 1, 5 and 7. So the minimum distance is 7-5 = 2. Input : arr[] = 10 min read Minimum distance between duplicates in a String Given a string S and its length N (provided N > 0). The task is to find the minimum distance between same repeating characters, if no repeating characters present in string S return -1. Examples: Input: S = "geeksforgeeks", N = 13Output: 0 Explanation: The repeating characters in string S = "geek 15+ min read Minimum distance between any special pair in the given array Given an array arr[] of N integers, the task is to find the minimum possible absolute difference between indices of a special pair. A special pair is defined as a pair of indices (i, j) such that if arr[i] ? arr[j], then there is no element X (where arr[i] < X < arr[j]) present in between indi 9 min read Sum of minimum and the maximum difference between two given Strings Given two strings S1 and S2 of the same length. The task is to find the sum of the minimum and the maximum difference between two given strings if you are allowed to replace the character '+' in the strings with any other character.Note: If two strings have the same characters at every index, then t 8 min read Find Shortest Word Distance II Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array. Implement the WordDistance class: WordDistance(String[] wordsDict): constructor to initialize the object with the strings arr 7 min read POTD Solutions | 02 Novâ 23 | Minimum distance between two numbers View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Arrays but will also help you build up problem-solving 5 min read Check if edit distance between two strings is one An edit between two strings is one of the following changes. Add a characterDelete a characterChange a characterGiven two strings s1 and s2, find if s1 can be converted to s2 with exactly one edit. Note: Even if the strings are already equal, one edit operation can still be considered valid by "chan 14 min read Minimum distance between any two equal elements in an Array Given an array arr, the task is to find the minimum distance between any two same elements in the array. If no such element is found, return -1. Examples: Input: arr = {1, 2, 3, 2, 1} Output: 2 Explanation: There are two matching pairs of values: 1 and 2 in this array. Minimum Distance between two 1 11 min read Minimum count of words among all the given sentences Given N lowercase sentences, the task is to find the minimum count of words among all of these sentences. Examples: Input: arr[] = { âthere is a cowâ, âcow is our motherâ, âcow gives us milk and milk is sweetâ, âthere is a boy who loves cowâ} Output: 4Explanation: Both 1st and the second sentence ha 6 min read Like