Facebook Interview Question
SDE1sCountry: United States
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);
}
}
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;
}
}
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);
}
}
}
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);
}
}
}
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);
}
}
}
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);
}
}
}
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);
}
}
}
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)
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
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:
- Matviy Ilyashenko November 12, 2017