
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)
Editorial
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. |
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