Microsoft Interview Question
SDE-2sCountry: United States
Interview Type: In-Person
Step 1 :- First we create the trie and add the index value of word at the end of the word.
Step 2 :- search in the trie for the given words and if we found those words we also get the location of all the word where these word are present in the file.
Step 3:- we will put then in a single list of both the occurrence location of words and apply the below algorithm.
void function() {
List<Point> xPoints = new ArrayList<Point>();
List<Point> yPoints = new ArrayList<Point>();
xPoints.add(new Point("firstWord", 32));
xPoints.add(new Point("firstWord", 54));
yPoints.add(new Point("secondWord", 38));
yPoints.add(new Point("secondWord", 67));
Comparator<Point> myComparator = new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
return o1.value - o2.value;
}
};
List<Point> listOfPoints = new ArrayList<Point>();
listOfPoints.addAll(xPoints);
listOfPoints.addAll(yPoints);
Collections.sort(listOfPoints, myComparator);
Point xPoint = null;
Point yPoint = null;
int minValue = Integer.MAX_VALUE;
for (Point point : listOfPoints) {
if (point.type == "firstWord") {
if (null != yPoint) {
if (minValue > (point.value - yPoint.value)) {
minValue = point.value - yPoint.value;
}
}
xPoint = point;
} else if (point.type == "secondWord") {
if (null != xPoint) {
if (minValue > (point.value - xPoint.value)) {
minValue = point.value - xPoint.value;
}
}
yPoint = point;
}
}
System.out.println("Data Value "+minValue);
}
Always keep track of the latest position of the given words and compare the distance between the last positions found for word1 and word2.
int min_dist_in_words(string s, string word1, string word2){
int count_word=0; int p_word1=-1; int p_word2=-1; int min_dist=INT_MAX;
int i=0;
while(!isalpha(s[i])){ //if there is any blank space at the beginning
i++;
}
int j=i;
while(i<s.length()){
if(!isalpha(s[i])){
count_word++;
string s2=s.substr(j,i-j); //cout<<s2<<endl;
if(s2==word1){
p_word1=count_word;
if(p_word2!=-1 && min_dist>(p_word1-p_word2-1)){
min_dist=p_word1-p_word2-1;
if(min_dist==0)return min_dist;
}
}else if(s2==word2){
p_word2=count_word;
if(p_word1!=-1 && min_dist>(p_word2-p_word1-1)){
min_dist=p_word2-p_word1-1;
if(min_dist==0)return min_dist;
}
}
i++;
while(i<s.length() && !isalpha(s[i])){ // if there is ', " or additional blank space
i++;
}
j=i; i--;
}
i++;
}
return min_dist;
}
Scan text and for each word store in a list the positions it was found. Sort this list for each word. Assume we need to find the distance between w and v in the original text. The problem then boils down to finding the pair (a,b) where a is from the position list for w and b is from the position list of v. The pair where the difference abs (a-b) is minimum can be easily found. (O(n log n )
- Makarand September 05, 2017