Skip to main content

Shortest Word Distance III

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 176 ms)​

MetricValue
Runtime176 ms
Memory52.5 MB
Date2022-01-28
Solution
public class Solution {
public int ShortestWordDistance(string[] wordsDict, string word1, string word2) {
int min = Int32.MaxValue, index1 = -1, index2 = -1, prev = -1;
if(word1.Equals(word2))
{
for(int i=0;i<wordsDict.Length;i++)
{
if(wordsDict[i].Equals(word1))
{
if(prev != -1) min = Math.Min(min, i-prev);
prev = i;
}
}

}
else {
for(int i=0;i<wordsDict.Length;i++)
{
if(wordsDict[i].Equals(word1))
{
index1 = i;
if(index2 != -1) min = Math.Min(min, index1-index2);
}
if(wordsDict[i].Equals(word2))
{
index2 = i;
if(index1 != -1) min = Math.Min(min, index2-index1);
}
}
}
return min;

}
}
πŸ“œ 1 more C# submission(s)

Submission (2022-01-28) β€” 180 ms, 52.1 MB​

public class Solution {
public int ShortestWordDistance(string[] wordsDict, string word1, string word2) {
int min = Int32.MaxValue, index1 = -1, index2 = -1, prev = -1;
bool isSame = word1.Equals(word2);
for (int i = 0; i < wordsDict.Length; i++)
{
if (isSame)
{
if (wordsDict[i].Equals(word1))
{
if (prev != -1) min = Math.Min(min, i - prev);
prev = i;
}
}
else
{
if (wordsDict[i].Equals(word1))
{
index1 = i;
}
if (wordsDict[i].Equals(word2))
{
index2 = i;
}
if (index1 != -1 && index2 != -1) min = Math.Min(min, Math.Abs(index1 - index2));

}
}
return min;

}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed