LeetCode 243: Shortest Word Distance Solution
Master LeetCode problem 243 (Shortest Word Distance), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
The problem asks us to find the shortest distance between two words in a given list of words. We need to find the minimum distance between the two words.
To solve this problem, we can iterate through the list of words and keep track of the indices of the two words we are looking for. As we iterate, we update the minimum distance whenever we find a pair of indices for the two words.
- Time complexity: O(n), where n is the number of words in the list.
- Space complexity: O(1)
Solution Code
class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
int index1 = -1;
int index2 = -1;
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
index1 = i;
} else if (words[i].equals(word2)) {
index2 = i;
}
if (index1 != -1 && index2 != -1) {
minDistance = Math.min(minDistance, Math.abs(index1 - index2));
}
}
return minDistance;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 243 (Shortest Word Distance)?
This page provides optimized solutions for LeetCode problem 243 (Shortest Word Distance) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 243 (Shortest Word Distance)?
The time complexity for LeetCode 243 (Shortest Word Distance) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 243 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 243 in Java, C++, or Python.