|
| 1 | +#include <bits/stdc++.h> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +/* |
| 5 | + Alien Dictionary Problem |
| 6 | + ------------------------ |
| 7 | + Given a sorted dictionary of an alien language (lexicographically sorted), |
| 8 | + find the order of characters in the alien alphabet. |
| 9 | + |
| 10 | + Approach: |
| 11 | + - Build a directed graph where an edge u → v means 'u' comes before 'v'. |
| 12 | + - Perform topological sort (Kahn's Algorithm) to get the character order. |
| 13 | +*/ |
| 14 | + |
| 15 | +class Solution { |
| 16 | +public: |
| 17 | + string findOrder(vector<string>& dict, int K) { |
| 18 | + // Step 1: Build adjacency list for K characters |
| 19 | + vector<int> adj[K]; |
| 20 | + |
| 21 | + // Compare adjacent words to find ordering |
| 22 | + for (int i = 0; i < dict.size() - 1; i++) { |
| 23 | + string word1 = dict[i]; |
| 24 | + string word2 = dict[i + 1]; |
| 25 | + int len = min(word1.size(), word2.size()); |
| 26 | + |
| 27 | + for (int j = 0; j < len; j++) { |
| 28 | + if (word1[j] != word2[j]) { |
| 29 | + adj[word1[j] - 'a'].push_back(word2[j] - 'a'); |
| 30 | + break; // Only first differing character matters |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // Step 2: Perform Topological Sort (Kahn's Algorithm) |
| 36 | + vector<int> indegree(K, 0); |
| 37 | + for (int i = 0; i < K; i++) { |
| 38 | + for (auto it : adj[i]) |
| 39 | + indegree[it]++; |
| 40 | + } |
| 41 | + |
| 42 | + queue<int> q; |
| 43 | + for (int i = 0; i < K; i++) { |
| 44 | + if (indegree[i] == 0) |
| 45 | + q.push(i); |
| 46 | + } |
| 47 | + |
| 48 | + string order; |
| 49 | + while (!q.empty()) { |
| 50 | + int node = q.front(); |
| 51 | + q.pop(); |
| 52 | + |
| 53 | + order += (node + 'a'); |
| 54 | + |
| 55 | + for (auto neigh : adj[node]) { |
| 56 | + indegree[neigh]--; |
| 57 | + if (indegree[neigh] == 0) |
| 58 | + q.push(neigh); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + // Step 3: Return result |
| 63 | + return order; |
| 64 | + } |
| 65 | +}; |
| 66 | + |
| 67 | +int main() { |
| 68 | + /* |
| 69 | + Example: |
| 70 | + Dictionary = {"baa", "abcd", "abca", "cab", "cad"} |
| 71 | + K = 4 (characters: a, b, c, d) |
| 72 | + |
| 73 | + Possible order: b -> d -> a -> c |
| 74 | + Output: "bdac" (or another valid topological ordering) |
| 75 | + */ |
| 76 | + |
| 77 | + vector<string> dict = {"baa", "abcd", "abca", "cab", "cad"}; |
| 78 | + int K = 4; |
| 79 | + |
| 80 | + Solution sol; |
| 81 | + string result = sol.findOrder(dict, K); |
| 82 | + |
| 83 | + cout << "Alien Dictionary Order: " << result << endl; |
| 84 | + |
| 85 | + return 0; |
| 86 | +} |
0 commit comments