The best and easiest solution to find the minimum distance between two words in this section.
String[] strArray = {"the","quick","brown","fox","quick"}; String str1 = "quick"; String str2 = "fox"; int i,startIndex=0,minDistnace=100; for( i=0;i<strArray.length;i++){ if(strArray[i].equals(str1)||strArray[i].equals(str2)){ startIndex = i; //get the first occurence of either word break; } } for(;i<strArray.length;i++){ if(strArray[i].equals(str1)||strArray[i].equals(str2)){ //compare every word from that first occurence // if words not same and distance less than minimun distance then update if(!strArray[i].equals(strArray[startIndex]) && (i-startIndex)<minDistance){ minDistance = i-startIndex; startIndex =i; } else{ startIndex =i; } } } System.out.println(minDistance);
Difficulty of time : O (n)
Space Maintenance : O (1)
source share