Skip to main content

Shortest Word Distance

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

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

MetricValue
Runtime97 ms
Memory38.8 MB
Date2022-01-28
Solution
public class Solution {
public int ShortestDistance(string[] wordsDict, string word1, string word2) {
int min = Int32.MaxValue, index1 = -1, index2 = -1;
for(int i=0;i<wordsDict.Length;i++)
{
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;
}
}
πŸ“œ 1 more C# submission(s)

Submission (2022-01-27) β€” 122 ms, 38.7 MB​

public class Solution {
public int ShortestDistance(string[] wordsDict, string word1, string word2) {
int min = Int32.MaxValue, index1 = -1, index2 = -1;
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;
}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed