Skip to main content

168. Excel Sheet Column Title

easy

Convert 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 Sam K., 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

Input
columnNumber = 1
Output
"A"

Example 2

Input
columnNumber = 28
Output
"AB"

Example 3

Input
columnNumber = 701
Output
"ZY"

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

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

More Math practice problems

See all Math problems →