Shortest Word Distance - Python Solution

1. Introduction

The "Shortest Word Distance" problem is an interesting challenge often encountered in text processing and analysis. It involves finding the minimum distance between two given words in a list of words. This problem tests the ability to efficiently navigate and compare elements within an array or list, a common task in data processing and manipulation.

Problem

Given an array of words wordsDict and two words word1 and word2, return the shortest distance between these two words in the list. The distance between two words is defined as the absolute difference between their indices in the list.

2. Solution Steps

1. Initialize two variables index1 and index2 to store the latest indices of word1 and word2, respectively. Set them to -1 initially.

2. Initialize a variable minDistance to keep track of the minimum distance found so far.

3. Iterate over wordsDict.

4. If the current word is word1, update index1.

5. If the current word is word2, update index2.

6. If both indices are not -1, calculate the distance and update minDistance if it's smaller than the current minDistance.

7. Return minDistance after the iteration.

3. Code Program

def shortestDistance(wordsDict, word1, word2):
    index1 = index2 = -1
    minDistance = len(wordsDict)

    for i, word in enumerate(wordsDict):
        if word == word1:
            index1 = i
        elif word == word2:
            index2 = i

        if index1 != -1 and index2 != -1:
            minDistance = min(minDistance, abs(index1 - index2))

    return minDistance

# Example Usage
print(shortestDistance(["practice", "makes", "perfect", "coding", "makes"], "coding", "practice"))  # Output: 3
print(shortestDistance(["practice", "makes", "perfect", "coding", "makes"], "makes", "coding"))     # Output: 1

Output:

3
1

Explanation:

1. Index Tracking: Maintains the latest positions of word1 and word2 in the list.

2. Distance Calculation: Computes the distance whenever both words have appeared at least once.

3. Efficient Solution: Iterates through the list once, achieving O(n) time complexity.

4. Minimum Distance Update: Continuously updates the smallest distance found.

5. Practical Use Case: Useful in various scenarios involving text analysis and word proximity in documents.


Comments