{"id":22513464,"url":"https://github.com/emahtab/alien-dictionary","last_synced_at":"2026-03-19T23:02:41.876Z","repository":{"id":79525248,"uuid":"262534091","full_name":"eMahtab/alien-dictionary","owner":"eMahtab","description":"Find the order of alphabets in an alien dictionary","archived":false,"fork":false,"pushed_at":"2024-10-27T02:24:13.000Z","size":49,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-02T18:11:21.211Z","etag":null,"topics":["graph","leetcode","problem-solving","topological-sort"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eMahtab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-05-09T09:19:39.000Z","updated_at":"2024-10-27T02:24:17.000Z","dependencies_parsed_at":"2025-06-02T09:05:34.841Z","dependency_job_id":"69c09866-3ecd-4a69-88a7-55f2d5c038da","html_url":"https://github.com/eMahtab/alien-dictionary","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/eMahtab/alien-dictionary","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Falien-dictionary","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Falien-dictionary/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Falien-dictionary/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Falien-dictionary/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eMahtab","download_url":"https://codeload.github.com/eMahtab/alien-dictionary/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Falien-dictionary/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28879088,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-29T10:31:27.438Z","status":"ssl_error","status_checked_at":"2026-01-29T10:31:01.017Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graph","leetcode","problem-solving","topological-sort"],"created_at":"2024-12-07T03:12:25.782Z","updated_at":"2026-01-29T14:11:54.719Z","avatar_url":"https://github.com/eMahtab.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Alien Dictionary\n## https://leetcode.com/problems/alien-dictionary\n\nThere is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you. You receive a list of non-empty words from the dictionary, where words are sorted lexicographically by the rules of this new language. Derive the order of letters in this language.\n```\nExample 1:\n\nInput:\n[\n  \"wrt\",\n  \"wrf\",\n  \"er\",\n  \"ett\",\n  \"rftt\"\n]\n\nOutput: \"wertf\"\n\nExample 2:\n\nInput:\n[\n  \"z\",\n  \"x\"\n]\n\nOutput: \"zx\"\n\nExample 3:\n\nInput:\n[\n  \"z\",\n  \"x\",\n  \"z\"\n] \n\nOutput: \"\" \nExplanation: The order is invalid, so return \"\".\n```\n\n**Note:**\n1. You may assume all letters are in lowercase.\n2. If the order is invalid, return an empty string.\n3. There may be multiple valid order of letters, return any one of them is fine.\n\n## Approach :\nBefore we try to solve this problem, lets first understand one very important thing.\n\n**The letters within a single word don't tell us anything about the relative order.** \nFor example, the presence of the word `train` in the list does not tell us that the letter t is before the letter r in the dictionary.\nSo to find the relative order of letters in the dictionary we must compare two words.\n\n![Graph](graph.JPG?raw=true \"Graph\")\n\n# Implementation :\n```java\nclass Solution {\n    public String alienOrder(String[] words) {\n        Map\u003cCharacter, Set\u003cCharacter\u003e\u003e map = new HashMap\u003c\u003e();\n        int[] indegree = new int[26];\n        buildGraph(map, indegree, words);\n        return bfs(map, indegree);\n    }\n    \n    private void buildGraph(Map\u003cCharacter, Set\u003cCharacter\u003e\u003e map, int[] indegree, String[] words) {\n        for(String word : words) {\n            for(char ch : word.toCharArray())\n                map.putIfAbsent(ch, new HashSet\u003cCharacter\u003e());\n        }\n        \n        for(int i = 0; i \u003c words.length - 1; i++) {\n            String first = words[i];\n            String second = words[i+1];\n            // Check If second word is a prefix of first word, If thats the case its not a valid alien dictionary\n            if(first.startsWith(second) \u0026\u0026 first.length() \u003e second.length()) {\n                map.clear();\n                return;\n            }\n            int minLength = Math.min(first.length(), second.length());\n            for(int index = 0; index \u003c minLength; index++) {\n                if(first.charAt(index) != second.charAt(index)) {\n                    // If check is required, e.g. for words {ox, sx, to, ts, x}\n                    // We should not increment the indegree multiple times because of same dependency/relationship\n                    // comparison between words ox and sx tells us that o comes before s\n                    // again comparison between words to and ts tells us o comes before s\n                    if(!map.get(first.charAt(index)).contains(second.charAt(index))) {\n                        indegree[second.charAt(index) - 'a']++;\n                        map.get(first.charAt(index)).add(second.charAt(index));\n                    }\n                    break;\n                }\n            }\n                \n        }\n    }\n    \n    private String bfs(Map\u003cCharacter,Set\u003cCharacter\u003e\u003e map, int[] indegree) {\n        Queue\u003cCharacter\u003e q = new LinkedList\u003c\u003e();\n        int totalChars = map.size();\n        StringBuilder sb = new StringBuilder();\n        for(Character ch : map.keySet()) { \n            // if(map.get(ch).size() == 0) , this will be wrong to check the 0 indegree node\n            if(indegree[ch - 'a'] == 0) \n                q.add(ch);\n        }\n        int count = 0;\n        while(!q.isEmpty()) {\n            char ch = q.poll();\n            count++;\n            sb.append(ch);\n            for(char c : map.get(ch)) {\n                indegree[c - 'a']--;\n                if(indegree[c - 'a'] == 0) {\n                    q.add(c);\n                }\n            }\n        }\n        \n       return  count == totalChars ? sb.toString() : \"\";\n    }\n}\n```\n\n### Implementation 2\n```java\nclass Solution {\n    public String alienOrder(String[] words) {\n        if(words == null || words.length == 0)\n          return \"\";\n        Set\u003cCharacter\u003e allChars = new HashSet\u003c\u003e();  \n        for(String word : words)\n          for(char ch : word.toCharArray())\n             allChars.add(ch);\n\n        Map\u003cCharacter,Set\u003cCharacter\u003e\u003e relations = new HashMap\u003c\u003e();\n        for(int i = 0; i \u003c words.length - 1; i++) {\n            String s1 = words[i];\n            String s2 = words[i+1];\n            if(s1.indexOf(s2) == 0 \u0026\u0026 s1.length() \u003e s2.length())\n              return \"\";\n           \n            int minLength = Math.min(s1.length(), s2.length());\n            for(int j = 0; j \u003c minLength; j++) {\n                char ch1 = s1.charAt(j);\n                char ch2 = s2.charAt(j);\n                if(ch1 != ch2) {\n                    relations.putIfAbsent(ch2, new HashSet\u003cCharacter\u003e());\n                    relations.get(ch2).add(ch1);\n                    break;\n                }\n            }\n        }\n        StringBuilder order = new StringBuilder();\n        Queue\u003cCharacter\u003e queue = new LinkedList\u003c\u003e();\n        for(char ch : allChars){\n            if(!relations.containsKey(ch))\n              queue.add(ch);\n        }\n        while(!queue.isEmpty()) {\n            char ch = queue.remove();\n            order.append(ch);\n            for(char c : relations.keySet()) {\n                Set\u003cCharacter\u003e set = relations.get(c);\n                if(set.contains(ch)) {\n                    set.remove(ch);\n                    if(set.size() == 0) {\n                        queue.add(c);\n                    }\n                }\n            }\n        }\n        return order.length() == allChars.size() ? order.toString() : \"\";    \n    }\n}\n```\n## Important :\n1. Prefix check is required to handle e.g. [\"apple\", \"app\"] these type of inputs. \n2. Don't compare after the first different character, so break; is must\n3. Don't forget array's have `length` property while strings have `length()` method\n4. In second implementation we are using `Map` for storing indegree for each character and we are using `Set` to know all the distinct characters in the words array.\n\n# References :\nhttps://www.youtube.com/watch?v=LA0X_N-dEsg\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Falien-dictionary","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femahtab%2Falien-dictionary","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Falien-dictionary/lists"}