|
| 1 | +package java1.algorithms.graph; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class AlienDictionary { |
| 6 | + |
| 7 | + //BFS(Topological sorting through Kahn's alogirthm):- TC: O(m*n) SC:O(m*n) |
| 8 | + private static String alienOrder(String[] words) { |
| 9 | + if(words == null || words.length == 0) return null; |
| 10 | + |
| 11 | + Map<Character, List<Character>> adjList = new HashMap<>(); |
| 12 | + int[] inDegree = new int[26]; |
| 13 | + |
| 14 | + for(int i=0; i< words.length-1; i++) { |
| 15 | + String currWord = words[i], nextWord = words[i+1]; |
| 16 | + if(currWord.length() > nextWord.length() && currWord.substring(0, nextWord.length()).equals(nextWord)) { |
| 17 | + return ""; |
| 18 | + } |
| 19 | + for(int j=0; j< Math.min(currWord.length(), nextWord.length()); j++) { |
| 20 | + char ch1 = currWord.charAt(j); |
| 21 | + char ch2 = nextWord.charAt(j); |
| 22 | + if(ch1 != ch2) { |
| 23 | + if(!adjList.containsKey(ch1)) { |
| 24 | + adjList.put(ch1, new ArrayList<>()); |
| 25 | + } |
| 26 | + adjList.get(ch1).add(ch2); |
| 27 | + inDegree[ch2- 'a']++; |
| 28 | + break; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + Set<Character> uniqueLetters = new HashSet<>(); |
| 34 | + for(String word: words) { |
| 35 | + for(char ch: word.toCharArray()) { |
| 36 | + uniqueLetters.add(ch); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + PriorityQueue<Character> queue = new PriorityQueue<>(); |
| 41 | + for(char ch: uniqueLetters) { |
| 42 | + if(inDegree[ch-'a'] == 0) { |
| 43 | + queue.add(ch); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + String topSort = ""; |
| 48 | + while(!queue.isEmpty()) { |
| 49 | + char ch = queue.poll(); |
| 50 | + topSort += ch; |
| 51 | + if(adjList.get(ch) == null) continue; |
| 52 | + for(char neighbour: adjList.get(ch)) { |
| 53 | + if(--inDegree[neighbour-'a'] == 0) { |
| 54 | + queue.add(neighbour); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + return topSort.length() == uniqueLetters.size() ? topSort : ""; |
| 59 | + } |
| 60 | + |
| 61 | + public static void main(String[] args) { |
| 62 | + String[] words = {"wrt", "wrf", "er", "ett", "rftt"}; |
| 63 | + System.out.println(alienOrder(words)); |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments