Problem 171

Abstract / Summary

Convert an excel column title to its corresponding column number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
7 lines | 217 bytes | submitted September 5, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (1+ million submissions).

Typical patterns to solve this problem:
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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') + 1 translates 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 result at its initial value of 0.
  • Single-character titles - Multiplication by 26 occurs once, but since the initial result is 0, 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” becomes 27).
  • 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 result directly 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') + 1 converts 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 9.04 | σ = 0.79

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
55 links | 40 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Excel Sheet Column Number | LeetCode 171 | C++, Java, Python'
Knowledge Center 8 mins
Excel Sheet Column Number | LeetCode 171 | C++, Java, Python
YouTube video '171. Excel Sheet Column Number || Java || Leetcode || Hindi'
Coding Sphere 7 mins
171. Excel Sheet Column Number || Java || Leetcode || Hindi
YouTube video 'Excel Sheet Column Number | Day 10 | [ August LeetCoding Challenge ] [ Leetcode #171 ] [ 2020 ]'
Algorithms Made Easy 3 mins
Excel Sheet Column Number | Day 10 | [ August LeetCoding Challenge ] [ Leetcode #171 ] [ 2020 ]
YouTube video '171. Excel Sheet Column Number | Leetcode | Math based | Fundamentals'
Coding with Tamilarasan 7 mins
171. Excel Sheet Column Number | Leetcode | Math based | Fundamentals
YouTube video 'Microsoft Excel Sheet Column Number |. Leetcode August Challenge(Day 10) |  Leetcode 171'
Coding Decoded 5 mins
Microsoft Excel Sheet Column Number |. Leetcode August Challenge(Day 10) | Leetcode 171
YouTube video 'Excel sheet column number | Leetcode 171 | Java solution explained with intuition'
Joey'sTech 13 mins
Excel sheet column number | Leetcode 171 | Java solution explained with intuition
YouTube video 'Excel Sheet Column Number | LeetCode 171 | Coders Camp'
Coders Camp 6 mins
Excel Sheet Column Number | LeetCode 171 | Coders Camp
YouTube video 'Daily Leetcode #693: Feb 22, 2022 - 171. Excel Sheet Column Number'
Programming Live with Larry 7 mins
Daily Leetcode #693: Feb 22, 2022 - 171. Excel Sheet Column Number
YouTube video 'Excel Sheet Column Number | LeetCode 171 | Coders Camp'
Coders Camp 6 mins
Excel Sheet Column Number | LeetCode 171 | Coders Camp
YouTube video 'Daily Leetcode #132: Aug 10, 2020 - 171. Excel Sheet Column Number'
Programming Live with Larry 4 mins
Daily Leetcode #132: Aug 10, 2020 - 171. Excel Sheet Column Number
YouTube video '171. Excel Sheet Column Number || Leetcode Easy || Cpp'
Komal Pal 8 mins
171. Excel Sheet Column Number || Leetcode Easy || Cpp
YouTube video 'Leetcode | Easy  | 171. Excel Sheet Column Number | Time: O(n) | Javascript'
Software Interviews Prep 19 mins
Leetcode | Easy | 171. Excel Sheet Column Number | Time: O(n) | Javascript
YouTube video '171. Excel Sheet Column Number | Leetcode | Python'
Abdullah Arshed 4 mins
171. Excel Sheet Column Number | Leetcode | Python
YouTube video 'Day 125: LeetCode 171. Excel Sheet Column Number - Swift'
iOSxBank 9 mins
Day 125: LeetCode 171. Excel Sheet Column Number - Swift
YouTube video 'Decode Excel 🤯 Two MIND-BLOWING Approaches LeetCode 171. Excel Sheet Column Number'
vanAmsen 6 mins
Decode Excel 🤯 Two MIND-BLOWING Approaches LeetCode 171. Excel Sheet Column Number
YouTube video 'Excel Sheet Column Number | Leetcode 171 | Approach + Code with explanation.'
Pirai's Academy 6 mins
Excel Sheet Column Number | Leetcode 171 | Approach + Code with explanation.
YouTube video 'Excel Sheet Column Number - LeetCode 171 - Coding Interview Tutorial'
CodeLucky 4 mins
Excel Sheet Column Number - LeetCode 171 - Coding Interview Tutorial
YouTube video 'LeetCode 171 | Excel Sheet Column Number | Math | Java'
Sleepy Cracker 3 mins
LeetCode 171 | Excel Sheet Column Number | Math | Java
18 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 easy 6 medium
12 solutions   September 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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