Google Interview Question Software Engineer / Developers
0of 0 votesWhen people search at Google, they often type two words without space. For example, instead of typing "binary tree", someone can type "binarytree". Given an input, what is a good way of finding if it is a combination of two valid words?
same as : careercup.com/question?id=10060840
2 complete solutions (both based on DP) have been posted there.
I think the interviewer wanted to know if you can do something similar to Rabin-Karp algorithm. Basically keep building the first word by concatenating characters and compute hash (remember in R-K algo. the hash computation does not depend on the length of string). Similarly compute hash of the last word simultaneously (ok the first time it will be O(n-1) = O(n) but that's one time cost). If both hashes are present in dictionary only then do actual comparison, otherwise keep shifting a character from front of second word to the end of first word and repeat. Even if both words are present you must use other heuristics such as frequency of words and/or frequency of words occurring together to sort the list of words found as suggestions.
Use to prefix tree to get the sorted list of candidate breaking positions.
Use to suffix tree to get the sorted list of candidate breaking positions.
Find the common elements between two sorted lists.
Total time is O(N).
What anonimous said its true to a certain point, but this problem is much easier that the pointed one. Can be done in O(n) time and O(n) space, given a dictionary of words.
Algorthm:
1. Split the input string in two parts between every characters.
2. check if both sides are present in dictionary, if so you have two words
- lucas.eustaquio on August 03, 2011 Edit | Flag Replypublic class SplitStrings { public static List<String[]> splitStr(Set<String> dictionary, String str) { List<String[]> options = new ArrayList<String[]>(); for (int i=1; i<str.length();++i) { if (dictionary.contains(str.substring(0,i)) && dictionary.contains(str.substring(i))) { options.add(new String[] {str.substring(0,i), str.substring(i)}); } } return options; } }