</>

269. Alien Dictionary

Hard NeetCode 150
Advanced Graphs Time O(C) Space O(U+E)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Advanced Graphs
Time
O(C)
Space
O(U+E)

Standard Solution (C++)

SummaryGiven a sorted list of words in an alien language, deduce a valid ordering of that language's alphabet, returning any one valid ordering as a string — or an empty string if no consistent ordering exists.

Approach
  • Extract ordering constraints: compare each adjacent pair of words character by character; the first differing character position gives a directed edge a -> b meaning a comes before b in the alien alphabet. A longer word prefix-dominating a shorter word is invalid.
  • Build a directed graph over the unique characters using an adjacency list and track each node's in-degree.
  • Topological sort via BFS (Kahn's algorithm): seed the queue with all zero-in-degree nodes, repeatedly remove a node, emit it, and decrement neighbors' in-degrees, pushing any newly zeroed neighbor.
  • If the result string does not contain every unique character, a cycle exists (contradiction), so return "".
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <queue>
using namespace std;

class Solution {
public:
    string alienOrder(vector<string>& words) {
        // Collect every unique character and initialise in-degree to 0.
        unordered_map<char, int> inDegree;
        unordered_map<char, unordered_set<char>> adj;

        for (const string& w : words)
            for (char c : w)
                inDegree.emplace(c, 0);  // no-op if already present

        // Derive ordering edges from adjacent word pairs.
        for (int i = 0; i + 1 < (int)words.size(); ++i) {
            const string& a = words[i];
            const string& b = words[i + 1];
            int minLen = min(a.size(), b.size());

            bool found = false;
            for (int j = 0; j < minLen; ++j) {
                if (a[j] != b[j]) {
                    // Edge a[j] -> b[j]; guard against duplicate edges.
                    if (!adj[a[j]].count(b[j])) {
                        adj[a[j]].insert(b[j]);
                        ++inDegree[b[j]];
                    }
                    found = true;
                    break;
                }
            }
            // "abc" before "ab" is impossible in any sorted dictionary.
            if (!found && a.size() > b.size()) return "";
        }

        // Kahn's BFS topological sort.
        queue<char> q;
        for (auto& [c, deg] : inDegree)
            if (deg == 0) q.push(c);

        string order;
        while (!q.empty()) {
            char u = q.front(); q.pop();
            order += u;
            for (char v : adj[u])
                if (--inDegree[v] == 0) q.push(v);
        }

        // A cycle means some characters were never emitted.
        return order.size() == inDegree.size() ? order : "";
    }
};
Time O(C) where C is the total number of characters across all words — each character is visited once to build the graph and once during BFS. The graph itself is bounded by O(U + min(U^2, N)) edges where U ≤ 26 unique letters and N is the number of adjacent word pairs, making the overall complexity effectively O(C). Space O(U + E) for the adjacency list and in-degree map, where U is the number of unique characters and E the number of edges; both are bounded by the 26-letter alphabet, so O(1) in practice.

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <queue>
using namespace std;

class Solution {
public:
    string alienOrder(vector<string>& words) {
        if(words.empty()){
            return "";
        }

        std::unordered_set<char> all_chars;
        for(const string& w: words){
            for(const char& c: w){
                all_chars.insert(c);
            }
        }

        // build inDegree
        std::unordered_map<char, int> inDegree;
        for(const char c: all_chars){
            inDegree[c]=0;
        }

        // build adj list
        std::unordered_map<char, std::unordered_set<char>> adj;
        for(int i=0; i<words.size()-1; ++i){
            const string& s1=words[i];
            const string& s2=words[i+1];

            int len1=s1.length();
            int len2=s2.length();

            bool foundDiff=false;
            for(int j=0; j<std::min(len1, len2); ++j){
                if(s1[j]!=s2[j]){
                    if(!adj[s1[j]].count(s2[j])){
                        adj[s1[j]].insert(s2[j]);
                        ++inDegree[s2[j]];
                    }
                    foundDiff=true;
                    break;
                }
            }
            if(!foundDiff && len1>len2){
                return "";
            }
        }

        // bfs
        string res="";
        queue<char> q;
        for(const auto& [ch, degree]: inDegree){
            if(degree==0){
                q.push(ch);
            }
        }

        while(!q.empty()){
            char u=q.front();
            q.pop();
            res+=u;
            for(char v: adj[u]){
                --inDegree[v];
                if(inDegree[v]==0){
                    q.push(v);
                }
            }
        }

        if(res.length()!=all_chars.size()){
            return "";
        }

        return res;

    }
};

// Time Complexity: O(C) where C is the total number of characters in all words. We need to iterate through all characters to build the graph and perform BFS.
// Space Complexity: O(U+E) where U is the number of unique characters and E is the number of edges in the graph. We need space to store the graph and the in-degree of each character.
// But it's bound by 26^2, so we can consider it O(1) in terms of space complexity.
Time O(C) Space O(U+E)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern