PIXELBANKv8.2.1
Menu

Shortest Word Distance

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: practice and coding
  • The indices of these words in the list are found: practice is at index 0 and coding is at index 3
  • The shortest distance between them is calculated as the absolute difference in their indices: 03=3|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

Test Results

0/0
Run code to see test results.