Facebook Interview Question for SDE1s


Country: United States




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

Wel... Actually you build a usual trie, but should take attention on next aspects:
1) Some words can be subwords of another, like: caw and cawboy, so you should have marker that will indicate complete words in a trie
2) '*' means that you should try to continue recursive backtracking search with any character on current level as well as with next character in pattern
3) Take into account that there can be '**' and more asterisk in line (I just replace such with single one)
4) Take into account that '*' could be last character in a pattern (and the only one character in a pattern).
Space complexity O(S*L), where S - number of words in trie, L - average length of word. Time complexity equals to number of nodes in a trie (in worst case of '*' pattern) should be O(S*L) (as we will visit each node one or two times in worst case).
It is tricky to take this all into account, but here is the code:

private static class Node {
    boolean isWord;
    Map<Byte,Node> children = new HashMap<Byte,Node>();    
  }
  
  private static class Trie {
    Node root=new Node();
    
    void add(String str) {
      Node node = root;
      for(int i=0;i<str.length();i++) {
        char ch=str.charAt(i);
        node=node.children.computeIfAbsent((byte)ch,s->new Node());
      }
      node.isWord=true;
    }
    
    static String preparePattern(String pattern) {
      return pattern.replaceAll("\\*+","*");
    }
    
    String stringFromPath(List<String> path) {
      return String.join("",path);
    }
    
    void searchRecursive(Node node, String pattern, int pos,
                         LinkedList<String> path, Set<String> found) {
      if(pos==pattern.length()) {
        if(node.isWord) 
          found.add(stringFromPath(path));
        return;
      }
      
      char ch = pattern.charAt(pos);
      if(ch=='*') {
        if(pos==pattern.length()-1 && node.isWord) {
          found.add(stringFromPath(path));
          if(node.children.size()==0)
            return;
        }
        
        for(Map.Entry<Byte,Node> entry : node.children.entrySet()) {
          Node nextNode = entry.getValue();
          path.addLast(String.valueOf((char)(entry.getKey().byteValue())));             
          searchRecursive(nextNode, pattern, pos, path, found);
          searchRecursive(nextNode, pattern, pos+1, path, found);
          path.removeLast();
        }
      } else {
        Node nextNode = node.children.get((byte)ch);
        if(nextNode!=null) {
          path.addLast(String.valueOf(ch));
          searchRecursive(nextNode, pattern, pos+1, path, found);
          path.removeLast();
        }
      }
    }
    
    Set<String> search(String pattern) {
      pattern = preparePattern(pattern);
      Set<String> found = new HashSet<String>();
      searchRecursive(root, pattern, 0, new LinkedList<String>(), found);
      return found;
    }
  }
  
  private static void doTest(Trie trie, String pattern) {
    System.out.println("Pattern: "+pattern+" : "+trie.search(pattern));
  }
  
  public static void main(String[] args) {
    Trie trie = new Trie();
    trie.add("car");
    trie.add("caw");
    trie.add("cauw");
    trie.add("caqweruw");
    trie.add("trie");
    trie.add("computer");
    trie.add("cawboy");
    doTest(trie,"c*w");
    doTest(trie,"ca*");
    doTest(trie,"c**w*");
    doTest(trie,"*r*");
    doTest(trie,"*");
  }

- Matviy Ilyashenko November 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String args[]) {

            Trie root = new Trie();
            root.addWord("ca");
            root.addWord("cat");
            root.addWord("caw");
            root.addWord("cauw");
            root.addWord("cw");
            root.addWord("cramtowa");
            root.addWord("mccatorw");

            Set<String> result = new HashSet<>();
            FindWords(root, "c*a*", "", result);

            System.out.println(result);
    }

    private static void FindWords(Trie root, String word, String prefix, Set<String> result){

        if(word == null || word.length()==0 || root == null)
            return;

        StringBuilder sb = new StringBuilder();

        Trie current = root;
        for(int i=0;i<word.length(); i++){
            char c = word.charAt(i);
            if(c == '*'){
                String w = word.substring(i);
                char child = 'a';
                for(Trie t: current.childs()){
                    FindWords(t, w, prefix+sb.toString()+child, result);
                    child++;
                }
            }else{
                int index = c - 'a';
                if(current.childs()[index] != null){
                    current = current.childs()[index];
                    sb.append(c);
                }else{
                    return;
                }
            }
        }
        if(current.isKey()){
            System.out.println("Found String: "+prefix+sb);
            result.add(prefix+sb);
        }
    }

- incarose November 12, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {

		Trie root = new Trie(false);
		add(root, "car".toCharArray());
		add(root, "caw".toCharArray());
		add(root, "cauw".toCharArray());

		match(root, "c*w".toCharArray(), 0, "", false);

	}

	// caw, c*w
	public static void match(Trie trie, char[] carr, int index, String str, boolean leaf) {

		if (index == carr.length) {
			if (leaf)
				System.out.println(str);
			return;
		}

		char c = carr[index];
		if (c == '*') {
			Trie[] next = trie.next;
			for (int i = 0; i < 26; i++) {
				if (next[i] != null) {
					match(next[i], carr, index + 1, str + (char)(i + 'a'), trie.leaf);
					match(next[i], carr, index, str + (char)(i + 'a'), trie.leaf);
				}
			}
		} else if (trie.next[c - 'a'] == null) {
			return;
		} else {
			match(trie.next[c - 'a'], carr, index + 1, str + carr[index], trie.leaf);
		}

	}

	// car
	public static void add(Trie trie, char[] carr) {
		int n = carr.length;
		for (int i = 0; i < n; i++) {
			if (trie.next[carr[i] - 'a'] == null) {
				Trie node = new Trie(false);
				trie.next[carr[i] - 'a'] = node;
				if (i == n - 2)
					node.leaf = true;
			}
			trie = trie.next[carr[i] - 'a'];
		}
	}

	static class Trie {

		Trie[] next = new Trie[26];
		boolean leaf;

		public Trie(boolean leaf) {
			this.leaf = leaf;
		}
	}

- sudip.innovates November 13, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

How about following code:
import java.util.List;
import java.util.*;
public class StringSearcher {
public List<String> search(String pattern, List<String> stringList){
final StringBuilder regexBuilder = new StringBuilder("^");
final String intrimRegex = pattern.replace("*",".*");
regexBuilder.append(intrimRegex).append("$");
final String regex = regexBuilder.toString();
final List<String> matchedStrings = new ArrayList<>();
for(String stringToMatch:stringList){
if(stringToMatch.matches(regex)){
matchedStrings.add(stringToMatch);
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
stringList.add("car");
stringList.add("caw");
stringList.add("acauw");
List<String> matchedList = new StringSearcher().search("c*w",stringList);
if(matchedList.size() == 0){
System.out.println("No match found");
return;
}
System.out.println("Following are the string matching the pattern:");
for(String matchedString: matchedList){
System.out.println(matchedString);
}
}
}

- Sameer November 24, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.List;
import java.util.*;
public class StringSearcher {
public List<String> search(String pattern, List<String> stringList){
final StringBuilder regexBuilder = new StringBuilder("^");
final String intrimRegex = pattern.replace("*",".*");
regexBuilder.append(intrimRegex).append("$");
final String regex = regexBuilder.toString();
final List<String> matchedStrings = new ArrayList<>();
for(String stringToMatch:stringList){
if(stringToMatch.matches(regex)){
matchedStrings.add(stringToMatch);
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
stringList.add("car");
stringList.add("caw");
stringList.add("acauw");
List<String> matchedList = new StringSearcher().search("c*w",stringList);
if(matchedList.size() == 0){
System.out.println("No match found");
return;
}
System.out.println("Following are the string matching the pattern:");
for(String matchedString: matchedList){
System.out.println(matchedString);
}
}
}

- Sameer November 24, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.List;
import java.util.*;
public class StringSearcher {
public List<String> search(String pattern, List<String> stringList){
final StringBuilder regexBuilder = new StringBuilder("^");
final String intrimRegex = pattern.replace("*",".*");
regexBuilder.append(intrimRegex).append("$");
final String regex = regexBuilder.toString();
final List<String> matchedStrings = new ArrayList<>();
for(String stringToMatch:stringList){
if(stringToMatch.matches(regex)){
matchedStrings.add(stringToMatch);
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
stringList.add("car");
stringList.add("caw");
stringList.add("acauw");
List<String> matchedList = new StringSearcher().search("c*w",stringList);
if(matchedList.size() == 0){
System.out.println("No match found");
return;
}
System.out.println("Following are the string matching the pattern:");
for(String matchedString: matchedList){
System.out.println(matchedString);
}
}
}

- Sameer November 24, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.List;
import java.util.*;
public class StringSearcher {
public List<String> search(String pattern, List<String> stringList){
final StringBuilder regexBuilder = new StringBuilder("^");
final String intrimRegex = pattern.replace("*",".*");
regexBuilder.append(intrimRegex).append("$");
final String regex = regexBuilder.toString();
final List<String> matchedStrings = new ArrayList<>();
for(String stringToMatch:stringList){
if(stringToMatch.matches(regex)){
matchedStrings.add(stringToMatch);
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
stringList.add("car");
stringList.add("caw");
stringList.add("acauw");
List<String> matchedList = new StringSearcher().search("c*w",stringList);
if(matchedList.size() == 0){
System.out.println("No match found");
return;
}
System.out.println("Following are the string matching the pattern:");
for(String matchedString: matchedList){
System.out.println(matchedString);
}
}
}

- Sameer November 24, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.List;
import java.util.*;
public class StringSearcher {
public List<String> search(String pattern, List<String> stringList){
final StringBuilder regexBuilder = new StringBuilder("^");
final String intrimRegex = pattern.replace("*",".*");
regexBuilder.append(intrimRegex).append("$");
final String regex = regexBuilder.toString();
final List<String> matchedStrings = new ArrayList<>();
for(String stringToMatch:stringList){
if(stringToMatch.matches(regex)){
matchedStrings.add(stringToMatch);
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
stringList.add("car");
stringList.add("caw");
stringList.add("acauw");
List<String> matchedList = new StringSearcher().search("c*w",stringList);
if(matchedList.size() == 0){
System.out.println("No match found");
return;
}
System.out.println("Following are the string matching the pattern:");
for(String matchedString: matchedList){
System.out.println(matchedString);
}
}
}

- Sameer November 24, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Easy Python solution using tries:

def trieSearch(words, pattern):


	class Trie:

		def __init__(self):
			self.isWord = False 
			self.childrens = dict()


	def printTrie(trie, curr_word):

		if not trie:
			return
		if trie.isWord:
			print(curr_word)

		for children, trieNode in trie.childrens.iteritems():
			printTrie(trieNode,curr_word+children) 

	# Search funtionality for a give true and pattern
	def search(trie, pattern, curr_word, res):

		if not trie:
			return 

		if (not pattern or set(pattern)=='*') and trie.isWord:
			res.append(curr_word)
			return 

		if pattern[0] in trie.childrens:
				search(trie.childrens[pattern[0]], pattern[1:], curr_word + pattern[0],res)
		elif pattern[0]=='*':
			for char, children in trie.childrens.iteritems():
				search(children, pattern, curr_word + char, res)
				search(children, pattern[1:], curr_word + char, res)

	root = Trie()

	# Add all words in the word list to this Trie
	for word in words: 
		temp = root
		for char in word:
			if char not in temp.childrens:
				temp.childrens[char] = Trie()
			temp = temp.childrens[char]
		temp.isWord=True 

	# PrintTrie
	printTrie(root,'')

	# Search for the pattern
	res = []
	search(root, pattern, '', res)
	print(' Result : {}'.format(res))
	return res


def main():

	# TrieSearch with '*'
	words, pattern = ['car','cauw','cow','basdas'], 'c*w'
	trieSearch(words, pattern)

- DyingLizard December 20, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assuming * means 0 or more characters, every time you encounter a *, you have 1 of 3 decisions to make:
1. Consume 1 character from the input, but continue matching for * (c*w matches caaaw)
2. Consume 1 character from the input and consume the * and continue (c*w matches caw)
3. Consume the * and continue (c*w matches cw)

def match(haystack, needle):
    if not haystack and not needle:
        return True
    elif not haystack or not needle:
        return False
    elif needle[0] == '*':
        return match(haystack[1:], needle) or \
               match(haystack[1:], needle[1:]) or \
               match(haystack, needle[1:])
    elif needle[0] == haystack[0]:
        return match(haystack[1:], needle[1:])
    else:
       return False

- saishg April 17, 2018 | Flag Reply


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