Skip to content

Commit edb0d72

Browse files
committed
creating a graph and doing a topological sort
1 parent 5d15d96 commit edb0d72

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

BFS/alienOrder.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution {
2+
public String alienOrder(String[] words) {
3+
if (words == null || words.length == 0) {
4+
return "";
5+
}
6+
HashMap<Character, HashSet<Character>> graph = new HashMap<>();
7+
int[] inDegreeMap = new int[26]; //to keep a track of indegrees to a
8+
// character
9+
/* according to given dictionary with specified order, traverse every pair of words,
10+
* then put each pair into graph map to build the graph, and then update inDegree map
11+
* for every "nextChar" (increase their inDegree by 1 every time) */
12+
for (String s: words) {
13+
for( char x: s.toCharArray()) {
14+
graph.putIfAbsent(x, new HashSet<>());
15+
}
16+
}
17+
for (int i=0; i< words.length - 1; i++) {
18+
String first = words[i];
19+
String second = words[i+1];
20+
int len = Math.min(first.length(), second.length());
21+
for (int j=0; j<len; j++) {
22+
if (first.charAt(j) != second.charAt(j)) {
23+
char f = first.charAt(j);
24+
char s = second.charAt(j);
25+
if (!graph.get(f).contains(s)) {
26+
graph.get(f).add(s);
27+
inDegreeMap[(int)(s - 'a')]++;
28+
}
29+
}
30+
break;
31+
}
32+
}
33+
// Doing a BFS but putting all starting nodes i.e ones with inDegree 0 in the queue
34+
// and then exploring their neighbours, if we get indegree 0, we add to queue to
35+
// further evaluate.
36+
Queue<Character> q = new LinkedList<>();
37+
StringBuilder sb = new StringBuilder();
38+
for (char c: graph.keySet()) {
39+
if (inDegreeMap[(int)(c-'a')] == 0) {
40+
q.offer(c);
41+
}
42+
}
43+
44+
while(!q.isEmpty()) {
45+
char out = q.poll();
46+
sb.append(out);
47+
if (graph.get(out) == null) {
48+
continue;
49+
}
50+
System.out.println(out);
51+
for (char neighbour: graph.get(out)) {
52+
inDegreeMap[(int)(neighbour -'a')]--;
53+
if (inDegreeMap[(int)(neighbour - 'a')] == 0) {
54+
q.offer(neighbour);
55+
}
56+
}
57+
}
58+
return sb.length() == graph.size() ? sb.toString() : "";
59+
}
60+
}

0 commit comments

Comments
 (0)