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 to min(len(u), len(v)) - 1. At the earliest index k where u[k] != v[k], u <= v holds if and only if u[k] precedes v[k] in order.
  • If u and v agree at every shared position, the shorter string comes first (len(u) <= len(v)), so strict prefixes precede longer extensions and identical strings satisfy u <= v.
  • Sequences containing 0 or 1 strings have no out-of-order pairs and return True.

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) <= 1000
  • 1 <= len(words[i]) <= 1000
  • len(order) == 26, containing each lowercase ASCII letter 'a'–'z' once, and every character in words[i] belongs to 'a'–'z'.

Step-by-step walkthrough

  1. Understand how dictionary order works with a custom alphabet

    Normally, an English dictionary places 'a' first and 'z' last. Here, order defines a 26-letter permutation where order[0] is the smallest character and order[25] is the largest.

    Two strings left_word and right_word are ordered using lexicographical order (dictionary order — scanning left to right, one character index at a time):

    1. Walk both strings starting at index 0 until reaching the earliest position where their characters differ. That single position settles everything: whichever letter comes earlier in order is smaller, and all subsequent positions are ignored.
    2. 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 means words[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!
    
  2. Why a rank lookup table and adjacent pairs are enough

    A slow approach could sort a copy of words with a custom comparator and compare it to the original list. Worse yet, calling order.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 order inside a hash map (a Python dict supporting O(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] and words[1] <= words[2], words[0] <= words[2] follows automatically. Checking the len(words) - 1 adjacent 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
    
  3. 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 pos from 0 through min(len(left_word), len(right_word)) - 1 so neither string index goes out of bounds.
    • At the very first pos where left_word[pos] != right_word[pos], return char_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)
    
  4. Scan every neighbor pair in the list

    With _build_char_rank and _are_words_in_order ready, is_sorted ties everything together:

    1. Construct char_rank once from order.
    2. Step i from 0 to len(words) - 2 and test (words[i], words[i + 1]). Return False immediately if any pair fails.
    3. If every neighbor pair passes (including lists of 0 or 1 strings, where range(len(words) - 1) is empty), return True.
    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
    
  5. 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).
    
  6. 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) (or O(A + W + N) if empty strings were permitted). Building char_rank scans the A characters of order once. Then each neighbor comparison (words[i], words[i + 1]) steps through at most min(len(words[i]), len(words[i + 1])) <= len(words[i]) positions and runs at most one O(1) dictionary lookup at the first mismatch; summing len(words[i]) across all W - 1 pairs never exceeds N (and with non-empty words, W <= N).
  • Space: O(A). char_rank stores A character-to-rank entries (26 entries 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 returns True.
  • Equal adjacent strings (["catalog", "catalog"]): Non-decreasing order means <=, not <, so len(left_word) <= len(right_word) returns True.
  • Prefix pairs (["catalog", "cat"] vs ["cat", "catalog"]): Every shared character matches, so the length check rejects "catalog" before "cat" (7 <= 3 is False) and accepts "cat" before "catalog" (3 <= 7 is True).
  • 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 returning True.
  • Long shared prefixes: 1000 identical 1000-letter strings scan all 1000 positions per pair, finishing in roughly 10^6 steps.

Common mistakes

  • Using Python's < or <= directly on strings: left_word <= right_word uses ASCII order (a..z) and ignores order.
  • Omitting the length fallback after the loop: Returning True whenever no character mismatch is found wrongly accepts ["catalog", "cat"].
  • Using < instead of <= on lengths: Returning len(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"] (under a..z) because 'z' > 'a' at index 1.
  • Calling order.index(ch) inside the comparison loop: Linear scans cost O(A) per lookup on larger character sets instead of O(1).

Alternative approaches

  • Remap to a..z via str.maketrans: Precompute table = str.maketrans(order, "abcdefghijklmnopqrstuvwxyz"), translate adjacent words, and check prev_mapped <= curr_mapped. This preserves O(A + N) time while delegating character scanning to C, using O(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 performs O(W log W) comparisons and allocates key tuples for the entire list instead of stopping early in O(A + N) time.

Follow-up questions

  • How should the checker behave if order specifies 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 a ValueError, or rank after every listed character using its Unicode code point (ord(ch)) to break ties? Under strict validation, check if ch not in char_rank: raise ValueError(...) while scanning; under fallback ordering, read ranks via char_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 N across all strings and the alphabet length A? Runtime scales as O(A + N) with O(A) auxiliary space. Populating char_rank visits each of the A characters in order once, and each adjacent check (words[i], words[i + 1]) examines at most len(words[i]) positions before either hitting a differing character or exhausting words[i]. Summing len(words[i]) across i = 0 .. len(words) - 2 totals at most N character comparisons.
  • What optimizations help when validating huge word streams or running millions of checks against the same custom alphabet? When order remains constant across calls, build char_rank (or a str.maketrans table) once in an initializer rather than per call, and consume words lazily from an iterator so memory stays O(max_word_length) and execution halts at the first inversion. To parallelize a massive array across P worker threads or machines, partition words into P contiguous slices, validate each slice independently, and verify the P - 1 boundary pairs (slice[k][-1], slice[k + 1][0]).

Follow-up questions

Similar questions

More Truefoundry interview questions

All 3 Truefoundry questions →