📘
Shortest Word Distance
EasyStrings & Arrays
Given a list of words and two different words, find the shortest distance between them in the list (measured by index difference).
Example:
Input:
practice,makes,perfect,coding,makes practice coding
Output:
3
Reasoning:
- The input list of words is split into individual words:
practice,makes,perfect,coding,makes - The two target words are identified:
practiceandcoding - The indices of these words in the list are found:
practiceis at index 0 andcodingis at index 3 - The shortest distance between them is calculated as the absolute difference in their indices: ∣0−3∣=3
- The final output is the calculated shortest distance: 3
Constraints:
- 2 <= len(words) <= 3 * 10^4
- word1 != word2
- Both words exist in the list
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.