Shortest Word Distance

EasyArrays & Hashingtwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an array of strings wordsDict and two different strings word1 and word2, both of which appear somewhere in the array (each may appear more than once). Return the smallest distance |i - j| over all index pairs where wordsDict[i] == word1 and wordsDict[j] == word2. Aim for a single pass over the array with O(1) extra space.

Examples

Input: wordsDict = ["practice","makes","perfect","coding","makes"], word1 = "coding", word2 = "practice"
Output: 3
"practice" is at index 0 and "coding" at index 3.
Input: wordsDict = ["practice","makes","perfect","coding","makes"], word1 = "makes", word2 = "coding"
Output: 1
"coding" at index 3 is next to "makes" at index 4.

Constraints

  • 2 <= wordsDict.length <= 3 * 10^4
  • 1 <= wordsDict[i].length <= 10
  • `wordsDict[i]` consists of lowercase English letters
  • `word1` and `word2` are both in `wordsDict`
  • `word1 != word2`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems