LeetCode #168 Easy

Excel Sheet Column Title

Convert a positive integer to its corresponding Excel column title.

mathstring
Open on LeetCode ↗
02

Intuition

💡

This looks like plain base-26 conversion - take mod 26, take the letter, divide by 26, repeat - but that breaks because Excel's scheme is 1-indexed: there is no digit for zero, A is 1 and Z is 26, not 0 and 25. If you take a plain mod 26 on a number like 26 itself, you get remainder 0, which maps to 'A' with a leftover that produces 'AZ' instead of the correct single letter 'Z'. The fix is to subtract 1 from the current value BEFORE taking the modulo at every step, which shifts the range from 1..26 down to 0..25 just long enough to pick the right letter, then divide by 26 as usual.

03

Approach

1

Subtract 1 before every modulo

At each step, decrement the current value by 1 first. This remaps the 1-indexed range 1..26 to the 0-indexed range 0..25, so a plain modulo now lines up with letter indices A=0..Z=25 correctly.

2

Extract the letter and shrink the value

Take the decremented value mod 26 to get a digit 0..25, convert it to a letter with chr(65 + digit), and prepend it to the result. Then divide the decremented value by 26 (integer division) to move to the next higher place.

3

Repeat until the value reaches zero

Continue the subtract-mod-divide cycle while the current value is still positive; each iteration peels off one more letter from the least significant end, building the title back to front.

04

Solution & live demo

python
1class Solution:
2 def convertToTitle(self, columnNumber: int) -> str:
3 result = []
4 n = columnNumber
5 while n > 0:
6 n -= 1
7 result.append(chr(65 + n % 26))
8 n //= 26
9 return ''.join(reversed(result))
05

Edge cases

columnNumber == 26

Subtracting 1 first gives 25, which mods to 25 -> 'Z', then divides to 0, stopping immediately - not 'AZ'.

columnNumber == 27

Subtract 1 to get 26; 26 % 26 = 0 -> 'A', then 26 // 26 = 1, one more round gives 'A' again for the tens place -> 'AA'.

columnNumber == 1

Subtract 1 to get 0; 0 % 26 = 0 -> 'A', divides to 0, loop ends -> 'A'.

large multi-letter values, e.g. 701

Multiple rounds of subtract-mod-divide each contribute one letter, correctly producing multi-character titles like 'ZY'.

06

Complexity

Time
O(log n)
Space
O(log n)
The number of letters grows logarithmically with columnNumber in base 26.