Check Lexicographical Order With Custom Alphabet
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are given a sequence of lowercase strings words alongside a 26-character permutation order of 'a' through 'z' that defines a custom character collation from lowest rank (order[0]) to highest rank (order[25]). Implement:
def is_sorted(words: List[str], order: str) -> bool:
Return True if words is arranged in non-decreasing dictionary order under order (words[0] <= words[1] <= ... <= words[-1]), and False otherwise.
Two strings u and v satisfy u <= v under order according to standard dictionary rules:
- Scan positions
k = 0, 1, ...up tomin(len(u), len(v)) - 1. At the earliest indexkwhereu[k] != v[k],u <= vholds if and only ifu[k]precedesv[k]inorder. - If
uandvagree at every shared position, the shorter string comes first (len(u) <= len(v)), so strict prefixes precede longer extensions and identical strings satisfyu <= v. - Sequences containing
0or1strings have no out-of-order pairs and returnTrue.
Examples
Example 1
Input:
words = ["mint", "table", "alpha"]
order = "mtabcdefghijklnopqrsuvwxyz"
Output:
True
Walk-through: In order, 'm' has rank 0, 't' has rank 1, and 'a' has rank 2. Comparing first letters gives 'm' < 't' for ("mint", "table") and 't' < 'a' for ("table", "alpha"), so every neighbor pair is ordered.
Example 2
Input:
words = ["spark", "span", "pond"]
order = "spnrkabcdefghijlmoqtuvwxyz"
Output:
False
Walk-through: "spark" and "span" share "spa", then differ at index 3: 'r' (rank 3) versus 'n' (rank 2). Because 'r' ranks after 'n', "spark" should follow "span", so the list is not sorted.
Example 3
Input:
words = ["catalog", "cat"]
order = "abcdefghijklmnopqrstuvwxyz"
Output:
False
Walk-through: "cat" matches the first three letters of "catalog", and a longer string cannot appear before its own shorter prefix.
Example 4
Input:
words = ["cat", "catalog", "catalog"]
order = "abcdefghijklmnopqrstuvwxyz"
Output:
True
Walk-through: Shorter prefix "cat" precedes "catalog", and equal neighbors "catalog" and "catalog" satisfy non-decreasing order.
Constraints
0 <= len(words) <= 10001 <= len(words[i]) <= 1000len(order) == 26, containing each lowercase ASCII letter'a'–'z'once, and every character inwords[i]belongs to'a'–'z'.
Step-by-step walkthrough
Understand how dictionary order works with a custom alphabet
Normally, an English dictionary places
'a'first and'z'last. Here,orderdefines a 26-letter permutation whereorder[0]is the smallest character andorder[25]is the largest.Two strings
left_wordandright_wordare ordered using lexicographical order (dictionary order — scanning left to right, one character index at a time):- Walk both strings starting at index
0until reaching the earliest position where their characters differ. That single position settles everything: whichever letter comes earlier inorderis smaller, and all subsequent positions are ignored. - If no mismatch appears before the shorter string ends, one string is a prefix (an initial substring) of the other. Shorter prefixes always precede longer words (
"cat"precedes"catalog"), while equal strings ("catalog"and"catalog") are permitted because non-decreasing order meanswords[i] <= words[i + 1].
Rule 1 (earliest mismatch decides): order = "spnrkabcdefghijlmoqtuvwxyz" (note: 'n' is at index 2, 'r' is at index 3) left_word = "s p a r k" right_word = "s p a n" = = = ^ First mismatch: 'r' (rank 3) vs 'n' (rank 2) -> out of order! Rule 2 (prefix tie-breaker when shared letters match): left_word = "c a t a l o g" (length 7) right_word = "c a t" (length 3) = = = Shorter word ran out -> 7 <= 3 is False -> out of order!- Walk both strings starting at index
Why a rank lookup table and adjacent pairs are enough
A slow approach could sort a copy of
wordswith a custom comparator and compare it to the original list. Worse yet, callingorder.index(ch)inside every letter comparison would scan up to 26 letters repeatedly.Two observations let us validate the list in a single linear pass:
- Precompute a rank map. Record every character's position in
orderinside a hash map (a PythondictsupportingO(1)average-time key lookups). Comparing two characters reduces to comparing two integers:char_rank[left_char] < char_rank[right_char]. - Inspect only neighboring pairs. Dictionary order is transitive: whenever
words[0] <= words[1]andwords[1] <= words[2],words[0] <= words[2]follows automatically. Checking thelen(words) - 1adjacent pairs(words[i], words[i + 1])and stopping on the first failure suffices.
order = "mtabcdefghijklnopqrsuvwxyz" | | | | v v v v char_rank = {'m': 0, 't': 1, 'a': 2, 'b': 3, ..., 'z': 25}def _build_char_rank(order: str) -> Dict[str, int]: """Map each character in `order` to its 0-based priority index.""" # char_rank: dict mapping single-character str -> int priority, e.g. {'m': 0, 't': 1, ...} char_rank: Dict[str, int] = {} for index, ch in enumerate(order): char_rank[ch] = index return char_rank- Precompute a rank map. Record every character's position in
Write a helper to compare two words
Next, turn our two comparison rules directly into
_are_words_in_order(left_word, right_word, char_rank):- Step
posfrom0throughmin(len(left_word), len(right_word)) - 1so neither string index goes out of bounds. - At the very first
poswhereleft_word[pos] != right_word[pos], returnchar_rank[left_char] < char_rank[right_char]right away. Never continue past this index — later characters cannot override an earlier mismatch. - If the loop completes without finding a mismatch, every shared character matched. Returning
len(left_word) <= len(right_word)accepts both strict prefixes ("cat"before"catalog",3 <= 7) and equal neighbors ("catalog"before"catalog",7 <= 7), while rejecting"catalog"before"cat"(7 <= 3).
def _are_words_in_order(left_word: str, right_word: str, char_rank: Dict[str, int]) -> bool: """Return True if left_word <= right_word under the custom alphabet.""" # Phase 1: Walk both words side by side up to the end of the shorter word. shorter_len = min(len(left_word), len(right_word)) for pos in range(shorter_len): left_char = left_word[pos] right_char = right_word[pos] if left_char != right_char: # In dictionary order, the VERY FIRST differing character decides everything; # characters at later positions never override an earlier tie-breaker. return char_rank[left_char] < char_rank[right_char] # Phase 2: Every shared character matched, so one word is a prefix of the other # (or the two words are identical). Use <= so equal words count as non-decreasing, # while a longer word before its shorter prefix (like "catalog" before "cat") fails. return len(left_word) <= len(right_word)- Step
Scan every neighbor pair in the list
With
_build_char_rankand_are_words_in_orderready,is_sortedties everything together:- Construct
char_rankonce fromorder. - Step
ifrom0tolen(words) - 2and test(words[i], words[i + 1]). ReturnFalseimmediately if any pair fails. - If every neighbor pair passes (including lists of
0or1strings, whererange(len(words) - 1)is empty), returnTrue.
def is_sorted(words: List[str], order: str) -> bool: # Precompute O(1) character rank lookups once before scanning the word list. char_rank = _build_char_rank(order) # Because dictionary order is transitive (w0 <= w1 and w1 <= w2 implies w0 <= w2), # checking adjacent pairs is sufficient; lists of 0 or 1 word skip the loop and return True. for i in range(len(words) - 1): left_word = words[i] right_word = words[i + 1] if not _are_words_in_order(left_word, right_word, char_rank): return False return True- Construct
Trace the examples step by step
Let's trace Example 1 (
words = ["mint", "table", "alpha"],order = "mtabcdefghijklnopqrsuvwxyz") and Example 2 (words = ["spark", "span", "pond"],order = "spnrkabcdefghijlmoqtuvwxyz"):Example 1: char_rank: 'm' -> 0, 't' -> 1, 'a' -> 2, ... i = 0: compare "mint" and "table" pos = 0: 'm' != 't' -> char_rank['m'] (0) < char_rank['t'] (1) is True! i = 1: compare "table" and "alpha" pos = 0: 't' != 'a' -> char_rank['t'] (1) < char_rank['a'] (2) is True! All pairs passed -> return True. Example 2: char_rank: 's' -> 0, 'p' -> 1, 'n' -> 2, 'r' -> 3, 'k' -> 4, ... i = 0: compare "spark" and "span" pos = 0: 's' == 's' (continue) pos = 1: 'p' == 'p' (continue) pos = 2: 'a' == 'a' (continue) pos = 3: 'r' != 'n' -> char_rank['r'] (3) < char_rank['n'] (2) is False! Pair 0 failed -> return False immediately (pair 1 ("span", "pond") is skipped).Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def _build_char_rank(order: str) -> Dict[str, int]: """Map each character in `order` to its 0-based priority index.""" # char_rank: dict mapping single-character str -> int priority, e.g. {'m': 0, 't': 1, ...} char_rank: Dict[str, int] = {} for index, ch in enumerate(order): char_rank[ch] = index return char_rank def _are_words_in_order(left_word: str, right_word: str, char_rank: Dict[str, int]) -> bool: """Return True if left_word <= right_word under the custom alphabet.""" # Phase 1: Walk both words side by side up to the end of the shorter word. shorter_len = min(len(left_word), len(right_word)) for pos in range(shorter_len): left_char = left_word[pos] right_char = right_word[pos] if left_char != right_char: # In dictionary order, the VERY FIRST differing character decides everything; # characters at later positions never override an earlier tie-breaker. return char_rank[left_char] < char_rank[right_char] # Phase 2: Every shared character matched, so one word is a prefix of the other # (or the two words are identical). Use <= so equal words count as non-decreasing, # while a longer word before its shorter prefix (like "catalog" before "cat") fails. return len(left_word) <= len(right_word) def is_sorted(words: List[str], order: str) -> bool: # Precompute O(1) character rank lookups once before scanning the word list. char_rank = _build_char_rank(order) # Because dictionary order is transitive (w0 <= w1 and w1 <= w2 implies w0 <= w2), # checking adjacent pairs is sufficient; lists of 0 or 1 word skip the loop and return True. for i in range(len(words) - 1): left_word = words[i] right_word = words[i + 1] if not _are_words_in_order(left_word, right_word, char_rank): return False return True✅ Submit now — all tests should pass.
Intuition & how it works
Imagine proofreading a glossary from an alien language whose alphabet runs "m, t, a, b, c, ..." instead of "a, b, c, ...". Before inspecting any entries, you jot down a numbered key mapping each letter to its rank 0 through 25. Then you slide your finger down the page comparing each entry against the one right below it using lexicographical order — standard dictionary order, where two words are decided at their earliest differing letter, and a shorter prefix such as "cat" precedes a longer word such as "catalog". Storing that rank key inside a hash map — a key-value table (dict in Python) offering O(1) average lookup time — turns every character comparison into an instant integer check.
Why do simpler shortcuts fall short? Comparing strings with Python's built-in <= or sorted(words) fails because Python orders characters by standard ASCII code points ('a' < 'b' < ...) rather than order. Even with a custom sort key, sorting a copy performs O(W log W) word comparisons when W - 1 neighbor checks already suffice by transitivity (if word_0 <= word_1 and word_1 <= word_2, then word_0 <= word_2 holds automatically). Likewise, calling order.index(ch) inside the inner loop rescans up to 26 characters per check instead of reading a precomputed rank in O(1) time.
Walk through Example 2 with words = ["spark", "span", "pond"] and order = "spnrkabcdefghijlmoqtuvwxyz":
1. Build rank map from `order`:
char_rank = {'s': 0, 'p': 1, 'n': 2, 'r': 3, 'k': 4, 'a': 5, ...}
2. Check pair 0: left_word = "spark", right_word = "span"
- pos 0: 's' == 's'
- pos 1: 'p' == 'p'
- pos 2: 'a' == 'a'
- pos 3: 'r' != 'n' -> compare char_rank['r'] (3) < char_rank['n'] (2) -> False!
3. Stop immediately and return False ("pond" never needs to be inspected).
Complexity
Let N be the combined character count across all strings in words, W be the number of strings (len(words)), and A be the length of order (26 here).
- Time:
O(A + N)(orO(A + W + N)if empty strings were permitted). Buildingchar_rankscans theAcharacters oforderonce. Then each neighbor comparison(words[i], words[i + 1])steps through at mostmin(len(words[i]), len(words[i + 1])) <= len(words[i])positions and runs at most oneO(1)dictionary lookup at the first mismatch; summinglen(words[i])across allW - 1pairs never exceedsN(and with non-empty words,W <= N). - Space:
O(A).char_rankstoresAcharacter-to-rank entries (26entries here), while comparing pairs uses only integer indices without copying strings.
Edge cases
- Empty list
[]or single-word list["zebra"]: Zero neighbor pairs exist, so the loop skips cleanly and returnsTrue. - Equal adjacent strings (
["catalog", "catalog"]): Non-decreasing order means<=, not<, solen(left_word) <= len(right_word)returnsTrue. - Prefix pairs (
["catalog", "cat"]vs["cat", "catalog"]): Every shared character matches, so the length check rejects"catalog"before"cat"(7 <= 3isFalse) and accepts"cat"before"catalog"(3 <= 7isTrue). - Single repeated character (
["aaaa", "aaa"]): No character mismatch occurs, leaving lengths to settle the order. - Mismatch only on the final pair: Every neighbor pair down to
(words[-2], words[-1])is checked before returningTrue. - Long shared prefixes:
1000identical1000-letter strings scan all1000positions per pair, finishing in roughly10^6steps.
Common mistakes
- Using Python's
<or<=directly on strings:left_word <= right_worduses ASCII order (a..z) and ignoresorder. - Omitting the length fallback after the loop: Returning
Truewhenever no character mismatch is found wrongly accepts["catalog", "cat"]. - Using
<instead of<=on lengths: Returninglen(left_word) < len(right_word)wrongly rejects equal neighbors such as["cat", "cat"]. - Continuing past the earliest mismatch: Only the first differing index matters; inspecting later indices breaks valid pairs such as
["az", "ba"](undera..z) because'z' > 'a'at index1. - Calling
order.index(ch)inside the comparison loop: Linear scans costO(A)per lookup on larger character sets instead ofO(1).
Alternative approaches
- Remap to
a..zviastr.maketrans: Precomputetable = str.maketrans(order, "abcdefghijklmnopqrstuvwxyz"), translate adjacent words, and checkprev_mapped <= curr_mapped. This preservesO(A + N)time while delegating character scanning to C, usingO(max_word_length)auxiliary memory when keeping only the previous translated string. - Sort a copy with a key function (
words == sorted(words, key=...)): Concise to write, but performsO(W log W)comparisons and allocates key tuples for the entire list instead of stopping early inO(A + N)time.
Follow-up questions
- How should the checker behave if
orderspecifies priorities for only part of the character set, leaving some characters unlisted? Clarify the specification for unlisted characters with the interviewer first: should an unrecognized character raise aValueError, or rank after every listed character using its Unicode code point (ord(ch)) to break ties? Under strict validation, checkif ch not in char_rank: raise ValueError(...)while scanning; under fallback ordering, read ranks viachar_rank.get(ch, len(order) + ord(ch)). Never silently ignore unknown characters, because"a#"and"a"would become indistinguishable and violate prefix ordering. - How does the runtime scale with the combined character count
Nacross all strings and the alphabet lengthA? Runtime scales asO(A + N)withO(A)auxiliary space. Populatingchar_rankvisits each of theAcharacters inorderonce, and each adjacent check(words[i], words[i + 1])examines at mostlen(words[i])positions before either hitting a differing character or exhaustingwords[i]. Summinglen(words[i])acrossi = 0 .. len(words) - 2totals at mostNcharacter comparisons. - What optimizations help when validating huge word streams or running millions of checks against the same custom alphabet? When
orderremains constant across calls, buildchar_rank(or astr.maketranstable) once in an initializer rather than per call, and consumewordslazily from an iterator so memory staysO(max_word_length)and execution halts at the first inversion. To parallelize a massive array acrossPworker threads or machines, partitionwordsintoPcontiguous slices, validate each slice independently, and verify theP - 1boundary pairs(slice[k][-1], slice[k + 1][0]).
Follow-up questions
- How should the checker behave if `order` specifies priorities for only part of the character set, leaving some characters unlisted?
- How does the runtime scale with the combined character count `N` across all strings and the alphabet length `A`?
- What optimizations help when validating huge word streams or running millions of checks against the same custom alphabet?
Similar questions
- Snapshot Queries on a Versioned Array
- Concurrent Interview Scheduling and Availability API
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance