Excel Sheet Column Title: The Off-by-One Lesson Hidden in Base-26 Conversion
3 views
"Excel Sheet Column Title" asks you to convert a positive integer into a spreadsheet column label: 1 is A, 26 is Z, 27 is AA, 28 is AB, 702 is ZZ, and 703 is AAA. The reverse problem converts a label back into a number. Both look like simple base conversion, which is exactly why interviewers like them: most candidates write ordinary base-26 code first and get Z wrong.
Why ordinary base-26 fails
In normal base 26 there would be a digit for zero. Column labels have no zero: the digits run from 1 (A) to 26 (Z). This is sometimes called bijective base-26. If you compute n % 26 and map 0..25 to A..Z, then 26 gives remainder 0 and you either print a nonsense character or print "BA" for 52 instead of "AZ".
The fix in one line
Subtract one before taking the remainder:
while n > 0:
n -= 1
result.append(chr(ord('A') + n % 26))
n //= 26
return ''.join(reversed(result))
Shifting n down by one turns the 1..26 digit range into 0..25 for that step, so the remainder maps cleanly to a letter, and the integer division then moves to the next position. Trace 26: n becomes 25, the letter is Z, n becomes 0, done. Trace 27: n becomes 26, the letter is A, n becomes 1; then n becomes 0, the letter is A, done, giving AA. Doing two traces out loud like this is the fastest way to show the interviewer your code is right.
The reverse direction
Going from title to number is easier because there is no zero problem: result = result * 26 + (ord(c) - ord('A') + 1) for each character. Interviewers often ask for both directions and then check that converting there and back returns the original value for edge cases such as 1, 26, 27, 52, 702 and 703.
Complexity and follow-ups
Both directions run in O(log n) time, since each step divides by 26. Common follow-ups include: what is the largest column a 32-bit integer can represent, how would you handle lowercase input or invalid characters, and how would you generalize to an alphabet of k symbols (replace 26 with k). The general lesson is to ask whether a numbering system has a zero before reaching for a standard conversion routine.
How to present it
Say the zero-digit insight before you code, then write the loop, then trace 26 and 27. That sequence shows reasoning, not memorization, and it takes under ten minutes.
If you want help staying structured during a live coding round, Linkjob AI (https://linkjob.ai) gives real-time support during job interviews and technical interviews, so you can focus on explaining edge cases like these clearly.