Shortest Word Distance II in C++

C++Server Side ProgrammingProgramming

Suppose there is a class that receives a list of words in the constructor, there will be a method that takes two words word1 and word2 and find the shortest distance between these two words in the list. That method will be called repeatedly many times with different parameters.

Let us assume that words = ["practice", "makes", "perfect", "skill", "makes"].

So, if the input is like word1 = “skill”, word2 = “practice”, then the output will be 3

To solve this, we will follow these steps −

  • Define one map m

  • The initializer takes an array of words

    • for initialize i := 0, when i < size of words, update (increase i by 1), do −

      • insert i at the end of m[words[i]]

  • Define a function shortest(), this will take word1, word2,

  • Define an array arr1 := m[word1]

  • Define an array arr2 := m[word2]

  • i := 0, j := 0

  • ret := infinity

  • while (i < size of arr1 and j < size of arr2), do −

    • ret := minimum of ret and |arr1[i] - arr2[j]|

    • if arr1[i] < arr2[j], then −

      • (increase i by 1)

    • Otherwise

      • (increase j by 1)

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class WordDistance {
public:
   unordered_map <string, vector <int< > m;
   WordDistance(vector<string<& words) {
      for(int i = 0; i < words.size(); i++){
         m[words[i]].push_back(i);
      }
   }
   int shortest(string word1, string word2) {
      vector<int<& arr1 = m[word1];
      vector<int<& arr2 = m[word2];
      int i = 0;
      int j = 0;
      int ret = INT_MAX;
      while (i < arr1.size() && j < arr2.size()) {
         ret = min(ret, abs(arr1[i] - arr2[j]));
         if (arr1[i] < arr2[j]) {
            i++;
         }
         else
            j++;
      }
      return ret;
   }
};
main(){
   vector<string< v = {"practice", "makes", "perfect", "skill","makes"};
   WordDistance ob(v);
   cout << (ob.shortest("skill", "practice")) << endl;
   cout << (ob.shortest("makes", "skill"));
}

Input

{"practice", "makes", "perfect", "skill", "makes"}
Call shortest("skill", "practice")
Call shortest("makes", "skill")

Output

3
1
raja
Published on 18-Nov-2020 11:16:39
Advertisements