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.
this solution uses a TreeSet --this is all that is needed.
A TreeSet holds items in sorted order; so as I process items from the original input list, I do the following;
find the least element in this set greater than or equal to the given element, or null if there is no such element.
find the greatest element in this set less than or equal to the given element, or null if there is no such element.
check if the current word being processed is (or has) a prefix to (for) an already processed word in the set.
if #3 is false, then add current word to the set of processed words. [this must be done last before the loop continues, so that we can catch & return the duplicate -since the duplicate will be a valid answer]
publicstaticvoidnoPrefix(List<String>words){// Write your code hereTreeSet<String>treeSet=newTreeSet<>();for(inti=0;i<words.size();i++){Stringword=words.get(i);Stringnext=treeSet.ceiling(word);Stringprev=treeSet.floor(word);if((next!=null&&next.startsWith(word))||(prev!=null&&word.startsWith(prev))){System.out.println("BAD SET");System.out.println(word);return;}treeSet.add(word);}System.out.println("GOOD SET");}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
No Prefix Set
You are viewing a single comment's thread. Return to all comments →
Straightforward Java soluion
this solution uses a TreeSet --this is all that is needed.
A TreeSet holds items in sorted order; so as I process items from the original input list, I do the following; find the least element in this set greater than or equal to the given element, or null if there is no such element. find the greatest element in this set less than or equal to the given element, or null if there is no such element. check if the current word being processed is (or has) a prefix to (for) an already processed word in the set. if #3 is false, then add current word to the set of processed words. [this must be done last before the loop continues, so that we can catch & return the duplicate -since the duplicate will be a valid answer]