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.
To keep it simple, just use a BST and make a second pass through the list. Example in Java 17:
/** * Find the first string within a list which creates a prefix * relationship with any other string. * * Applies a sorted map. Reporting the first occurrence is * rather troublesome: This requires tracking the index of * each prefix relationship and making a second pass. * * 𝚯(N log N) * 𝚯(N) space (red-black tree) * * https://github.com/profinite/HackerRank/ */publicstaticvoidnoPrefix(List<String>words){TreeMap<String,Integer>sorted=newTreeMap<>();intmin=Integer.MAX_VALUE;// index of first observable prefixintindex=0;for(Stringword:words){if(sorted.containsKey(word))// check for identicalmin=Math.min(min,index);sorted.putIfAbsent(word,index++);// sort the strings}for(Stringword:words.stream().distinct().toList()){Stringnext=sorted.higherKey(word);while(isPrefix(word,next)){min=Math.min(min,Math.max(sorted.get(word),sorted.get(next)));next=sorted.higherKey(next);}}if(min!=Integer.MAX_VALUE)System.out.println("BAD SET\n"+words.get(min));elseSystem.out.println("GOOD SET");}staticbooleanisPrefix(Stringpre,Stringfull){returnpre!=null&&full!=null&&full.startsWith(pre);}
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 →
Optionally, no need for a trie here.
To keep it simple, just use a BST and make a second pass through the list. Example in Java 17: