243 Shortest Word Distance

Given a list of words and two wordsword1andword2, return the shortest distance between these two words in the list.

For example, Assume that words =["practice", "makes", "perfect", "coding", "makes"].

Givenword1=“coding”,word2=“practice”, return 3. Givenword1="makes",word2="coding", return 1.

Note: You may assume thatword1does not equal toword2, andword1andword2are both in the list.

Attempt 1

  #include <iostream>
  #include <vector>
  #include <math.h>
  #include <algorithm>

  using namespace std;

  int shortestDistance(vector<string> *words, string word1, string word2)
  {

      vector<int> minElements;
      vector<int> word1Positions;
      vector<int> word2Positions;

      int word1Pos, word2Pos;
      int size = (*words).size();

      for (int i = 0; i < size; i++)
      {
          // store all positions of first word
          string currentWord = (*words).at(i);
          if (currentWord == word1)
              word1Positions.push_back(i);
          else if(currentWord == word2)
              word2Positions.push_back(i);
      }

      // find the minimum displacement between each word
      int difference;
      int j = 0;
      while (word2Positions.size() > j)
      {
          for (int i = 0; i < word1Positions.size(); i++)
          {
              difference = abs(((word1Positions).at(i)) - ((word2Positions).at(j)));
              minElements.push_back(difference);
          }
          j++;
      }

      int minElement = *min_element(minElements.begin(), minElements.end());
      cout << minElement << endl;
      return minElement;

  }

  int main()
  {
      vector<string> words = { "practice", "makes", "perfect", "coding", "makes" };

      string word1 = "coding", word2 = "practice"; // 3
      string word3 = "makes", word4 = "coding"; // 1

      shortestDistance(&words, word1, word2);
      shortestDistance(&words, word3, word4);
  }

Attempt 2: (12 ms, 92 percentile)

The Idea: First locate the occurrences of both words into two arrays. The shortest difference would then just be the minimum absolute difference between these two arrays. More specifically, it would be the minimum pair wise combination between the two arrays. We can perform two improvements here: first, since the arrays are sorted, we can binary search for the minimum difference. Secondly, we can scale better if we binary search on the larger array group. We know that we found the minimum difference when both the left and right side of the element produce a larger difference with the current key.

Complexity: O(NlogN) time, O(N) space

Testing

Last updated

Was this helpful?