LeetCode #168 Easy

Excel Sheet Column Title

Excel Sheet Column Title is LeetCode 168 (Easy). Given a positive integer columnNumber, return the title that a spreadsheet shows for that column: 1 is "A", 26 is "Z", 27 is "AA", 28 is "AB".

  • columnNumber can be as large as 2³¹ − 1, whose title is "FXSHRXW".
Constraints
  • 1 <= columnNumber <= 2³¹ − 1
mathstring
Open on LeetCode ↗
02

Intuition

A column title is a number in base 26, but its digits run from 1 to 26 (A to Z) instead of 0 to 25. Normal base conversion takes n % 26 as the last digit, and that breaks here: column 26 is Z, yet 26 % 26 is 0.

Subtract 1 before each step. If the last letter is worth v (1 to 26) and the letters before it are worth q, then n = q × 26 + v. Taking 1 away gives n − 1 = q × 26 + (v − 1), and now v − 1 is a normal remainder from 0 to 25. So (n − 1) % 26 picks the letter, with 0 meaning A, and (n − 1) // 26 is exactly q, the number the remaining letters spell.

The loop finds letters from the right end first, so they are reversed at the end.

How to spot this pattern

Writing a number in a positional system whose digits start at 1, with no zero. The fix is always the same: subtract 1 before taking the remainder and the quotient.

03

Approach

Try it first

Before reading on, write out 26, 27 and 52 by hand, then check what n % 26 and n // 26 give for each. Aim for O(log n) time.

1

Subtract 1

At the start of each round set n -= 1. This moves the last letter's value from the range 1 to 26 down to 0 to 25, which is the range % 26 can produce.

2

Take the last letter

Append chr(ord('A') + n % 26). A remainder of 0 gives A and 25 gives Z, so every remainder maps to a real letter.

3

Divide to drop that letter

Set n //= 26, using the same decremented n. What is left is the number spelled by the letters still to the left, and the loop stops when it reaches 0.

4

Reverse and join

The letters were found from right to left, so reverse the list and join it. Building a list and reversing once is cheaper than adding each letter to the front of a string.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def convertToTitle(self, columnNumber: int) -> str:
▶3 letters = []
▶4 n = columnNumber
▶5 while n > 0:
▶6 n -= 1
▶7 letters.append(chr(ord("A") + n % 26))
▶8 n //= 26
▶9 return "".join(reversed(letters))
number left to convert701letters, in the order found701 needs 2 letters → 2 rounds
n701
lettersnone yet
Each round finds one letter, starting from the rightmost, and divides the number by 26. The dashed slots are the letters still to find.
number left to convert701701number−1=700shiftedletters, in the order foundround 1: 701 − 1 = 700
n700
The last letter is worth 1 to 26, but a remainder can only be 0 to 25. Taking 1 away first lines the two ranges up, so 0 will mean A and 25 will mean Z.
number left to convert701700shifted=26letters left×26+24lastletters, in the order foundsplit 700 into 26 × 26 + 24
n % 2624
n // 2626
Dividing by 26 separates the last letter from the rest. The remainder 24 is the last letter; the quotient 26 is the number that the letters to its left spell.
number left to convert2624remainder→Yletterletters, in the order foundYremainder 24 → Y, number left is 26
letterY
n26
Remainder 24 counts from A = 0, so it is Y. The number becomes 26, and the next round finds the letter to the left of Y.
number left to convert2626number−1=25shiftedletters, in the order foundYround 2: 26 − 1 = 25
n25
The last letter is worth 1 to 26, but a remainder can only be 0 to 25. Taking 1 away first lines the two ranges up, so 0 will mean A and 25 will mean Z.
number left to convert2625shifted=0letters left×26+25lastletters, in the order foundYsplit 25 into 0 × 26 + 25
n % 2625
n // 260
Dividing by 26 separates the last letter from the rest. The remainder 25 is the last letter; the quotient 0 is the number that the letters to its left spell. Without the subtraction this remainder would have been 0, which has no letter.
number left to convert025remainder→Zletterletters, in the order foundYZremainder 25 → Z, number left is 0
letterZ
n0
Remainder 25 counts from A = 0, so it is Z. The number becomes 0, so there are no letters left to find and the loop stops.
number left to convert0title, letters reversedZYreverse YZ → "ZY"
answer"ZY"
The first letter found, Y, is the rightmost one, so the list is read backwards. Column 701 is ZY.
05

Common pitfalls

Subtracting 1 for the letter but not for the division

✗ Wrong
letters.append(chr(ord("A") + (n - 1) % 26))
n //= 26
✓ Right
n -= 1
letters.append(chr(ord("A") + n % 26))
n //= 26

The letter comes out right, but the quotient is too big whenever the last letter is Z. For 26 the loop picks Z, then divides 26 by 26 and gets 1, adding a stray A: it returns "AZ" instead of "Z". For 52 it returns "BZ" instead of "AZ".

Returning the letters in the order they were found

✗ Wrong
return "".join(letters)
✓ Right
return "".join(reversed(letters))

The first letter found is the rightmost one. Single letters hide the bug, but 28 comes back as "BA" (column 53) instead of "AB".

06

Complexity

Time
O(log n)
Space
O(log n)
Each round divides n by 26, so there is one round per letter, at most 7 for a 32-bit input. The only storage is the letters of the answer.
07

Excel Sheet Column Title FAQ

Can it be written recursively?

Yes. The title of n is the title of (n − 1) // 26 followed by the letter for (n − 1) % 26, and the title of 0 is the empty string. The recursion builds the string left to right, so no reverse is needed, and its depth is at most 7.

How do I get the letters for a column number in Excel itself?

=SUBSTITUTE(ADDRESS(1, n, 4), "1", "") returns the column letters for n. ADDRESS builds a cell name such as AB1, and removing the row number leaves AB. It is a quick way to check your answers for large inputs.

How do I convert letters back into the number?

That is the reverse problem, Excel Sheet Column Number. It needs no correction step: read left to right and compute result × 26 + value with A = 1.