Spreadsheet Column Index to Letter Code

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Grid applications label columns alphabetically starting at position 1: positions 1 through 26 use single uppercase letters "A" through "Z", position 27 begins two-letter codes at "AA", "AB", ..., "AZ" (position 52), "BA" (position 53), and so on up to "ZZ" at position 702.

Implement column_label(n) to return the uppercase letter code corresponding to the 1-based column index n.

  • Every digit position chooses from the 26 letters "A".."Z" (1..26); no symbol represents zero, and index 0 does not exist.
  • Return only the uppercase letters for the column header, without any row coordinate.
def column_label(n: int) -> str:

Examples

Example 1

  • Input: n = 8
  • Output: "H"
  • Explanation: Index 8 falls within the first 26 columns and maps directly to the 8th letter of the alphabet, "H".

Example 2

  • Input: n = 52
  • Output: "AZ"
  • Explanation: Columns 1..26 occupy "A".."Z" and the next 26 columns (27..52) occupy "AA".."AZ", placing index 52 at "AZ".

Constraints

  • 1 <= n <= 702
  • n is always a valid int inside [1, 702] (out-of-bounds validation is not required).
  • Output consists solely of uppercase ASCII letters 'A'..'Z'.

Step-by-step walkthrough

  1. Understand the numbering pattern

    We are given a 1-based spreadsheet column index n (1 <= n <= 702) and must return its uppercase letter code (such as "H" or "AZ"), with no row coordinate attached.

    Look at how the labels progress across rollover boundaries:

    Column:    1    2  ...   25   26 |  27   28  ...   51   52 |  53  ...  701  702
    Label:     A    B  ...    Y    Z |  AA   AB  ...   AY   AZ |  BA  ...   ZY   ZZ
    

    At first glance this looks like converting n to base 26 using the 26 letters A..Z. The crucial twist is that there is no zero digit: A stands for 1 (not 0), and Z stands for 26. After single-letter Z (26) comes AA (26 * 1 + 1 = 27), and ZZ is 26 * 26 + 26 = 702.

  2. Why naive remainder-by-26 breaks at multiples of 26

    Suppose you try standard base conversion — taking n % 26 for the last digit and n // 26 for the next digit — on n = 26 (which should be "Z"):

    • 26 % 26 gives 0 instead of 25.
    • 26 // 26 gives 1 instead of 0, tricking the loop into running an extra round and producing a bogus two-letter string ("BA").

    Because n <= 702 is small, a brute-force helper could pre-build all 702 strings (A..Z followed by AA..ZZ) and index labels[n - 1]. Our test suite uses that list as a reference check, but in an interview it misses the core arithmetic and stops working at column 703 ("AAA"). Let us fix the math cleanly so one tiny loop works for any positive integer n.

  3. Key insight: subtract 1 before every remainder and division

    Write any column label's numeric value from its 1-based letter values (A = 1, B = 2, ..., Z = 26). If d (between 1 and 26) is the rightmost letter and prefix is the value of all letters to its left (prefix = 0 for a 1-letter label), then:

    n = 26 * prefix + d          (where d is in 1..26)
    

    Why did n % 26 and n // 26 fail when d = 26? Because modulo 26 expects a remainder in 0..25, so d = 26 wraps around to 0 and adds an unwanted +1 to the quotient prefix!

    Watch what happens when we subtract 1 from both sides first:

    n - 1 = 26 * prefix + (d - 1)    (where d - 1 is in 0..25!)
    

    Because d - 1 sits strictly inside 0..25, integer division and remainder by 26 now separate the two parts cleanly with zero special cases:

    • (n - 1) % 26 is always d - 1 (0 for 'A', 1 for 'B', ..., 25 for 'Z').
    • (n - 1) // 26 is always prefix (the exact 1-based column number of the remaining letters to the left, or 0 when no letters remain).
  4. Turn each 0..25 offset into an uppercase letter

    In Python, ord("A") returns the character code of 'A' (65), and chr(code) turns a character code back into a 1-character string:

    • letter_offset = 0 -> chr(ord("A") + 0) -> "A"
    • letter_offset = 25 -> chr(ord("A") + 25) -> "Z"

    Because each loop iteration peels off the rightmost letter first, we append characters into letters_right_to_left and call .reverse() once after n reaches 0:

    from typing import List
    
    
    def column_label(n: int) -> str:
        letters_right_to_left: List[str] = []
    
        while n > 0:
            # Shift 1..26 down to 0..25 before taking % 26 and // 26.
            n -= 1
            letter_offset = n % 26
            current_letter = chr(ord("A") + letter_offset)
            letters_right_to_left.append(current_letter)
            n //= 26
    
        letters_right_to_left.reverse()
        return "".join(letters_right_to_left)
    

    Notice that n -= 1 runs inside every iteration of the while loop, because every position (units, 26s, 26^2s, ...) is 1-based without a zero digit.

  5. Trace Example 1, Example 2, and rollover boundaries step by step

    Let us trace Example 1 (8 -> "H"), Example 2 (52 -> "AZ"), rollover 53 -> "BA", and upper limit 702 -> "ZZ":

    Input n = 8 (Example 1):
      Round 1: n -= 1 ->  7 |  7 % 26 =  7 ('H') |  7 // 26 = 0 -> stop
      letters_right_to_left = ['H'] -> reversed -> "H"
    
    Input n = 52 (Example 2):
      Round 1: n -= 1 -> 51 | 51 % 26 = 25 ('Z') | 51 // 26 = 1
      Round 2: n -= 1 ->  0 |  0 % 26 =  0 ('A') |  0 // 26 = 0 -> stop
      letters_right_to_left = ['Z', 'A'] -> reversed -> "AZ"
    
    Input n = 53:
      Round 1: n -= 1 -> 52 | 52 % 26 =  0 ('A') | 52 // 26 = 2
      Round 2: n -= 1 ->  1 |  1 % 26 =  1 ('B') |  1 // 26 = 0 -> stop
      letters_right_to_left = ['A', 'B'] -> reversed -> "BA"
    
    Input n = 702:
      Round 1: n -= 1 -> 701 | 701 % 26 = 25 ('Z') | 701 // 26 = 26
      Round 2: n -= 1 ->  25 |  25 % 26 = 25 ('Z') |  25 // 26 =  0 -> stop
      letters_right_to_left = ['Z', 'Z'] -> reversed -> "ZZ"
    

    Every rollover and multiple of 26 lands on the exact right letter without a single if branch.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def column_label(n: int) -> str:
        # letters_right_to_left: characters peeled from rightmost to leftmost, e.g. ['Z', 'A'] for column 52 ("AZ").
        letters_right_to_left: List[str] = []
    
        while n > 0:
            # Phase 1: Shift 1-based positions (1..26) down to 0-based offsets (0..25) BEFORE % and //.
            # Excel labels have no zero symbol ('A'=1 .. 'Z'=26); without n -= 1, multiples of 26 like n = 26
            # give remainder 0 and carry 1 ("BA") instead of offset 25 ('Z') and remaining quotient 0 ("Z").
            n -= 1
            letter_offset = n % 26
            current_letter = chr(ord("A") + letter_offset)
            letters_right_to_left.append(current_letter)
    
            # Phase 2: Advance to the remaining prefix to the left using the already-shifted value of n.
            n //= 26
    
        # Phase 3: Reverse once in O(k) time because modulo/division extracts the rightmost letter first.
        letters_right_to_left.reverse()
        return "".join(letters_right_to_left)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of an Excel column label like a car odometer whose wheels hold the 26 uppercase letters A through Z instead of the digits 0 through 9. Because there is no blank or zero slot on any wheel, A represents 1 and Z represents 26; clicking one step past Z (26) immediately rolls to AA (27). In math, this numbering system is called bijective base-26 — a positional number system with radix (base) 26 whose digit values are 1..26 instead of 0..25, giving a one-to-one match between positive integers and non-empty letter strings.

A naive base-26 loop computes n % 26 and n // 26 directly, assuming remainders run from 0 to 25. That breaks on every multiple of 26: for n = 26, 26 % 26 gives 0 and 26 // 26 carries 1 into the next place, producing "BA" instead of "Z". Writing separate if formulas for 1-letter and 2-letter columns works up to 702, but fails to generalize when spreadsheets reach column 703 ("AAA").

Subtracting 1 (n -= 1) at the start of every loop iteration shifts the rightmost letter's 1-based value (1..26) down to a clean 0-based offset (0..25). Then n % 26 gives the exact letter offset (0 -> 'A', ..., 25 -> 'Z', converted via Python's ASCII character helpers ord("A") and chr(...)), and integer quotient n // 26 gives the exact 1-based number for the remaining letters to the left.

Watch three representative values pass through the loop:

  • n = 8 (Example 1): subtract 1 -> 7; 7 % 26 = 7 ('H'), 7 // 26 = 0 -> stop -> "H".
  • n = 52 (Example 2): subtract 1 -> 51; 51 % 26 = 25 ('Z'), 51 // 26 = 1; next round subtract 1 -> 0 ('A'), 0 // 26 = 0 -> reverse ['Z', 'A'] -> "AZ".
  • n = 53: subtract 1 -> 52; 52 % 26 = 0 ('A'), 52 // 26 = 2; next round subtract 1 -> 1; 1 % 26 = 1 ('B'), 1 // 26 = 0 -> reverse ['A', 'B'] -> "BA".

Complexity

Let n be the 1-based column number (1 <= n <= 702 in this problem, and k = floor(log_26(25n + 1)) letters in general).

  • Time: O(log_26 n) (which is at most 2 loop iterations for 1 <= n <= 702, so effectively O(1) here), because each iteration performs constant-time arithmetic (-= 1, % 26, //= 26) and shrinks n by a factor of at least 26, followed by a single pass to reverse and join the O(log_26 n) characters.
  • Space: O(log_26 n) (at most 2 characters in letters_right_to_left for n <= 702) to store the output characters before joining them into a string.

Edge cases

  • Smallest valid column (n = 1): n -= 1 gives 0, emitting 'A' and stopping after 1 iteration ("A").
  • Multiples of 26 (26, 52, 676, 702): produce "Z", "AZ", "YZ", and "ZZ" cleanly because subtracting 1 turns remainder 0 into 25 ('Z') and prevents an extra carry of +1.
  • Rollover pairs (26 -> 27, 52 -> 53, 676 -> 677): transition smoothly from "Z" -> "AA", "AZ" -> "BA", and "YZ" -> "ZA".
  • Top of the stated range (n = 702): two iterations emit 'Z' then 'Z', returning "ZZ".

Common mistakes

  • Taking n % 26 before subtracting 1: causes every multiple of 26 (26, 52, 702) to emit 'A' (or '@') and carry 1 too much into the next position.
  • Subtracting 1 only once outside the while loop: fixes the rightmost character, but leaves all leftward positions off by 1 (n = 27 becomes 26, emitting 'A' and then 1 % 26 -> 'B' for "BA" instead of "AA").
  • Forgetting letters_right_to_left.reverse(): modulo and division extract the least-significant (rightmost) letter first, so skipping the reverse turns 28 ("AB") into "BA".
  • Prepending with result = current_letter + result inside the loop: copies the whole string on every step (O(k^2) character copies for k letters) instead of O(k) list append + reverse + "".join(...).

Alternative approaches

  • Direct 1-letter / 2-letter case split for 1..702: if n <= 26, return chr(ord("A") + n - 1); otherwise set k = n - 27 (0-based index among AA..ZZ) and return chr(ord("A") + k // 26) + chr(ord("A") + k % 26). Simple for n <= 702, but breaks at n = 703 ("AAA").
  • Recursive helper: return "" when n == 0, and column_label((n - 1) // 26) + chr(ord("A") + (n - 1) % 26) when n > 0. Uses the exact same arithmetic while letting the call stack build the characters left to right.

Follow-up questions

  • How would you implement the reverse mapping from a letter code such as "AZ" back to its 1-based column index 52? Scan the code from left to right starting with result = 0, and for each character ch update result = result * 26 + (ord(ch) - ord("A") + 1). No - 1 adjustment is needed in the reverse direction because each character directly contributes its 1-based digit value 1..26 ("AZ" -> (0 * 26 + 1) * 26 + 26 = 52, and "ZZ" -> 26 * 26 + 26 = 702).
  • Does this loop still work unchanged when n exceeds 702, such as 3-letter headers like "XFD" (16,384) or 64-bit integers? Yes, without changing a single line! Because the while n > 0: loop repeats n -= 1, n % 26, and n //= 26 until n reaches 0, it handles 3-letter (703 -> "AAA", 16384 -> "XFD") and arbitrarily long codes in O(log_26 n) time, whereas hardcoded 2-letter formulas or lookup tables stop at 702.
  • What checks would you add at the entry point if callers could supply zero, negative integers, or non-integer values? Raise a ValueError whenever not isinstance(n, int) or isinstance(n, bool) or n < 1 (remembering that bool is a subclass of int in Python, so isinstance(True, int) evaluates to True!). Without that guard, n = 0 would skip the while n > 0: loop and silently return "", while negative n would loop forever in Python because (-1) // 26 floors to -1.

Follow-up questions

Similar questions

More Houzz interview questions

All 1 Houzz questions →