Facebook L4 question query
Company: Meta (Facebook)
Role: e4
Interview Stage: Phone Screen
Location: unknown
Year: unknown
Original Post Content:
Given n strings (all of length L), check if there exists two strings which are different at only one position
Example :
["abc", "add", "xyz"] -> False
["abcd", "abxx", "azcd"] -> True (as "abcd" and "azcd" are different at only one position)
I gave a solution with time complexity O(n*L*L). Is there a better way to do this ?
Note :
Normal trie lookup wouldn't work. Say you have following words in trie : ["abcd", "exxx"]. Now when you do a lookup for say "ebcd", then you would go along the path of "exxx" in the trie and wrongly say that there isn't any required string for "ebcd" (while in fact "abcd" is the required string for "ebcd"]. Probably need to add/restructure a normal trie, not sure!
My solution:
Remove duplicates
Maintain an unordered set of {prefix, suffix}
For each string : consider ith position -> see if {s[0..i-1], s[i+1, s.length()-1]} is in our set : if yes return true, if not insert it in our set
As for each word (n), we are considering each position (L), and the set lookup would take O(L) time [time to compute hash for {prefix, suffix} ], total complexity is O(n*L*L)