Leetcode 243. Shortest Word Distance

Problem explanation:

Given a list of words along with two others words, word1 and word2, we are to find out the shortest distance between these two words in the list of given words. We will be returning an integer as the answer which represents the minimum distance between the two words in the list.

Example:

Let's walk through one example:

Given: words = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"

In this case, we have the word "makes" appearing twice in the list and the word "coding" which appears once. The minimum distance between "makes" and "coding" is 1 as they are adjacent to each other in the list. Hence, the output is 1.

Approach of the solution:

We will be using two pointers to keep track of the last occurrences of the two words in the list. As we iterate through the list, we update the pointers when we find a match to either of the two words. All the while, we also calculate the shortest distance encountered so far.

Python solution:

1
2python
3class Solution:
4    def shortestDistance(self, wordsDict, word1, word2):
5        index1 = -1 # position of word1
6        index2 = -1 # position of word2
7        ans = len(wordsDict) # initialize with maximum possible distance
8
9        for i, word in enumerate(wordsDict):
10            if word == word1:
11                index1 = i
12                if index2 != -1:
13                    ans = min(ans, index1 - index2)
14            if word == word2:
15                index2 = i
16                if index1 != -1:
17                    ans = min(ans, index2 - index1)
18        return ans

Java solution:

1
2java
3public class Solution {
4    public int shortestDistance(String[] wordsDict, String word1, String word2) {
5        int index1 = -1;  // Index of word1 in wordsDict
6        int index2 = -1;  // Index of word2 in wordsDict
7        int ans = wordsDict.length;  // Initialize with maximum possible distance
8
9        for (int i = 0; i < wordsDict.length; ++i) {
10            if (wordsDict[i].equals(word1)) {
11                index1 = i;
12                if (index2 != -1) {
13                    ans = Math.min(ans, index1 - index2);
14                }
15            }
16            if (wordsDict[i].equals(word2)) {
17                index2 = i;
18                if (index1 != -1) {
19                    ans = Math.min(ans, index2 - index1);
20                }
21            }
22        }
23        return ans;
24    }
25}

JavaScript solution:

1
2javascript
3class Solution {
4    shortestDistance(wordsDict, word1, word2) {
5        let index1 = -1; // Index of word1 in wordsDict
6        let index2 = -1; // Index of word2 in wordsDict
7        let ans = wordsDict.length; // Initialize with maximum possible distance
8    
9        for (let i = 0; i < wordsDict.length; ++i) {
10            if (wordsDict[i] == word1) {
11                index1 = i;
12                if (index2 !== -1)
13                    ans = Math.min(ans, index1 - index2);
14            }
15            if (wordsDict[i] == word2) {
16                index2 = i;
17                if (index1 !== -1)
18                    ans = Math.min(ans, index2 - index1);
19            }
20        }
21
22        return ans;
23    }
24}

C++ solution:

1
2c++
3class Solution {
4public:
5    int shortestDistance(vector<string>& wordsDict, string word1, string word2) {
6        int index1 = -1; // Index of word1 in wordsDict
7        int index2 = -1; // Index of word2 in wordsDict
8        int ans = wordsDict.size(); // Initialize with maximum possible distance
9    
10        for (int i = 0; i < wordsDict.size(); ++i) {
11            if (wordsDict[i] == word1) {
12                index1 = i;
13                if (index2 != -1)
14                    ans = min(ans, index1 - index2);
15            }
16            if (wordsDict[i] == word2) {
17                index2 = i;
18                if (index1 != -1)
19                    ans = min(ans, index2 - index1);
20            }
21        }
22
23        return ans;
24    }
25};

C# solution:

1
2csharp
3public class Solution {
4    public int ShortestDistance(string[] wordsDict, string word1, string word2) {
5        int index1 = -1;  // Index of word1 in wordsDict
6        int index2 = -1;  // Index of word2 in wordsDict
7        int ans = wordsDict.Length;  // Initialize with maximum possible distance
8
9        for (int i = 0; i < wordsDict.Length; ++i) {
10            if (wordsDict[i] == word1) {
11                index1 = i;
12                if (index2 != -1) {
13                    ans = Math.Min(ans, index1 - index2);
14                }
15            }
16            if (wordsDict[i] == word2) {
17                index2 = i;
18                if (index1 != -1) {
19                    ans = Math.Min(ans, index2 - index1);
20                }
21            }
22        }
23        return ans;
24    }
25}

Time Complexity Analysis:

The time complexity for this problem is O(n), where n is the number of words in the list. This is because we have to iterate over the entire list to find the shortest distance between the two given words.

This solution does not require any additional space, so the space complexity is O(1), making this solution quite efficient.

Conclusion:

This problem demonstrates an important concept in computer programming - the pointer or cursor. It also teaches us to wisely choose the right data structure for the right problem. Here, it was not necessary to store the entire list in memory. We only needed the indices of the last occurrences of the two words, which was accomplished by using two pointers. Keeping track of these indices and the minimum distance so far allowed us to solve the problem efficiently.

Therefore, it's a good practice to understand the properties of the data you are dealing with before diving into coding. Often, it's not necessary to use complicated data structures to get the job done. The use of simple variables, conditionals and loops can be quite powerful as this problem demonstrates.

Remember, a code is as good as its simplicity and efficiency. The more you keep practicing, the more you become efficient. Practice coding every day, and you will soon find yourself writing efficient and clean code effortlessly. Happy coding!

Please feel free to reach out if you have any questions or comments about this solution!


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫