We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- No Prefix Set
- Discussions
No Prefix Set
No Prefix Set
Sort by
recency
|
209 Discussions
|
Please Login in order to post a comment
Do I have to predict HackRank's solution testing order?
Use Trie with python and create find_prefix function. In find_prefix function, consider the inserting order. For example :
words_1 = ["dogfood","dog"]
orwords_2= ["dog","dogfood"]
. In word_1, the length of "dogfood" is longer than "dog", so that thecurrent.is_word_end
is not working. Thus, we have thereturn True
outside the loop check. In word_2, the length of "dog" is shorter than "dogfood", When we check "dogfood", we will find "dog". Then we get thecurrent.is_word_end
is True.Besides, if there is not any same char in child node then we
return False
.Solution in Python, a little rusty on perfect Trie implementation but this did the trick.
To tackle the ordering and avoid sorting the list, the key check is in
Full code:
I managed to have a solution passing tests other than dictionary tree. Sort the words. For each word check with words greater than it and break when not a prefix. Among the pair, the one with greater index in the unsorted original array is the one triggering the "BAD SET". However we need to iterate to the end and keep the first.
This problem is annoying because it is solution dependent and doing the most basic solution using sets/dicts is too slow to pass all the test cases. Any implementation of a Trie data structure will pass all tests though. Here is mine after some help cleaning up from our AI overlords: