- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Shortest Word Distance III in C++
Suppose we have a list of words and another two words called word1 and word2, we have to find the shortest distance between these two words in the list. Here word1 and word2 may be the same and they represent two individual words in the list. Let us assume that words = ["practice", "makes", "perfect", "skill", "makes"].
So, if the input is like word1 = “makes”, word2 = “skill”, then the output will be 1
To solve this, we will follow these steps −
ret := 10^9, l1 := 10^9, l2 := -10^9
n := size of words
for initialize i := 0, when i < n, update (increase i by 1), do −
if words[i] is same as word1, then −
l1 := i
if words[i] is same as word2, then −
if word1 is same as word2, then −
l1 := l2
l2 := i
ret := minimum of |l2 - l1| and ret
return ret
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int shortestWordDistance(vector<string<& words, string word1, string word2) { int ret = 1e9; int l1 = 1e9; int l2 = -1e9; int n = words.size(); for (int i = 0; i < n; i++) { if (words[i] == word1) { l1 = i; } if (words[i] == word2) { if (word1 == word2) { l1 = l2; } l2 = i; } ret = min(abs(l2 - l1), ret); } return ret; } }; main(){ Solution ob; vector<string< v = {"practice", "makes", "perfect", "skill", "makes"}; cout << (ob.shortestWordDistance(v, "makes", "skill")); }
Input
{"practice", "makes", "perfect", "skill", "makes"},"makes", "skill"
Output
1
- Related Articles
- Shortest Word Distance II in C++
- Shortest Completing Word in Python
- Shortest Distance to Target Color in C++
- Shortest Distance from All Buildings in C++
- Word Ladder (Length of shortest chain to reach a target word) in C++
- Finding shortest word in a string in JavaScript
- Shortest distance between objects in JavaScript
- Corresponding shortest distance in string in JavaScript
- C++ code to get shortest distance from circular stations
- Find shortest unique prefix for every word in a given list in C++
- Program to Find the Shortest Distance Between Two Points in C++
- C++ Program to find the Shortest Distance to a character
- C++ program to find the shortest distance between two nodes in BST
- Minimum Distance to Type a Word Using Two Fingers in C++
- Find the shortest distance between any pair of two different good nodes in C++
