Lexicographically Smallest Custom Alphabet from Sorted Words

Medium · Coding & Algorithms · Machine Learning Engineer · Onsite

Problem Statement

You are given an array words of lowercase English strings purported to be arranged in non-decreasing dictionary order under an unknown ranking of characters.

Reconstruct a string containing every distinct character present across words once, ordered so that words is sorted in non-decreasing lexicographical order under that ranking:

  • Given two strings u and v, find the earliest index i where u[i] != v[i]. If such an index exists, u precedes v when u[i] appears earlier than v[i] in the character ranking. If no index differs up to min(len(u), len(v)), u may precede v only when len(u) <= len(v).
  • Tie-breaker: When multiple character orderings satisfy every pairwise constraint in words, return the one that comes first in standard 'a'-to-'z' lexicographical order.
  • Inconsistent inputs: If no valid ordering exists—because the implied character rules contain a cycle or because a longer string appears ahead of its own shorter prefix—return "".
  • Empty or unconstrained inputs: An empty words list returns "". When words imposes no ordering rules (for instance, a single string or repeated identical strings), return all distinct characters in 'a'-to-'z' order.
def find_smallest_alphabet(words: List[str]) -> str:

Examples

Example 1

Input: words = ["wn", "wg"]
Output: "ngw"

Walk-through: - "wn" and "wg" match at index 0 ('w') and differ at index 1, requiring 'n' before 'g'. - 'w' has no constraints. Placing 'n' then 'g' ahead of 'w' produces "ngw", the smallest 'a'–'z' permutation with 'n' before 'g'.

Example 2

Input: words = ["pk", "pd", "dk", "da"]
Output: "kapd"

Walk-through: - Adjacent pairs require 'k' before 'd' ("pk" vs "pd"), 'p' before 'd' ("pd" vs "dk"), and 'k' before 'a' ("dk" vs "da"). - Initially 'k' and 'p' have no prerequisites; choosing 'k' first ('k' < 'p') unlocks 'a', which then precedes 'p' ('a' < 'p'), followed by 'p' and 'd'.

Example 3

Input: words = ["plan", "pla"]
Output: ""

Walk-through: - "pla" is a shorter prefix of "plan", so "plan" cannot appear before "pla" under any character ranking.

Example 4

Input: words = ["mg", "mt", "gb", "gr", "tb", "br"]
Output: "mgtbr"

Walk-through: - Adjacent comparisons yield 'g' -> 't', 'm' -> 'g', 'b' -> 'r', 'g' -> 't' (repeated), and 't' -> 'b', forming the unique chain 'm' -> 'g' -> 't' -> 'b' -> 'r'.

Constraints

  • 0 <= len(words) <= 100
  • 1 <= len(words[i]) <= 100
  • Every words[i] consists solely of lowercase English letters ('a'–'z').

Step-by-step walkthrough

  1. Understand the goal and invalid cases

    We are given words, a list of strings already ordered under a hidden character ranking. We want to return a single string containing every unique character that appears anywhere in words, arranged in an order that keeps words validly sorted.

    Two extra rules shape the output:

    • Tie-breaker: When more than one valid alphabet exists, return the one that comes first in normal 'a'-to-'z' dictionary order (for example, "ngw" beats "nwg" and "wng").
    • Contradictions return "": No valid alphabet exists if the clues form a loop (such as 'a' before 'b' and 'b' before 'a') or if a longer word appears before its own shorter prefix (such as ["plan", "pla"], because in dictionary order "pla" always comes before "plan" no matter how letters are ranked).

    If words is empty, has only one word, or repeats the exact same word, there are zero ordering clues, so every unique character simply comes back sorted from 'a' to 'z'.

  2. Why brute force is too slow

    A direct brute-force method collects the U distinct characters, generates all U! permutations in 'a'-to-'z' order, and returns the first permutation under which words is sorted.

    That works as a test check when U <= 6, because 6! = 720. However, lowercase English has up to U = 26 letters, and 26! is roughly 4 * 10^26. Instead of guessing whole alphabets, we need to read the exact ordering rules out of words and build the answer one character at a time.

  3. Extract ordering rules from adjacent words

    How do two words reveal a letter rule? Compare neighboring words character by character from left to right:

    Compare "mg" and "mt":
      pos 0: 'm' == 'm'  (tie, keep looking)
      pos 1: 'g' != 't'  --> first mismatch! Rule: 'g' must come before 't'
    
    Compare "abz" and "acy":
      pos 0: 'a' == 'a'
      pos 1: 'b' != 'c'  --> first mismatch! Rule: 'b' must come before 'c'
      pos 2: 'z' vs 'y'  --> IGNORE (pos 1 already decided "abz" < "acy")
    

    Three key facts keep this scan simple and complete:

    1. Stop at the first mismatch: Once position pos differs, later letters have zero effect on which word comes first.
    2. Check the prefix trap: If no position differs up to the shorter word's length, one word is a prefix of the other. "pla" before "plan" is always valid and adds no letter rule, whereas "plan" before "pla" is impossible and immediately forces "".
    3. Adjacent pairs are enough: Dictionary order is transitive (if word[0] <= word[1] and word[1] <= word[2], then word[0] <= word[2] automatically). Satisfying every neighboring pair (words[i], words[i + 1]) guarantees the entire list is sorted.
  4. Model the rules as a dependency graph

    Treat every unique character in words as a node in a directed graph, and every rule "u must appear before v" as a directed arrow u -> v. For each character v, we also count its in-degree: how many distinct characters must appear before v.

    • Register every character first: A letter like 'w' in ["wn", "wg"] never appears at a mismatch position, yet it must still be in the final alphabet. Initializing every character with an empty set() and in_degree = 0 ensures no letter is forgotten.
    • Deduplicate edges: Two different word pairs might produce the same rule 'g' -> 't' (as in Example 4). Storing successors[earlier_char] as a set ensures we increment in_degree[later_char] only once per distinct rule.
    def build_dependency_graph(
        words: List[str],
    ) -> Optional[Tuple[Dict[str, Set[str]], Dict[str, int]]]:
        """Build character ordering graph u -> v ('u before v'), or None if prefix order is invalid."""
        # successors: {char: set of chars that must appear AFTER char}, e.g. {'n': {'g'}, 'g': set()}
        successors: Dict[str, Set[str]] = {}
        # in_degree: {char: count of distinct chars that must appear BEFORE char}, e.g. {'n': 0, 'g': 1}
        in_degree: Dict[str, int] = {}
    
        # Phase 1: Register every unique character so unconstrained letters still appear in the output.
        for word in words:
            for ch in word:
                if ch not in successors:
                    successors[ch] = set()
                    in_degree[ch] = 0
    
        # Phase 2: Compare each adjacent pair of words to extract at most one ordering rule.
        for i in range(len(words) - 1):
            left_word = words[i]
            right_word = words[i + 1]
            shared_len = min(len(left_word), len(right_word))
            found_difference = False
    
            for pos in range(shared_len):
                if left_word[pos] != right_word[pos]:
                    earlier_char = left_word[pos]
                    later_char = right_word[pos]
                    # Deduplicate edges so repeated rules do not inflate in_degree[later_char].
                    if later_char not in successors[earlier_char]:
                        successors[earlier_char].add(later_char)
                        in_degree[later_char] += 1
                    found_difference = True
                    # Stop at the first mismatch: later positions play no role in dictionary order.
                    break
    
            # A longer word cannot come before its own shorter prefix (e.g. "plan" before "pla").
            if not found_difference and len(left_word) > len(right_word):
                return None
    
        return successors, in_degree
    
  5. Pick the smallest available letter with a min-heap

    We now need a topological sort: a left-to-right arrangement of all nodes where every arrow u -> v points forward. Kahn's algorithm builds this order step by step:

    1. Any character with in_degree == 0 has zero unmet prerequisites, so it is safe to place right now.
    2. Once we place a character current_char, its requirement on each next_char in successors[current_char] is satisfied, so we subtract 1 from in_degree[next_char]. Whenever in_degree[next_char] hits 0, next_char becomes unlocked too.

    Why use a min-heap (heapq) instead of a plain queue? Look at Example 1, words = ["wn", "wg"]. The only rule is 'n' -> 'g', while 'w' is completely free. At the start, both 'n' and 'w' have in_degree == 0. A plain queue might pop 'w' first and return "wng", whereas a min-heap always pops the smallest 'a'-to-'z' character currently unlocked:

    • Heap ['n', 'w'] pops 'n', which unlocks 'g' -> heap becomes ['g', 'w'].
    • Heap ['g', 'w'] pops 'g' -> heap becomes ['w'].
    • Heap ['w'] pops 'w' -> result "ngw", the smallest valid alphabet!

    Finally, if the graph contains a cycle (like 'a' -> 'b' -> 'a'), the characters on that cycle never drop to in_degree == 0, so len(result_chars) < len(in_degree) catches every contradiction cleanly.

    def run_kahns_min_heap(
        successors: Dict[str, Set[str]], in_degree: Dict[str, int]
    ) -> str:
        available_heap: List[str] = []
        for ch, count in in_degree.items():
            if count == 0:
                heapq.heappush(available_heap, ch)
    
        result_chars: List[str] = []
        while available_heap:
            current_char = heapq.heappop(available_heap)
            result_chars.append(current_char)
    
            for next_char in successors[current_char]:
                in_degree[next_char] -= 1
                if in_degree[next_char] == 0:
                    heapq.heappush(available_heap, next_char)
    
        if len(result_chars) < len(in_degree):
            return ""
        return "".join(result_chars)
    
  6. Trace Example 2 end to end

    Let's trace words = ["pk", "pd", "dk", "da"]:

    Adjacent pair    First mismatch     Rule added
    "pk" vs "pd"     pos 1: 'k' != 'd'  'k' -> 'd'
    "pd" vs "dk"     pos 0: 'p' != 'd'  'p' -> 'd'
    "dk" vs "da"     pos 1: 'k' != 'a'  'k' -> 'a'
    
    Graph:   'k' ---> 'a'
              \
               v
              'd' <--- 'p'
    
    Initial in_degree: {'k': 0, 'p': 0, 'd': 2, 'a': 1}
    

    Now watch available_heap and in_degree update at each step:

    Step  available_heap  Pop   in_degree updates          result_chars
    1     ['k', 'p']      'k'   'd': 2 -> 1, 'a': 1 -> 0   ['k']
    2     ['a', 'p']      'a'   (none)                     ['k', 'a']
    3     ['p']           'p'   'd': 1 -> 0                ['k', 'a', 'p']
    4     ['d']           'd'   (none)                     ['k', 'a', 'p', 'd']
    

    Notice step 2: unlocking 'a' after popping 'k' immediately pushes 'a' ahead of 'p' in the min-heap! All 4 unique characters were placed (len(result_chars) == 4), so we join them into "kapd".

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    
    def build_dependency_graph(
        words: List[str],
    ) -> Optional[Tuple[Dict[str, Set[str]], Dict[str, int]]]:
        """Build character ordering graph u -> v ('u before v'), or None if prefix order is invalid."""
        # successors: {char: set of chars that must appear AFTER char}, e.g. {'n': {'g'}, 'g': set()}
        successors: Dict[str, Set[str]] = {}
        # in_degree: {char: count of distinct chars that must appear BEFORE char}, e.g. {'n': 0, 'g': 1}
        in_degree: Dict[str, int] = {}
    
        # Phase 1: Register every unique character so unconstrained letters still appear in the output.
        for word in words:
            for ch in word:
                if ch not in successors:
                    successors[ch] = set()
                    in_degree[ch] = 0
    
        # Phase 2: Compare each adjacent pair of words to extract at most one ordering rule.
        for i in range(len(words) - 1):
            left_word = words[i]
            right_word = words[i + 1]
            shared_len = min(len(left_word), len(right_word))
            found_difference = False
    
            for pos in range(shared_len):
                if left_word[pos] != right_word[pos]:
                    earlier_char = left_word[pos]
                    later_char = right_word[pos]
                    # Deduplicate edges so repeated rules do not inflate in_degree[later_char].
                    if later_char not in successors[earlier_char]:
                        successors[earlier_char].add(later_char)
                        in_degree[later_char] += 1
                    found_difference = True
                    # Stop at the first mismatch: later positions play no role in dictionary order.
                    break
    
            # A longer word cannot come before its own shorter prefix (e.g. "plan" before "pla").
            if not found_difference and len(left_word) > len(right_word):
                return None
    
        return successors, in_degree
    
    
    def find_smallest_alphabet(words: List[str]) -> str:
        graph = build_dependency_graph(words)
        if graph is None:
            return ""
        successors, in_degree = graph
    
        # Phase 3: Seed a min-heap with characters that have zero prerequisites.
        # available_heap: min-heap of unlocked characters, e.g. ['k', 'p'], ordered 'a'..'z'.
        available_heap: List[str] = []
        for ch, count in in_degree.items():
            if count == 0:
                heapq.heappush(available_heap, ch)
    
        # Greedily pop the smallest unlocked character to build the lexicographically smallest order.
        result_chars: List[str] = []
        while available_heap:
            current_char = heapq.heappop(available_heap)
            result_chars.append(current_char)
    
            for next_char in successors[current_char]:
                in_degree[next_char] -= 1
                if in_degree[next_char] == 0:
                    heapq.heappush(available_heap, next_char)
    
        # Phase 4: If some characters never reached in-degree 0, a cycle of contradictions blocked them.
        if len(result_chars) < len(in_degree):
            return ""
        return "".join(result_chars)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine finding a torn page from an alien dictionary: the words on the page are sorted, and you want to deduce the alien alphabet from those sorted words. Whenever two neighboring words share a common beginning and then differ at one position—like "wn" followed by "wg"—that first differing spot is a direct clue saying 'n' must come before 'g'. This rule is how lexicographical order works: strings are compared left to right at the first position where they differ, and if one string runs out of letters first, the shorter string comes earlier.

Trying every possible shuffling of the alphabet and checking whether the word list stays sorted is far too slow: with up to 26 letters, there are 26! (roughly 4 * 10^26) candidate orders. Even after extracting pairwise clues, using a standard first-in, first-out queue only produces some valid alphabet rather than the alphabetically smallest one when letters have no rules tying them down.

Instead, we model the clues as a directed graph (a network of nodes connected by one-way arrows u -> v meaning "u must come before v") and find a topological sort (a linear ordering of all nodes where every arrow points from left to right). We run Kahn's algorithm—a method that repeatedly places nodes whose in-degree (count of unmet prerequisites) is 0—backed by a min-heap (a priority queue data structure that always pops the smallest item in logarithmic time).

Walk through Example 1, words = ["wn", "wg"]:

  1. Register all unique letters ('w', 'n', 'g') with in_degree = 0.
  2. Compare "wn" and "wg": index 0 ties ('w' == 'w'), and index 1 differs ('n' != 'g'), adding the arrow 'n' -> 'g' and setting in_degree['g'] = 1.
  3. Push all in_degree == 0 letters into the min-heap: ['n', 'w'].
  4. Pop 'n' (smaller than 'w'), decrement in_degree['g'] to 0, and push 'g' so the heap becomes ['g', 'w'].
  5. Pop 'g', then pop 'w', yielding "ngw"—every arrow points forward, and "ngw" is the smallest possible valid string. If a cycle (a closed loop of arrows like 'a' -> 'b' -> 'a') existed, the trapped letters would never reach in_degree == 0, leaving the output shorter than the number of unique letters so we return "".

Complexity

Let n be the number of words, C be the total number of characters across all words, U be the number of unique characters (U <= 26 for lowercase English), and E be the number of distinct character rules (E <= min(n - 1, U * (U - 1))).

  • Time: O(C + U log U). Registering all unique characters reads every character once (O(C)). Comparing pair (words[i], words[i + 1]) scans at most len(words[i]) characters, so summing across all n - 1 adjacent pairs scans at most C characters in total. In Kahn's loop, each of the U unique characters is pushed onto and popped from the min-heap at most once (O(U log U)), and each of the E distinct edges decrements an in-degree once (O(E), which is at most O(C) because each non-empty word pair adds at most one edge). Since U <= 26 here, U log U is bounded by a small constant and the runtime scales linearly as O(C).
  • Space: O(U + E). The successors sets store U keys and E directed edges in total, while in_degree, available_heap, and result_chars each hold at most U characters.

Edge cases

  • Empty word list ([]): Zero unique characters exist, so the function returns "".
  • Single word or identical words (["banana"], ["cab", "cab"]): No mismatch ever occurs, so all unique characters have in_degree == 0 and the min-heap pops them in 'a'-to-'z' order ("abn", "abc").
  • Valid vs. invalid prefixes: "pla" before "plan" is valid and adds no rule; "plan" before "pla" (Example 3) cannot be sorted under any alphabet and immediately returns "".
  • Unconstrained letters (["wn", "wg"]): 'w' has no incoming or outgoing edges, yet registering all characters up front ensures 'w' is included and placed at its best spot ("ngw").
  • Cycles (both full and partial): Whether every letter is in the loop (["a", "b", "a"]) or some letters finish before a loop blocks the rest (["x", "ya", "yb", "ya"]), len(result_chars) < len(in_degree) detects the stuck nodes and returns "".
  • Duplicate rules (["mg", "mt", "gb", "gr", "tb", "br"]): 'g' -> 't' is discovered twice in Example 4, and the set check counts it once so 't' unlocks properly after 'g'.

Common mistakes

  • Continuing past the first mismatch: In ["abz", "acy"], position 1 ('b' vs 'c') already settles the word order; adding 'z' -> 'y' from position 2 invents a false constraint that can create bogus cycles or alter the output.
  • Skipping characters that never appear in an edge: Building nodes only when a mismatch occurs drops letters from single-word inputs or shared prefixes like 'w' in ["wn", "wg"].
  • Incrementing in_degree without checking for duplicate edges: If successors[u] is a set (removing the edge once) while in_degree[v] is incremented twice, in_degree[v] stays at 1 forever and falsely triggers cycle detection.
  • Using a FIFO queue or sorting only at the start: A FIFO queue ignores alphabetical order, and sorting only the initial zero-in-degree characters misses characters that unlock mid-run and are smaller than letters still waiting (like 'a' unlocking ahead of 'p' in Example 2).
  • Reversing the prefix check: Flagging "pla" before "plan" as invalid instead of "plan" before "pla" rejects normal dictionary order.

Alternative approaches

  • Depth-first search (DFS) with three-color cycle detection: Marking nodes unvisited, visiting, and visited finds a valid topological order and detects cycles in O(C + U + E) time, avoiding the heap's log U factor. However, standard post-order DFS cannot easily enforce the global lexicographically smallest tie-breaker when unrelated components interleave, making Kahn's algorithm with a min-heap much cleaner here.
  • Brute-force permutation search: Enumerating itertools.permutations(sorted(unique_chars)) and testing whether words is sorted guarantees the smallest order first, which makes an ideal reference check on tiny random tests (U <= 6), though O(U! * C) time is infeasible for larger alphabets.

Follow-up questions

  • What changes are needed if words may contain arbitrary Unicode characters or punctuation from an unbounded symbol set? Because successors and in_degree are hash maps keyed by character strings rather than fixed 26-slot arrays, the exact same code already handles arbitrary Unicode characters or symbols of any alphabet size U. Python's heapq compares single-character strings by their Unicode code point (ord(ch)), so tie-breaking automatically picks the smallest code point first; if a custom tie-breaking rank is required, push (custom_rank(ch), ch) tuples onto the heap instead.
  • How do the runtime and memory bounds scale with the combined string length C and the distinct symbol count U? The time complexity is O(C + U log U) and the space complexity is O(U + E), where C is the total character count across all words, U is the number of distinct characters, and E <= min(n - 1, U * (U - 1)) is the number of distinct edges. Scanning all words and comparing adjacent pairs takes O(C) work because each adjacent check inspects at most the length of the left word, while pushing and popping each of the U characters once in the min-heap adds O(U log U) (which ceases to be a tiny constant once U can grow as large as C).
  • Suppose the full target alphabet is known ahead of time, yet several of its characters never appear in words. How should they be placed? Any character that never appears in words has zero ordering constraints from the word list, so it can legally sit anywhere in the output. If the full target alphabet is passed in as a second parameter (for example alphabet: Set[str]), pre-populate every character from that set into successors and in_degree with 0 in Phase 1; the min-heap will then weave the missing letters into the earliest valid positions automatically. If the intended alphabet is completely unknown, you can only output the U observed characters and document that unseen symbols remain unconstrained.

Follow-up questions

Similar questions

More Rogo interview questions

All 2 Rogo questions →