Linkedin Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
2
of 2 vote

public static int distance(String str,String a,String b){
		int aIndex=-1;
		int bIndex=-1;
		int minDistance=Integer.MAX_VALUE;
		String[] aS=str.toLowerCase().split("[ \t]+");
		int i=0;
		for(String t:aS){
			if(t.equals(a)){
				aIndex=i;
			}
			if(t.equals(b)){
				bIndex=i;
			}
			if(aIndex!=-1 && bIndex!=-1){
				minDistance= minDistance > Math.abs(bIndex-aIndex) ? bIndex-aIndex : minDistance; 
			}
			i++;
		}
		if(aIndex ==-1 || bIndex==-1)
			return -1;
		else
			return minDistance;
	}

- Anonymous April 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

very smart solution

- byrlhb September 21, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

minDistance= minDistance > Math.abs(bIndex-aIndex) ? bIndex-aIndex : minDistance

This is not right. you cannot count for the case of bIndex < aIndex

- goalchaser November 01, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

minDistance= minDistance > Math.abs(bIndex-aIndex) ? bIndex-aIndex : minDistance;

This is wrong. It is supposed to be

minDistance= minDistance > Math.abs(bIndex-aIndex) ? Math.abs(bIndex-aIndex) : minDistance;

- Prashanthy March 19, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

and, as told by -goalchaser, you should also consider a case where bIndex is less than aIndex. In such a case it should return -1.

- Prashanthy March 19, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about this:

#include <iostream>
#include <limits.h>

using namespace std;

#define INCR(x) if((x)!= INT_MAX)(x)++;
int main()
{
    int p1 = INT_MAX; 
    int p2 = INT_MAX;
    int d  = INT_MAX;
    string word;
    
    while (cin >> word) {
        if (word == "hello")
            p1 = 0;
        else if (word == "you")
            p2 = 0; 

        if (p1 != INT_MAX && p2 != INT_MAX) {
            d = min(d, p1 - p2);
        }

        INCR(p1);
        INCR(p2);
    }
    
    cout << "distance = " << d << endl; 
}

- Westlake January 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Simplifying my previous code.

/*
    * Assume words in inputBody are separated by space.
    * */
    public static int findDistanceBetweenWords(String inputBody, String pair1, String pair2) {
        if (inputBody.isEmpty() || pair1.isEmpty() || pair2.isEmpty()) {
            return -1;
        }
        if (pair1.equals(pair2)) {
            return 0;
        }
        StringTokenizer stringTokenizer = new StringTokenizer(inputBody, " ");
        int distance = 0, globalDistance = Integer.MAX_VALUE;
        String token;
        while (stringTokenizer.hasMoreTokens()) {
            token = stringTokenizer.nextToken();
            if (token.equals(pair1)) {
                distance = 0;
            } else if (token.equals(pair2)) {
                globalDistance = Math.min(distance, globalDistance);
            }
            distance++;
        }
        if (globalDistance == Integer.MAX_VALUE || globalDistance == 0) {
            return -1;
        } else {
            return globalDistance;
        }
    }

- techpanja January 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python

state_machine.py

class State(object):
   no_match = 0
   one_match = 1
   both_match = 2
   def __init__(self):
      self.current = State.no_match

class StateMachine(object):
   def __init__(self):
      self._states = []

   def register(self, state_function):
      self._states.append(state_function)

   def evaluate(self, state, value):
      words = value.split(' ')
      for word in words:
         for state_func in self._states:
            print "word: {0}".format(word)
            print "state: {0}".format(state.current)
            ret_value = state_func(state, word)
            if ret_value != None:
               return ret_value
      return -1

check.py

from state_machine import State, StateMachine

start_word = "hello"
end_word = "you"
distance = 0

def state_no_match(state, word):
   if state.current == State.no_match:
      if word == start_word:
         print "Found start word"
         state.current = State.one_match
      else:
         print "Didn't find start word or none"

def state_one_match(state, word):
   global distance
   if state.current == State.one_match:
      if word == end_word:
         print "Found end word"
         state.current = State.both_match
      else:
         distance += 1
      
def state_both_match(state, word):
   global distance 
   if state.current == State.both_match:
      print "Found final word!"
      return distance

def main():
   sm = StateMachine()
   sm.register(state_no_match)
   sm.register(state_one_match)
   sm.register(state_both_match)

   some_string = "hello and welcome to you"
   initial_state = State()
   print sm.evaluate(initial_state, some_string)

   some_string = "hello and none"
   initial_state = State()
   print sm.evaluate(initial_state, some_string)

   some_string = "you and hello"
   initial_state = State()
   print sm.evaluate(initial_state, some_string)
   

if __name__=="__main__":
   main()

Example Run

[mjlee@alderon StateMachine]$ python check.py 
word: hello
state: 0
Found start word
word: hello
state: 1
word: hello
state: 1
word: and
state: 1
word: and
state: 1
word: and
state: 1
word: welcome
state: 1
word: welcome
state: 1
word: welcome
state: 1
word: to
state: 1
word: to
state: 1
word: to
state: 1
word: you
state: 1
word: you
state: 1
Found end word
word: you
state: 2
Found final word!
4
word: hello
state: 0
Found start word
word: hello
state: 1
word: hello
state: 1
word: and
state: 1
word: and
state: 1
word: and
state: 1
word: none
state: 1
word: none
state: 1
word: none
state: 1
-1
word: you
state: 0
Didn't find start word or none
word: you
state: 0
word: you
state: 0
word: and
state: 0
Didn't find start word or none
word: and
state: 0
word: and
state: 0
word: hello
state: 0
Found start word
word: hello
state: 1
word: hello
state: 1
-1

- Anonymous January 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This code doesn't handle minimum value correctly. Do NOT use this code.

- Anonymous January 30, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

-(int)findDistanceBetweenStrings:(NSString *)sentence word1:(NSString *)word1 word2:(NSString *)word2
{
	if(sentence.length < 1 || word1.length < 1 || word2.length < 1)
		return -1;
	NSArray *sentenceArray = [sentence componentsSeparatedByString:@" "];
	int distance1 = -1;
	int distance2;
	
	for (NSString *str in sentenceArray) {
		if ([str isEqualToString:word1])
			distance1 = [sentenceArray indexOfObject:str];
		}
	
	if(distance1 > -1)
	{
		for (int j = distance1; j < sentenceArray.count; j++) {
			if ([[sentenceArray objectAtIndex:j] isEqualToString:word2])
			{
				distance2 = j;
				return distance2-distance1;
			}
		}
	}
	return -1;
}

- funny_ani January 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think the second case’s result is -2, then find the word-index of first appeared “you” and the word-index of last appeared “hello”, minus them, you will get the answer you want。

#include<iostream>
#include<string>
using namespace std;

int main(int argc, char **argv)
{
    string str, str1, str2;
    string :: iterator iter, iter1, iter2, itersave;
    int n1, n2, i;

    getline(cin, str);
    cin >> str1 >> str2;

    for (iter = str.begin(), i = 0, n1 = n2 = -1; iter < str.end(); iter++) {
        while(iter < str.end() && *iter == ' ')
            iter++;
        if (iter < str.end()) {
            i++;
            iter1 = str1.begin();
            iter2 = str2.begin();
            itersave = iter;
            while (iter < str.end() && iter1 < str1.end() && *iter == * iter1) {
                iter++;
                iter1++;
            }
            if (iter1 == str1.end()) {
                n1 = i;
            }
            if (n2 == -1) {
                iter = itersave;
                while (iter < str.end() && iter2 < str2.end() && *iter == *iter2) {
                    iter++;
                    iter2++;
                }
                if (iter2 == str2.end()) {
                    n2 = i;
                }
            }
            while (iter < str.end() && *iter != ' ') {
                iter++;
            }
        }
    }
    if (n1 == -1 || n2 == -1)
        cout << -1 << endl;
    else
        cout << n2 - n1 << endl;

    return 0;
}

- ctang January 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I have one doubt. What will be the output for the following string
you are big string hello

Whether the output should be -3 or -1(as order is not there)?

- Ricky January 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

output will be -1 as it says that if the order is not possible then return -1

- kr.neerav February 07, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public int findMinimumDistance(String str,String word1,String word2){
        if(str==null||word1==null||word2==null) return -1;
        if(word1.equals(word2)) return 0;
        String[] words = str.split(" ");
        int minDistance = -1,start=0,end;
        for(int i=0;i<words.length;i++){
            if(words[i].equals(word1)){
                start=i;
            }
            else if(words[i].equals(word2)){
                end = i;
                if(start<end&&minDistance!=-1)
                    minDistance=Math.min(minDistance,end-start);
                else if(start<end)
                    minDistance =end-start;
                else
                    minDistance=-1;
            }
        }
        return minDistance;

}

- my solution February 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// C++ in place solution
int FindDistance(const char* bigStr, const char* str1, const char* str2)
{
    int result = -1;
    size_t str1cnt = strlen(str1);
    size_t str2cnt = strlen(str2);
    
    while (*bigStr) {
        char* firstPtr = strstr(bigStr, str1);
        if (firstPtr)
        {
            char* firstEndPtr = firstPtr + str1cnt;
            if (isspace(*firstEndPtr))
            {
                char* secondPtr = strstr(firstPtr, str2);
                if (secondPtr)
                {
                    char* secondEndPtr = secondPtr + str2cnt;
                    if (!*secondEndPtr || isspace(*secondEndPtr))
                    {
                        // count word breaks between first and second word
                        int distance = 1;
                        char* ptr = firstEndPtr;
                        while (ptr < secondPtr)
                        {
                            // walk thru spaces
                            while ((ptr < secondPtr) && isspace(*ptr))
                                 ptr++;
                            if (ptr < secondPtr)
                                distance++;
                            // walk thru word
                            while ((ptr < secondPtr) && !isspace(*ptr))
                                ptr++;
                        }
                        if ((result == -1) || (result > distance))
                           result = distance;
                        
                        // advance beyond first word and search again
                        bigStr = firstEndPtr;
                    }
                    else
                         break;
                }
                else
                    break;
            }
            else
                break;
        }
        else
            break;
    }
    
    return result;
}

- lowob February 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Writing the algorithm instead of the program

Let 'hello' = 1, 'you' = 2, all other words = 0
1) convert the string into an array of numbers as given e.g. "hello how are you" = 1-0-0-2
2) initialize min_distance = 999999 (very large value)
2) scan this array from left and store distance in count variable (initialized to -1)
whenever array element = 1, reset count value to 1
whenever array element = 0, copy value of count in min_distance if count<min_distance and reset count = -1
increment count if count >0

- kr.neerav February 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public StringFunctions{
public int dist(String str, String str1, String str2){
int startIndex = -1, endIndex = -1;
String[] tokens = str.split("\\s");
for (int i = 0; i < tokens.length; i++){
if (tokens[i].equals(str1))
startIndex = i;
if (tokens[i].equals(str2))
endIndex = i;
}
if (startIndex >= 0 && endIndex >= 0 && startIndex < endIndex)
return endIndex-startIndex;
else
return -1;
}

public static void main (String[] args){
StringFunctions strFuncs = new StringFunctions();
String str = "hello how are you"; String str1 = "hello"; String str2 = "you";
System.out.println(str);
System.out.println(strFuncs.dist(str, str1, str2));
str = "hello how are hello you";
System.out.println(str);
System.out.println(strFuncs.dist(str, str1, str2));
str = "you are hello";
System.out.println(str);
System.out.println(strFuncs.dist(str, str1, str2));
str = "hello how are hello";
System.out.println(str);
System.out.println(strFuncs.dist(str, str1, str2));
}
}

- Anonymous February 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
Find minimum distance between two words (order preserved) in a big string. 
For e.g 1. "hello how are you" - distance between "hello" and "you" is 3. 
e.g 2. "hello how are hello you" - distance is 1 
e.g 3. "you are hello" - distance is -1. Order of "hello" and "you" should be preserved. 
e.g 4. "hello how are hello" - distance is -1 since "you" didnt occur even once.
*/
//S is the big string. order A....B
public int findMinDistanceBtwWords(String S, String A, String B){
    int posCount = 0;
    int start = 0;
    int posA=0;
    int posB=0;
    int minDistance=-1;
    //counting position based on the spaces we encounter. append a space to the last wordrd
    S = S.concat(" ");
    for(int i=0;i<S.length();i++){
        if(S.charAt(i)==' '){
            posCount++;
            
            //see if substring at (start, i-1) matches any of A or B
            if(S.substring(start,i).equals(A)){
                posA = posCount;
            }
    
            if(S.substring(start,i).equals(B)){
                posB = posCount;
            }
            
            if((posB!=0 && posA!=0) && posB-posA>0){
                if(minDistance == -1){
                    minDistance = posB-posA;
                }else{
                    minDistance = Math.min(posB-posA,minDistance);
                }
                
            }
                    
            //update start
            start = i+1;
        }
    }
    
    return minDistance;
}

- sh88990 May 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Convert location of each word into an list. Then call the below method with two list.

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class Test26 {
	/*
	Find minimum distance between two words (order preserved) in a big string.
	For e.g 1. "hello how are you" - distance between "hello" and "you" is 3.
	e.g 2. "hello how are hello you" - distance is 1
	e.g 3. "you are hello" - distance is -1. Order of "hello" and "you" should be preserved.
	e.g 4. "hello how are hello" - distance is -1 since "you" didnt occur even once.
	*/
	//the first element of a is less than the first element of b
	public static int minumumDistance(List<Integer> a, List<Integer> b){
		if (a.size()==0 || b.size()==0){
			return -1;
		}else if (a.get(0) > b.get(b.size()-1)){
			return -1;
		}else {
			return test26(a, b);
		}
		 
	}
	public static int test26(List<Integer> a, List<Integer> b){
		int diff = Integer.MAX_VALUE ;
		
		while (true){
			while (a.size()>0 && a.get(0) < b.get(0)){
				diff = Math.min(diff, b.get(0) - a.remove(0));
			}
				
			if (a.size()>0){
				List<Integer> tmp;
				tmp = a;
				a = b;
				b = tmp;
			}else{
				break;
			}
				
		}
		
		return diff;
	}
	public static void main(String[] args) {
		System.out.println(minumumDistance(new ArrayList<Integer>(Arrays.asList(new Integer[]{0})), 
				new ArrayList<Integer>(Arrays.asList(new Integer[]{3}))));
		System.out.println(minumumDistance(new ArrayList<Integer>(Arrays.asList(new Integer[]{0,3})), 
				new ArrayList<Integer>(Arrays.asList(new Integer[]{4}))));
		System.out.println(minumumDistance(new ArrayList<Integer>(Arrays.asList(new Integer[]{0,3, 6, 10})), 
				new ArrayList<Integer>(Arrays.asList(new Integer[]{8,11,15}))));
		System.out.println(minumumDistance(new ArrayList<Integer>(Arrays.asList(new Integer[]{2})), 
				new ArrayList<Integer>(Arrays.asList(new Integer[]{0}))));
		System.out.println(minumumDistance(new ArrayList<Integer>(Arrays.asList(new Integer[]{2})), 
				new ArrayList<Integer>(Arrays.asList(new Integer[]{}))));

	}

}

- longread September 27, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void findMin(String[] str, String s1, String s2){
		
		if(str.length == 0)
			return;
		if(s1 == null || s2 == null)
			return;
		
		int s1Index = -1;
		int s2Index = -1;
		int diff = Integer.MAX_VALUE;
		for(int i=0;i<str.length;i++){
			
			if(str[i].equals(s1)){
				s1Index = i;
			}
			
			if(str[i].equals(s2)){
				s2Index = i;
			}
			
			if(s1Index >= 0 && s2Index >= 0 && Math.abs(s1Index - s2Index) < diff)
				diff = Math.abs(s1Index - s2Index);
			
				
		}
		
		if(diff == Integer.MAX_VALUE)
			System.out.println("Minimum distance -1 ...word not found" );
		else
			System.out.println("Minimum distance " + diff);
	}

- Anonymous September 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int findDistance(String str,String strIni,String strLast){
HashMap<String, Integer> hash = new HashMap<>();
String[] strA = str.split(" ");
int distance = -1;
for(int i=0;i<strA.length;i++){
hash.put(strA[i], i);
}
if(hash.containsKey(strIni) && hash.containsKey(strLast)){
distance = hash.get(strLast)-hash.get(strIni);
if(distance<=0){
distance = -1;
}
}
return distance;
}

- Ani December 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<string>
#include<map>
#include<vector>
using namespace std;
int fun(char str1[],char str2[])
{
int l1=3;
int flag;
int l2=3;
for(int i=0;i<l1;i++)
{
if(str1[i]==str2[i])
flag=1;
else{
flag=0;
break;
}}
if(flag==1)
return 1;
else
return 0;
}
int main()
{
int a[10]={0};
int b[10]={0};
char str[10][100]={"cat","dog","cat","ghj","god","god","cat","kl","kkil","god"};
map<string,vector<int> > m;
for(int i=0;i<10;i++){
if(fun(str[i],"cat")||fun(str[i],"god")){
m[str[i]].push_back(i);
}
}
int k=0,l=0,flag=1;
map<string,vector<int> > :: iterator it;
for(it=m.begin();it!=m.end();it++)
{
for(int j=0;j<it->second.size();j++)
{
if(flag==1){
a[k++]=it->second[j];
}
else{
b[l++]=it->second[j];
}
}
flag=0;
}

int i=0,j=0;
int min=99999;
int m1=k,n=l;
while(i<m1 && j<n)
{
if(a[i]<b[j])
{
while(a[i]<b[j] && i!=m1)
{
int diff=b[j]-a[i];
if(diff < min)
min=diff;
i++;
}
}
else
{
while(b[j]<a[i] && j!=n)
{
int diff=a[i]-b[j];
if(diff<min)
min=diff;
j++;

}
}
// printf("%d",min);
}
cout<<min;

}

- Anonymous January 19, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Naive approach is used to find a substring (which is OK if both words are short). If I had more time, I would something more advanced (e.g. Rabin–Karp algorithm).

using System;

namespace InterviewTasks
{
    internal static class MinLengthBetweenWords
    {
        public static int FindMinLength(string input, string x, string y)
        {
            if (string.IsNullOrEmpty(input))
            {
                throw new ArgumentException("input");
            }

            if (string.IsNullOrEmpty(x))
            {
                throw new ArgumentException("x");
            }

            if (string.IsNullOrEmpty(y))
            {
                throw new ArgumentException("y");
            }

            int whitespacesCount = 0;
            int lastXOccurence = -1;
            for (int i = 0; i < input.Length - x.Length + 1; ++i)
            {
                bool isSubstring = true;
                for (int j = 0; j < x.Length; ++j)
                {
                    if (input[i + j] != x[j])
                    {
                        isSubstring = false;
                        break;
                    }
                }

                if (isSubstring)
                {
                    lastXOccurence = i;
                }
            }

            if (lastXOccurence == -1)
            {
                return -1;
            }

            for (int i = lastXOccurence + x.Length; i < input.Length - y.Length + 1; ++i)
            {
                if (input[i] == ' ')
                {
                    whitespacesCount++;
                    continue;
                }

                bool isSubstring = true;
                for (int j = 0; j < y.Length; ++j)
                {
                    if (input[i + j] != y[j])
                    {
                        isSubstring = false;
                        break;
                    }
                }

                if (isSubstring)
                {
                    return whitespacesCount;
                }
            }

            return -1;
        }
    }
}

- stanislav.khalash January 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <string>
#include <limits.h>
#include <algorithm>

using namespace std;


int getMinDiff(string s, string w1, string w2) {
    int count = 0;
    int n = s.size();
    int p1 = -1;
    int p2 = -1;
    int minDiff = INT_MAX;
    for (int i = 0; i < n; ++i) {
        while(i < n && s[i] == ' ') i++;
        int j = i;
        while(j < n && s[j] != ' ') j++;
        if (j > i) {
            string word = string(s,i,j-i);
            count++;
            //cout << "word : " << word  << "\t" << count << "\n";
            if (word == w1) {
                //cout << "found " << w1 << " at " << count << "\n";
                p1 = count;
            } 
            if (word == w2) {
                //cout << "found " << w2 << " at " << count << "\n";
                p2 = count;
            }
        }
        i = j;

        if (p1 != -1 && p2 != -1) {
            minDiff = min(minDiff, p2-p1);
        }
    }

    return minDiff != INT_MAX ? minDiff : -1;
}

int main() {
    cout << "Min diff : " << getMinDiff("hello how are you", "how", "you") << "\n";
    cout << "Min diff : " << getMinDiff("hello how are you", "you", "you") << "\n";
    cout << "Min diff : " << getMinDiff("hello how are you", "you", "are") << "\n";
    cout << "Min diff : " << getMinDiff("hello how are you", "youkhask", "jare") << "\n";
    cout << "Min diff : " << getMinDiff("h", "youkhask", "jare") << "\n";
    cout << "Min diff : " << getMinDiff("     hello     ", "hello", "hello") << "\n";
    cout << "Min diff : " << getMinDiff("     hello     are   ", "hello", "are") << "\n";
}

- anonymous March 04, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int findSmallestDistanceBetweenWords(String[] tokens,String string1, String string2) {
		int string1Index = -1;
		int string2Index = -1;
		int distance =-1;
	
	for(int i=0;i<tokens.length;i++){
		if(string1Index != -1 && string2Index!=-1){
			if(distance == -1){
				distance = (string1Index>string2Index)?(string1Index-string2Index):(string2Index-string1Index);
			}else{
				int tempDist = (string1Index>string2Index)?(string1Index-string2Index):(string2Index-string1Index);
				if(tempDist<distance)
					distance = tempDist;
			}
		}
		
		if(tokens[i].equals(string1)){
			string1Index = i;
		}
		if(tokens[i].equals(string2)){
			string2Index = i;
		}
		
		
	}
	    
		
		return distance;
	}

- Anonymous July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static int findSmallestDistanceBetweenWords(String[] tokens,String string1, String string2) {
		int string1Index = -1;
		int string2Index = -1;
		int distance =-1;
	
	for(int i=0;i<tokens.length;i++){
		if(string1Index != -1 && string2Index!=-1){
			if(distance == -1){
				distance = (string1Index>string2Index)?(string1Index-string2Index):(string2Index-string1Index);
			}else{
				int tempDist = (string1Index>string2Index)?(string1Index-string2Index):(string2Index-string1Index);
				if(tempDist<distance)
					distance = tempDist;
			}
		}
		
		if(tokens[i].equals(string1)){
			string1Index = i;
		}
		if(tokens[i].equals(string2)){
			string2Index = i;
		}
		
		
	}
	    
		
		return distance;
	}

- Geky July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class MinimumDistance {

public static int minimumDistance(String bigStr, String word1, String word2 ){

String[] str= bigStr.split(" ");
int min= Integer.MAX_VALUE;
int pos1= Integer.MAX_VALUE;
int pos2 = Integer.MAX_VALUE;

for(int i=0; i< str.length; i++){

if(str[i].equals(word1)) {
int m1=getMin(i,pos2);
if ( m1< min){
min= getMin(i,pos2);
pos1=i;
}
}
if(str[i].equals(word2)){
int m2=getMin(pos1,i);
if (m2 < min){
min= getMin(pos1,i);
pos2=i;
}
}
}
return min;
}

public static int getMin(int x, int y){
int d= Math.abs(x-y);
//System.out.println(d);
return d;
}

public static void main(String args[] ){
int m=minimumDistance("The picture quality is great of this camera", "picture", "camera");
System.out.println("Minimum distance between 2 words in String :" + (m-1));
int n=minimumDistance("The color of the car is blue", "color", "blue");
System.out.println("Minimum distance between 2 words in String :" + (n-1));

- Anonymous January 05, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class MinimumDistance {
	
	public static int minimumDistance(String bigStr, String word1, String word2 ){
		
		String[] str= bigStr.split(" ");
		int min= Integer.MAX_VALUE;
		int pos1= Integer.MAX_VALUE;
		int pos2 = Integer.MAX_VALUE;
		
		for(int i=0; i< str.length; i++){
			
			if(str[i].equals(word1)) {
				int m1=getMin(i,pos2);
				if ( m1< min){
					min= getMin(i,pos2);
					pos1=i;
				}
			}
			if(str[i].equals(word2)){
				int m2=getMin(pos1,i);
				if (m2 < min){
					min= getMin(pos1,i);
					pos2=i;
				}
			}
		}
		return min;
	}
	
	public static int getMin(int x, int y){
		int d= Math.abs(x-y);
		//System.out.println(d);
		return d;
	}

	public static void main(String args[] ){
		int m=minimumDistance("The picture quality is great of this camera", "picture", "camera");
		System.out.println("Minimum distance between 2 words in String :" + (m-1));
		int n=minimumDistance("The color of the car is blue", "color", "blue");
		System.out.println("Minimum distance between 2 words in String :" + (n-1));

- Priyamvada January 05, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class MinimumDistance {
	
	public static int minimumDistance(String bigStr, String word1, String word2 ){
		
		String[] str= bigStr.split(" ");
		int min= Integer.MAX_VALUE;
		int pos1= Integer.MAX_VALUE;
		int pos2 = Integer.MAX_VALUE;
		
		for(int i=0; i< str.length; i++){
			
			if(str[i].equals(word1)) {
				int m1=getMin(i,pos2);
				if ( m1< min){
					min= getMin(i,pos2);
					pos1=i;
				}
			}
			if(str[i].equals(word2)){
				int m2=getMin(pos1,i);
				if (m2 < min){
					min= getMin(pos1,i);
					pos2=i;
				}
			}
		}
		return min;
	}
	
	public static int getMin(int x, int y){
		int d= Math.abs(x-y);
		//System.out.println(d);
		return d;
	}

	public static void main(String args[] ){
		int m=minimumDistance("The picture quality is great of this camera", "picture", "camera");
		System.out.println("Minimum distance between 2 words in String :" + (m-1));
		int n=minimumDistance("The color of the car is blue", "color", "blue");
		System.out.println("Minimum distance between 2 words in String :" + (n-1));

- Priyamvada January 05, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int dwords(string s, string a, string b) {
    queue<entry> pq;
    stringstream ss(s);
    int count = 0;
    while(!ss.eof()) {
        string stemp;
        ss>> stemp;

        if (!stemp.compare(a) || !stemp.compare(b)) {
            cout << "adding " << stemp  << ", at index " << count <<"\n";
            pq.push(entry(stemp, count));

        }
        count++;
    }
    cout << "count is " << count <<"\n";
    
    entry last_seen = pq.front();
    pq.pop();
    unsigned int distance = 0xFFFF;
    bool first_one = true;
    
    while(!pq.empty()) {
        entry current = pq.front();
        pq.pop();
        
        if (!current.w.compare(last_seen.w)) {
            // both equal
            continue;
        }
        if ((current.index - last_seen.index) < distance) {
            distance = current.index - last_seen.index;
            cout << "Found minumum distance " << distance << "\n";
            if (!last_seen.w.compare(b)) {
                first_one = false;
            }
        }
        last_seen = current;
    }
    
    if(distance == 0xFFFF) {
        return -2;
    }
    if (!first_one) {
        return -((int)distance);
    } return (int)distance;
}

- undefined July 15, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 3 vote

github.com/techpanja/interviewproblems/blob/master/src/strings/distancebetweenwords/DistanceBetweenWords.java

/*    Kadane's Algo  
    * Assume words in inputBody are separated by space.
    * */
    public static int findDistanceBetweenWords(String inputBody, String pair1, String pair2) {
        if (inputBody.isEmpty() || pair1.isEmpty() || pair2.isEmpty()) {
            return -1;
        }
        if (pair1.equals(pair2)) {
            return 0;
        }
        StringTokenizer stringTokenizer = new StringTokenizer(inputBody, " ");
        int distance = 0, globalDistance = inputBody.length();
        boolean foundPair1 = false;
        String token = "";
        while (stringTokenizer.hasMoreTokens()) {
            token = stringTokenizer.nextToken();
            if (token.equals(pair1)) {
                distance = 0;
                foundPair1 = true;
            }
            if (foundPair1) {
                distance++;
            }
            if (token.equals(pair2) && foundPair1) {
                globalDistance = Math.min(distance, globalDistance);
            }
        }
        if (globalDistance == inputBody.length()) {
            return -1;
        } else {
            return globalDistance - 1;
        }
    }

- techpanja January 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

function minDistance(str, str1, str2){
     if(str === "" || str1 === "" || str2 === "")
             return -1;
     var strArr = str.split(" ");
     var str1In = -1;
     for(var i=0,len=strArr.length;i<len;i++){
         if(str1 === strArr[i]){
              str1In = i;
         }else if(str1In !== -1 && str2 === strArr[i]){
             return i - str1In;

         }

     }return -1;
}minDistance("hello how are you","hello","you");

- KK February 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More