LeetCode #171 Easy

Excel Sheet Column Number

Convert an Excel column title to its corresponding integer column number.

mathstring
Open on LeetCode ↗
02

Intuition

💡

This is the mirror image of converting the other direction, and the trap mirrors it too: the instinctive ord(c) - ord('A') gives A a value of 0, matching plain base-26 digit indexing - but in this scheme A must be worth 1, not 0. Skip that +1 and every column number comes out too small, silently, for every single input. The fix is to add 1 after taking the offset, so ord(c) - ord('A') + 1 gives each letter its true place value, then fold the letters left to right with result = result * 26 + value, which is standard positional-number accumulation once the per-digit values are correct.

03

Approach

1

Compute each letter's true value

For each character in the title, take its offset from 'A' using ord(c) - ord('A'), then add 1 so that A maps to 1 and Z maps to 26 - matching the 1-indexed scheme instead of treating A as a zero digit.

2

Accumulate left to right

Walk the string from the first character to the last, updating result = result * 26 + value at each step. This is the same left-to-right accumulation used for any positional number system, once each digit's value is correct.

3

Return the accumulated result

After processing every character, the accumulator holds the exact column number - no separate power-of-26 lookup is needed because multiplying by 26 at each step already shifts prior digits into the right place.

04

Solution & live demo

python
1class Solution:
2 def titleToNumber(self, columnTitle: str) -> int:
3 result = 0
4 for ch in columnTitle:
5 value = ord(ch) - ord('A') + 1
6 result = result * 26 + value
7 return result
05

Edge cases

columnTitle == 'A'

Single letter, value = 0 + 1 = 1, result = 0*26 + 1 = 1.

columnTitle == 'Z'

Single letter, value = 25 + 1 = 26, result = 26 - the boundary case that plain base-26 (without +1) would get wrong.

columnTitle == 'AA'

First letter gives result = 1, second letter gives result = 1*26 + 1 = 27, correctly distinct from 'Z' = 26.

long titles near the integer limit

The same left-to-right multiply-and-add loop scales to any length without special-casing, bounded only by input size.

06

Complexity

Time
O(n)
Space
O(1)
n is the length of the column title; one pass with constant extra space.