Python 0171.py
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
result = 0
for c in columnTitle:
result *= 26
result += ord(c) - ord('A') + 1
return result
Difficulty
and has an acceptance rate of about 68% (1+ million submissions).
Typical patterns to solve this problem:
- Math
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation converts an Excel-style column title (a string consisting of capital letters A-Z) into its corresponding 1-based integer index. The algorithm treats the title as a representation in base-26 where ‘A’ maps to 1, ‘B’ to 2, …, ‘Z’ to 26. By iterating over the characters from left to right, the code builds the numeric value incrementally.
Initialization
The function begins by creating a variable to hold the cumulative result.
result = 0
This variable is set to zero before any characters are processed, establishing a clean starting point for the accumulation.
Iterative Accumulation
The core of the conversion occurs inside a for loop that visits each character c in the input string columnTitle.
for c in columnTitle:
result *= 26
result += ord(c) - ord('A') + 1
Two operations are performed for each character:
- Multiplication by 26 shifts the previously accumulated value one digit to the left in base-26, making room for the next digit.
- The expression
ord(c) - ord('A') + 1translates the current character into its numeric contribution (1-26) and adds it to the shifted result.
Because the loop processes characters in order, the most significant digit is handled first, mirroring the way humans read numbers.
Return Value
After all characters have been processed, the final integer is returned.
return result
If the input string is empty, the loop body never executes and the function returns 0, which is a sensible default for an undefined column title.
Edge Cases Handled
The algorithm gracefully manages several boundary conditions without additional checks:
- Empty string - The loop does not run, leaving
resultat its initial value of0. - Single-character titles - Multiplication by 26 occurs once, but since the initial
resultis0, the multiplication has no effect, and the character’s numeric value is added directly. - Titles with leading ‘A’s - Because ‘A’ contributes a value of
1, leading ‘A’s correctly influence the magnitude of the result (e.g., “AA” becomes27). - Maximum length titles - The loop scales linearly with the length of the string, and each iteration uses only constant-time arithmetic, so arbitrarily long titles are processed correctly as long as the resulting integer fits within Python’s arbitrary-precision integer type.
Performance Optimizations
The implementation exhibits several efficiency choices:
- In-place accumulation - By updating
resultdirectly rather than constructing intermediate strings or lists, the code minimizes memory allocations. - Avoidance of exponentiation - Instead of computing powers of 26 for each position, the algorithm uses a running multiplication, which is cheaper than repeated exponentiation.
- Direct ordinal conversion - The use of
ord(c) - ord('A') + 1converts a character to its numeric value with a single arithmetic operation, avoiding dictionary lookups or conditional branches. - Single pass - The function traverses the input exactly once, guaranteeing linear time relative to the length of the title and eliminating any need for back-tracking or multiple scans.
These choices combine to produce a solution that is both concise and performant for the intended conversion task.
ELI5 - Simplified Explanation
Imagine a game where you have a row of special blocks. Each block has a letter on it. This code is like a little machine that counts those letters to figure out their secret number value.
The machine starts with a count of zero. Then it looks at each letter one by one. For every letter it finds, the machine takes the number it already has and grows it twenty-six times bigger. This is like moving over one space on a giant scoreboard.
After making the number bigger, the machine looks at the letter to see which one it is. It turns the letter into a small number where A is one, B is two, and so on all the way to Z. It adds that small number to the big total. The machine keeps doing this until it reaches the end of the line of blocks. By the time it finishes, all the letters have been turned into a single big final number.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lennylxx | C | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| sonugiri1043 | C++ | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| XiaotaoGuo | C++ | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 168: Excel Sheet Column Title
Solved On The Same Day
- problem 168: Excel Sheet Column Title
- problem 506: Relative Ranks
- problem 561: Array Partition
- problem 628: Maximum Product of Three Numbers
- problem 908: Smallest Range I
- problem 306: Additive Number
- problem 307: Range Sum Query - Mutable
- problem 378: Kth Smallest Element in a Sorted Matrix
- problem 692: Top K Frequent Words
- problem 720: Longest Word in Dictionary
- problem 910: Smallest Range II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality