AlgoInsight

DSA problem

Excel Sheet Column Title

EasyMaths / GeometryPattern: Maths / Geometrytop600AmazonMicrosoftGoogleFacebookApple

Given a positive integer columnNumber, return its corresponding column title as it would appear in an Excel sheet. The Excel labels start at A = 1, run up to Z = 26, then continue with two-letter labels AA = 27, AB = 28, and so on, all the way to ZZ, then AAA, etc.

This looks like a straightforward base-26 conversion, but there is a crucial twist: the alphabet A..Z represents 1..26, not 0..25. There is no digit zero in this numbering scheme. Treating the problem as ordinary base-26 produces wrong answers around multiples of 26 — for example, Z should map to 26, but pure base-26 would emit A0 instead.

The fix is a small but elegant pre-decrement: at every step, subtract 1 from the current number before taking the modulo. This shifts the range 1..26 down to 0..25 so it aligns with characters A..Z. After capturing the rightmost letter, divide by 26 and repeat until the number reaches zero.

Because each iteration produces exactly one character and divides the number by 26, the loop runs O(log₍₂₆₎ n) times, which is bounded by 7 for the constraint columnNumber ≤ 2^31 - 1. Memory usage is O(1) beyond the output string itself. The algorithm prepends each new character, or equivalently builds the result in reverse and then reverses it.

Examples

Example 1
Input: columnNumber = 1
Output: "A"
Explanation: The number 1 maps directly to the first letter of the alphabet, A.
Example 2
Input: columnNumber = 28
Output: "AB"
Explanation: 28 = 26 + 2, so it is the column right after Z. After the (n - 1) shift we read off B then A, giving "AB".
Example 3
Input: columnNumber = 701
Output: "ZY"
Explanation: 701 = 26 * 26 + 25. After the shift the inner step yields Y (25), then Z (26), producing "ZY".

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

mathstring

Browse all DSA problems