LeetCode 245: Shortest Word Distance III
LeetCode 245 Solution Explanation
Explanation
To solve this problem, we can iterate through the input array of words and keep track of the indices of the two target words. We update the indices as we encounter the target words. We then calculate the minimum distance between the two indices. If the words can be the same, we need to handle the case where the two indices are the same.
Algorithm:
- Initialize variables
index1
,index2
, andminDistance
to track the indices and minimum distance. - Iterate through the input
words
array:- If the current word is equal to
word1
, updateindex1
. - If the current word is equal to
word2
, updateindex2
. - If both indices are valid, calculate the distance and update
minDistance
. - If
word1
andword2
are the same, handle the case whereindex1
andindex2
are the same.
- If the current word is equal to
- Finally, return
minDistance
.
Time Complexity: O(n) where n is the number of words in the input array.
Space Complexity: O(1)
LeetCode 245 Solutions in Java, C++, Python
class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
int index1 = -1, index2 = -1;
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
index1 = i;
}
if (words[i].equals(word2)) {
if (word1.equals(word2)) {
index1 = index2;
}
index2 = i;
}
if (index1 != -1 && index2 != -1) {
minDistance = Math.min(minDistance, Math.abs(index1 - index2));
}
}
return minDistance;
}
}
Interactive Code Editor for LeetCode 245
Improve Your LeetCode 245 Solution
Use the editor below to refine the provided solution for LeetCode 245. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...