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
uandv, find the earliest indexiwhereu[i] != v[i]. If such an index exists,uprecedesvwhenu[i]appears earlier thanv[i]in the character ranking. If no index differs up tomin(len(u), len(v)),umay precedevonly whenlen(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
wordslist returns"". Whenwordsimposes 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) <= 1001 <= len(words[i]) <= 100- Every
words[i]consists solely of lowercase English letters ('a'–'z').
Step-by-step walkthrough
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 inwords, arranged in an order that keepswordsvalidly 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
wordsis 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'.- Tie-breaker: When more than one valid alphabet exists, return the one that comes first in normal
Why brute force is too slow
A direct brute-force method collects the
Udistinct characters, generates allU!permutations in'a'-to-'z'order, and returns the first permutation under whichwordsis sorted.That works as a test check when
U <= 6, because6! = 720. However, lowercase English has up toU = 26letters, and26!is roughly4 * 10^26. Instead of guessing whole alphabets, we need to read the exact ordering rules out ofwordsand build the answer one character at a time.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:
- Stop at the first mismatch: Once position
posdiffers, later letters have zero effect on which word comes first. - 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"". - Adjacent pairs are enough: Dictionary order is transitive (if
word[0] <= word[1]andword[1] <= word[2], thenword[0] <= word[2]automatically). Satisfying every neighboring pair(words[i], words[i + 1])guarantees the entire list is sorted.
- Stop at the first mismatch: Once position
Model the rules as a dependency graph
Treat every unique character in
wordsas a node in a directed graph, and every rule "umust appear beforev" as a directed arrowu -> v. For each characterv, we also count its in-degree: how many distinct characters must appear beforev.- 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 emptyset()andin_degree = 0ensures no letter is forgotten. - Deduplicate edges: Two different word pairs might produce the same rule
'g' -> 't'(as in Example 4). Storingsuccessors[earlier_char]as asetensures we incrementin_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- Register every character first: A letter like
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 -> vpoints forward. Kahn's algorithm builds this order step by step:- Any character with
in_degree == 0has zero unmet prerequisites, so it is safe to place right now. - Once we place a character
current_char, its requirement on eachnext_charinsuccessors[current_char]is satisfied, so we subtract1fromin_degree[next_char]. Wheneverin_degree[next_char]hits0,next_charbecomes 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'havein_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 toin_degree == 0, solen(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)- Any character with
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_heapandin_degreeupdate 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! All4unique characters were placed (len(result_chars) == 4), so we join them into"kapd".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"]:
- Register all unique letters (
'w','n','g') within_degree = 0. - Compare
"wn"and"wg": index0ties ('w' == 'w'), and index1differs ('n' != 'g'), adding the arrow'n' -> 'g'and settingin_degree['g'] = 1. - Push all
in_degree == 0letters into the min-heap:['n', 'w']. - Pop
'n'(smaller than'w'), decrementin_degree['g']to0, and push'g'so the heap becomes['g', 'w']. - 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 reachin_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 mostlen(words[i])characters, so summing across alln - 1adjacent pairs scans at mostCcharacters in total. In Kahn's loop, each of theUunique characters is pushed onto and popped from the min-heap at most once (O(U log U)), and each of theEdistinct edges decrements an in-degree once (O(E), which is at mostO(C)because each non-empty word pair adds at most one edge). SinceU <= 26here,U log Uis bounded by a small constant and the runtime scales linearly asO(C). - Space:
O(U + E). Thesuccessorssets storeUkeys andEdirected edges in total, whilein_degree,available_heap, andresult_charseach hold at mostUcharacters.
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 havein_degree == 0and 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 thesetcheck counts it once so't'unlocks properly after'g'.
Common mistakes
- Continuing past the first mismatch: In
["abz", "acy"], position1('b'vs'c') already settles the word order; adding'z' -> 'y'from position2invents 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_degreewithout checking for duplicate edges: Ifsuccessors[u]is aset(removing the edge once) whilein_degree[v]is incremented twice,in_degree[v]stays at1forever 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'slog Ufactor. 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 whetherwordsis sorted guarantees the smallest order first, which makes an ideal reference check on tiny random tests (U <= 6), thoughO(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
successorsandin_degreeare 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 sizeU. Python'sheapqcompares 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 isO(U + E), whereCis the total character count across all words,Uis the number of distinct characters, andE <= min(n - 1, U * (U - 1))is the number of distinct edges. Scanning all words and comparing adjacent pairs takesO(C)work because each adjacent check inspects at most the length of the left word, while pushing and popping each of theUcharacters once in the min-heap addsO(U log U)(which ceases to be a tiny constant onceUcan grow as large asC). - 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
wordshas 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 examplealphabet: Set[str]), pre-populate every character from that set intosuccessorsandin_degreewith0in 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 theUobserved characters and document that unseen symbols remain unconstrained.
Follow-up questions
- What changes are needed if words may contain arbitrary Unicode characters or punctuation from an unbounded symbol set?
- How do the runtime and memory bounds scale with the combined string length C and the distinct symbol count U?
- Suppose the full target alphabet is known ahead of time, yet several of its characters never appear in words. How should they be placed?
Similar questions
- Context-Window Budgeting Middleware for Financial RAG
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One