Tutorialspoint
Problem
Solution
Submissions

Find Shortest Distance Between Words in a Text

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 10

Write a Python function shortest_distance(text, word1, word2) that returns the minimum number of words between two given words in a string.

Example 1
  • Input: text = "the quick brown fox jumps over the lazy dog", word1 = "fox", word2 = "dog"
  • Output: 4
  • Explanation:
    • Step 1: "fox" is at index 3, "dog" is at index 8.
    • Step 2: Words between them are ["jumps", "over", "the", "lazy"].
    • Step 3: Count = 4.
Example 2
  • Input: text = "the quick brown fox fox jumps over the lazy dog", word1 = "fox", word2 = "dog"
  • Output: 3
  • Explanation:
    • Step 1: Last "fox" at index 4, "dog" at index 9.
    • Step 2: Words between them are ["jumps", "over", "the"].
    • Step 3: Count = 3.
Constraints
  • 1 ≤ text.length ≤ 105
  • 1 ≤ word1.length, word2.length ≤ 20
  • Time Complexity: O(n), where n is the number of words
  • Space Complexity: O(1)
StringsFunctions / MethodsFacebookWipro
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Split the text into words and iterate through them
  • Keep track of the most recent positions where word1 and word2 were found
  • When you find either word, calculate the distance to the most recent occurrence of the other word
  • Update the minimum distance whenever a shorter distance is found
  • Be careful when word1 and word2 are the same word or when either word is not in the text

Steps to solve by this approach:

 Step 1: Split the input text into an array of words.
 Step 2: Initialize variables to track the positions of word1 and word2 and the minimum distance.
 Step 3: Iterate through each word in the text, updating the position variables when either target word is found.
 Step 4: When both words have been found at least once, calculate the current distance between them and update the minimum distance if needed.
 Step 5: Return the minimum distance found, or -1 if either word wasn't found in the text.

Submitted Code :