## 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();

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,
if(pos==pattern.length()) {
if(node.isWord)
return;
}

char ch = pattern.charAt(pos);
if(ch=='*') {
if(pos==pattern.length()-1 && node.isWord) {
if(node.children.size()==0)
return;
}

for(Map.Entry<Byte,Node> entry : node.children.entrySet()) {
Node nextNode = entry.getValue();
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) {
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();
doTest(trie,"c*w");
doTest(trie,"ca*");
doTest(trie,"c**w*");
doTest(trie,"*r*");
doTest(trie,"*");
}``````

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

``````public static void main(String args[]) {

Trie root = new Trie();

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);
}
}``````

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

``````public static void main(String[] args) {

Trie root = new Trie(false);

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;
}
}``````

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)){
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
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);
}
}
}

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)){
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
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);
}
}
}

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)){
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
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);
}
}
}

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)){
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
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);
}
}
}

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)){
}
}
return matchedStrings;
}

public static void main(String[] args){
List<String> stringList = new ArrayList<String>();
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);
}
}
}

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)``````

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``````

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.

### 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.