245. Shortest Word Distance III

Description

Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2, return the shortest distance between 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 = "coding", word2 = "practice"
Output: 3

Example 2:

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

Constraints:

  • 1 <= wordsDict.length <= 3 * 104

  • 1 <= wordsDict[i].length <= 10

  • wordsDict[i] consists of lowercase English letters.

  • word1 and word2 are in wordsDict.

Tags

Array

Solution

Based on the answer of LeetCode 243. Shortest Word Distance, we add a statement for the case when word1 and word2 are identical.

if word1 == word2 && p1 != -1 && i-p1 < ans {
    ans = i - p1
}

Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(1)O(1)

Code

func shortestWordDistance(wordsDict []string, word1 string, word2 string) int {
	ans, p1, p2 := 1<<31, -1, -1
	for i, w := range wordsDict {
		if w == word1 {
			if word1 == word2 && p1 != -1 && i-p1 < ans {
				ans = i - p1
			}
			p1 = i
		} else if w == word2 {
			p2 = i
		}
		if p1 != -1 && p2 != -1 {
			if n := abs(p1 - p2); n < ans {
				ans = n
			}
		}
	}
	return ans
}

func abs(a int) int {
	if a < 0 {
		return -1 * a
	}
	return a
}

Last updated

Was this helpful?