LeetCode 0245. Shortest Word Distance III Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0245. Shortest Word Distance III

Description

Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list.

Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.

 

Example 1:

Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
Output: 1

Example 2:

Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "makes"
Output: 3

 

Constraints:

  • 1 <= wordsDict.length <= 105
  • 1 <= wordsDict[i].length <= 10
  • wordsDict[i] consists of lowercase English letters.
  • word1 and word2 are in wordsDict.

Solutions

Solution 1: Case Analysis

First, we check whether word1 and word2 are equal:

  • If they are equal, iterate through the array wordsDict to find two indices i and j of word1, and compute the minimum value of i-j.
  • If they are not equal, iterate through the array wordsDict to find the indices i of word1 and j of word2, and compute the minimum value of i-j.

The time complexity is O(n), where n is the length of the array wordsDict. The space complexity is O(1).

PythonJavaC++GoTypeScript
class Solution: def shortestWordDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: ans = len(wordsDict) if word1 == word2: j = -1 for i, w in enumerate(wordsDict): if w == word1: if j != -1: ans = min(ans, i - j) j = i else: i = j = -1 for k, w in enumerate(wordsDict): if w == word1: i = k if w == word2: j = k if i != -1 and j != -1: ans = min(ans, abs(i - j)) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !