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
26letters"A".."Z"(1..26); no symbol represents zero, and index0does 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
8falls within the first26columns and maps directly to the 8th letter of the alphabet,"H".
Example 2
- Input:
n = 52 - Output:
"AZ" - Explanation: Columns
1..26occupy"A".."Z"and the next26columns (27..52) occupy"AA".."AZ", placing index52at"AZ".
Constraints
1 <= n <= 702nis always a validintinside[1, 702](out-of-bounds validation is not required).- Output consists solely of uppercase ASCII letters
'A'..'Z'.
Step-by-step walkthrough
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 ZZAt first glance this looks like converting
nto base 26 using the 26 lettersA..Z. The crucial twist is that there is no zero digit:Astands for1(not0), andZstands for26. After single-letterZ(26) comesAA(26 * 1 + 1 = 27), andZZis26 * 26 + 26 = 702.Why naive remainder-by-26 breaks at multiples of 26
Suppose you try standard base conversion — taking
n % 26for the last digit andn // 26for the next digit — onn = 26(which should be"Z"):26 % 26gives0instead of25.26 // 26gives1instead of0, tricking the loop into running an extra round and producing a bogus two-letter string ("BA").
Because
n <= 702is small, a brute-force helper could pre-build all 702 strings (A..Zfollowed byAA..ZZ) and indexlabels[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 column703("AAA"). Let us fix the math cleanly so one tiny loop works for any positive integern.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). Ifd(between1and26) is the rightmost letter andprefixis the value of all letters to its left (prefix = 0for a 1-letter label), then:n = 26 * prefix + d (where d is in 1..26)Why did
n % 26andn // 26fail whend = 26? Because modulo26expects a remainder in0..25, sod = 26wraps around to0and adds an unwanted+1to the quotientprefix!Watch what happens when we subtract
1from both sides first:n - 1 = 26 * prefix + (d - 1) (where d - 1 is in 0..25!)Because
d - 1sits strictly inside0..25, integer division and remainder by26now separate the two parts cleanly with zero special cases:(n - 1) % 26is alwaysd - 1(0for'A',1for'B', ...,25for'Z').(n - 1) // 26is alwaysprefix(the exact 1-based column number of the remaining letters to the left, or0when no letters remain).
Turn each 0..25 offset into an uppercase letter
In Python,
ord("A")returns the character code of'A'(65), andchr(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_leftand call.reverse()once afternreaches0: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 -= 1runs inside every iteration of thewhileloop, because every position (units,26s,26^2s, ...) is 1-based without a zero digit.Trace Example 1, Example 2, and rollover boundaries step by step
Let us trace Example 1 (
8 -> "H"), Example 2 (52 -> "AZ"), rollover53 -> "BA", and upper limit702 -> "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
ifbranch.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): subtract1->7;7 % 26 = 7('H'),7 // 26 = 0-> stop ->"H".n = 52(Example 2): subtract1->51;51 % 26 = 25('Z'),51 // 26 = 1; next round subtract1->0('A'),0 // 26 = 0-> reverse['Z', 'A']->"AZ".n = 53: subtract1->52;52 % 26 = 0('A'),52 // 26 = 2; next round subtract1->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 for1 <= n <= 702, so effectivelyO(1)here), because each iteration performs constant-time arithmetic (-= 1,% 26,//= 26) and shrinksnby a factor of at least 26, followed by a single pass to reverse and join theO(log_26 n)characters. - Space:
O(log_26 n)(at most 2 characters inletters_right_to_leftforn <= 702) to store the output characters before joining them into a string.
Edge cases
- Smallest valid column (
n = 1):n -= 1gives0, emitting'A'and stopping after 1 iteration ("A"). - Multiples of 26 (
26,52,676,702): produce"Z","AZ","YZ", and"ZZ"cleanly because subtracting1turns remainder0into25('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 % 26before subtracting1: causes every multiple of 26 (26,52,702) to emit'A'(or'@') and carry1too much into the next position. - Subtracting
1only once outside thewhileloop: fixes the rightmost character, but leaves all leftward positions off by 1 (n = 27becomes26, emitting'A'and then1 % 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 turns28("AB") into"BA". - Prepending with
result = current_letter + resultinside the loop: copies the whole string on every step (O(k^2)character copies forkletters) instead ofO(k)list append + reverse +"".join(...).
Alternative approaches
- Direct 1-letter / 2-letter case split for
1..702: ifn <= 26, returnchr(ord("A") + n - 1); otherwise setk = n - 27(0-based index amongAA..ZZ) and returnchr(ord("A") + k // 26) + chr(ord("A") + k % 26). Simple forn <= 702, but breaks atn = 703("AAA"). - Recursive helper: return
""whenn == 0, andcolumn_label((n - 1) // 26) + chr(ord("A") + (n - 1) % 26)whenn > 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 characterchupdateresult = result * 26 + (ord(ch) - ord("A") + 1). No- 1adjustment is needed in the reverse direction because each character directly contributes its 1-based digit value1..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 repeatsn -= 1,n % 26, andn //= 26untilnreaches0, it handles 3-letter (703 -> "AAA",16384 -> "XFD") and arbitrarily long codes inO(log_26 n)time, whereas hardcoded 2-letter formulas or lookup tables stop at702. - What checks would you add at the entry point if callers could supply zero, negative integers, or non-integer values? Raise a
ValueErrorwhenevernot isinstance(n, int) or isinstance(n, bool) or n < 1(remembering thatboolis a subclass ofintin Python, soisinstance(True, int)evaluates toTrue!). Without that guard,n = 0would skip thewhile n > 0:loop and silently return"", while negativenwould loop forever in Python because(-1) // 26floors to-1.
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?
- Does this loop still work unchanged when n exceeds 702, such as 3-letter headers like "XFD" (16,384) or 64-bit integers?
- What checks would you add at the entry point if callers could supply zero, negative integers, or non-integer values?
Similar questions
- 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
- Increment Digit Array