Could you provide the c++ code too? of O(N) time complexity for the question word distance 1?
Kindly provide C++ code for word distance 1 problem!
Hey @daspradhi1812
What you can do is use two variables to keep track of the position of each word and calculate the distance with a single pass through the list => O(N) .
index1 = -1,index2 = -1;
minDistance = Integer.MAX_VALUE
tempDistance = 0
for (string x in array of strings)
if strings[x].equals(targetString)
index1 = x;
if strings[x].equals(targetString2)
index2 = x;
if index1 != -1 and index2 != -1 // both words have to be found
tempDistance = absolute(index2 - index1)
if tempDistance < minDistance
then minDistance = tempDistance
Now try it yourself in C++.
1 Like
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.