~/problems / Math & matrices

Excel Sheet Column Title

easy ~15 min

A spreadsheet names its columns A, B, ..., Z, then AA, AB, ..., AZ, BA, ..., ZZ, then AAA, AAB, ... and so on. Column 1 is A, column 26 is Z and column 27 is AA.

Write column_label(n) -> str that returns the label of column number n.

column_label(1)       # "A"
column_label(26)      # "Z"
column_label(28)      # "AB"
column_label(702)     # "ZZ"
column_label(703)     # "AAA"
  • 1 <= n <= 2^31 - 1.
  • Aim for O(log n) time.
Show hint

this looks like writing n in base 26, but there's no digit for zero: the letters stand for 1 to 26. Adjust n by one before taking each remainder.

Topic: Math and matrices. Digit-by-digit arithmetic, matrix rotation and in-place tricks.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc