v9.1.1
Menu

Shortest Word Distance

easyPROStrings & ArraysLinkedIn DSA

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: ∣0−3∣=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

More from LinkedIn DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.