Excel Sheet Column Title
Easy · Math · Math · String
Problem
Spreadsheet columns are labeled A to Z for columns 1 to 26, then AA (27), AB (28), ..., AZ, BA, ..., ZZ (702), AAA (703), and so on.
There is no letter for zero: A stands for 1 and Z for 26 in every position. This is bijective base 26, not ordinary base 26.
Given a positive integer columnNumber, return the label of that column.
Examples
Input: columnNumber = 26 Output: "Z"
26 is Z, the last one-letter column.
Input: columnNumber = 53 Output: "BA"
Columns 27..52 are AA..AZ, so 53 starts the B group: BA.
Input: columnNumber = 1000 Output: "ALL"
1000 - 1 = 999 gives last letter L (999 % 26 = 11); 999 // 26 = 38, and 38 - 1 = 37 gives L again (37 % 26 = 11); 37 // 26 = 1, and 1 - 1 = 0 gives A. Reversed: ALL.
Constraints
- 1 <= columnNumber <= 2^31 - 1
Approaches
- Count up one column at a time — time O(n log n), space O(log n)
Follow-up
The reverse conversion reads the label left to right: n = n * 26 + (letter - 'A' + 1). The same subtract-one trick turns any bijective numeral system into ordinary base k, for any alphabet size.
Related problems
Start free on Cariara · Coding problems · System design studio