168. Excel Sheet Column Title
easyConvert a positive integer to its Excel column title (1 -> A, 26 -> Z, 27 -> AA, 28 -> AB, ...). The inverse of problem 171 — and a classic place to slip up on bijective base-26 division.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example: A -> 1, B -> 2, C -> 3, ..., Z -> 26, AA -> 27, AB -> 28, ...
Constraints
1 <= columnNumber <= 2^31 - 1
Examples
Example 1
columnNumber = 1"A"Example 2
columnNumber = 28"AB"Example 3
columnNumber = 701"ZY"Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Like base-26 conversion, but bijective: A=1, ..., Z=26 and there's no zero digit. Standard mod-and-divide needs adjustment.
Hint 2
The trick: subtract 1 BEFORE each modulo. Then mod 26 gives 0..25 mapping to A..Z, and the resulting integer division correctly handles the carry.
Hint 3
Build the title right to left: while columnNumber > 0, columnNumber -= 1; digit = columnNumber % 26; append chr('A' + digit); columnNumber /= 26.
Hint 4
Reverse the built string at the end.
Solution approach
Reveal approach
Bijective base-26 conversion. Standard mod-and-divide produces 0..25 cleanly only after subtracting 1 first, because 'A' starts at 1 (no zero digit). Loop: while columnNumber > 0, decrement columnNumber by 1, then take digit = columnNumber % 26 and append chr('A' + digit) to a buffer, then columnNumber //= 26. After the loop reverse the buffer. The decrement compensates for the missing zero — for example 26 -> after -1 becomes 25 (Z), then 25 / 26 = 0 and the loop exits, correctly producing 'Z' instead of 'AZ'. O(log26 n) time, O(log26 n) space for the output buffer.
Complexity
- Time
- O(log n)
- Space
- O(log n)
Related patterns
- math
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Microsoft
- Amazon
- Apple
Practice these live with InterviewChamp.AI
Drill Excel Sheet Column Title and Math problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →