> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/topology/269.-alien-dictionary.md).

# 269. Alien Dictionary

becuse this Q is about order, use topology sort

be careful this case

```
exception case is : 
for ex: 
ab
a.  => return ""

if (s1.length() > s2.length() && s2.equals(s1.substring(0, s2.length()))) {
    return "";
}
```

and duplicate path should not add to map, and indgree

```
Set<Character> set = map.getOrDefault(s[j], new HashSet<>());
if (!set.contains(t[j])) {
    set.add(t[j]);
    map.put(s[j], set);
    indegree.put(t[j], indegree.getOrDefault(t[j], 0)+1);
}
```

```
T: O(V+E), V is number of char , E is edge
S: O(V)
```

```java
class Solution {
    public String alienOrder(String[] words) {
        int n = words.length;
        Map<Character, Set<Character>> map = new HashMap<>();
        Map<Character, Integer> indegree = new HashMap<>();
        
        // 這裡要先把 char 都建立過, 不然之後會取不到, 之後只有建入度不為 0 的部分
        for (String word : words) {
            for (char c : word.toCharArray()) {
                indegree.put(c, 0);
            }
        }
        
        for (int i = 0; i < n-1; i++) {
            String s1 = words[i];
            String s2 = words[i+1];
            if (s1.length() > s2.length() && s2.equals(s1.substring(0, s2.length()))) {
                return "";
            }
            char[] s = words[i].toCharArray();
            char[] t = words[i+1].toCharArray();
            for (int j = 0; j < Math.min(s.length, t.length); j++) {
                if (s[j] == t[j]) {
                    continue;
                }
                Set<Character> set = map.getOrDefault(s[j], new HashSet<>());
                if (!set.contains(t[j])) {
                    set.add(t[j]);
                    map.put(s[j], set);
                    indegree.put(t[j], indegree.getOrDefault(t[j], 0)+1);
                }
                break;
            }
        }
        
        Queue<Character> queue = new LinkedList<>();
        for (char key : indegree.keySet()) {
            if (indegree.get(key) == 0) {
                queue.offer(key);
            }
        }
        
        StringBuilder res = new StringBuilder();
        while (!queue.isEmpty()) {
            char cur = queue.poll();
            res.append(cur);
            
            for (char next : map.getOrDefault(cur, new HashSet<>())) {
                indegree.put(next, indegree.get(next) - 1);
                if (indegree.get(next) == 0) {
                    queue.offer(next);
                }
            }
        }
        return res.length() == indegree.size() ? res.toString() : "";
            
    }
}

/*
wrt
wrf
er
ett
rftt

t < f
w < e
r < t
e < r

w - e - r - t - f


topology sort

1. build graph
this is a words list
so use Map<char, list<char>>
indegree<char, int>

1.a
for (int i = 0; i < words.length -1; i++) {
    String s = 
    String t = 
    
exception case is : s.length() > t.length && t.equals(s.substring(0, t.length)), 
for ex: 
ab
a.  => return ""

1.b
then compare s , t, add to map, but notice, if s->t is duplicate, dont add!

2. topology sort algo

3. result.size() != count of char return ""
or return result

T: O(V+E), V is number of char , E is edge
S: O(V)

*/
```

沒有判斷 s -> t 是否存在重複的話, 這個 case 會不過

```java
Set<Character> set = graph.get(w1[j]);
if (!set.contains(w2[j])) {
    set.add(w2[j]);
```

![](/files/ZLLkes6SBn8hFeCtxcoe)<br>

最後還要檢查 res 長度是不是跟 indegree 長度一樣, 不然這 test case fail

```java
return res.length() == indegree.size() ? res.toString() : "";
```

![](/files/F5Osn9UspK1RRwxj2ll9)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/topology/269.-alien-dictionary.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
