Facebook L4 question query

Anonymous User
1405
Sep 13, 2021
Sep 14, 2021

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 infact "abcd" is the required string for "ebcd"]. Probably need to add/restructure a normal trie, not sure!

My solution:
Remove duplicates
Maintain a 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)

Comments (10)