Excel Sheet Column Number — Solution in Python, Java & C++
Excel Sheet Column Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Excel Sheet Column Number is an easy coding problem on strings and math, asked in Amazon, Microsoft, Meta and Zoho interviews.
- Difficulty: Easy
- Topics: Strings, Math
- Asked at: Amazon, Microsoft, Meta, Zoho, Razorpay
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a string columnTitle that represents the column title as it appears in an Excel sheet, return its corresponding column number.
A -> 1
B -> 2
…
Z -> 26
AA -> 27
AB -> 28
…
Example 1
Input: columnTitle = "A"
Output: 1
Example 2
Input: columnTitle = "AB"
Output: 28
Explanation: 1 × 26 + 2.
Example 3
Input: columnTitle = "ZY"
Output: 701
Constraints
1 <= columnTitle.length <= 5columnTitle consists of uppercase English letters.
Hints for Excel Sheet Column Number
Hint 1
This is base 26, except the digits run 1…26 rather than 0…25 — there is no zero digit.
Hint 2
Fold left to right:
n = n * 26 + (ch - 'A' + 1).
How to solve Excel Sheet Column Number
Column titles are base-26 numerals whose digits run 1…26 instead of 0…25. Fold left to right with n = n * 26 + (ch - 'A' + 1).
Approach
- Start
n = 0. - For each character, compute its value
ch - 'A' + 1and setn = n * 26 + value. - Return
n.
Why it works
Horner's rule evaluates a positional numeral: each new digit shifts what has been read so far by one place (multiply by 26) and adds its own weight. The + 1 shift is the only difference from standard base 26, and it applies identically to every position.
Complexity
- Time —
O(len) - Space —
O(1)
Pitfalls
- Using
ch - 'A'without the+ 1makesAa zero digit, soAAwould collapse to0. - The maximum title fits comfortably in a 32-bit int; there is no overflow concern within the constraints.
Reference solution
Python
def titleToNumber(columnTitle: str) -> int:
n = 0
for ch in columnTitle:
n = n * 26 + (ord(ch) - ord('A') + 1)
return nJava
public static int titleToNumber(String columnTitle) {
int n = 0;
for (int i = 0; i < columnTitle.length(); i++) {
n = n * 26 + (columnTitle.charAt(i) - 'A' + 1);
}
return n;
}C++
int titleToNumber(string columnTitle) {
int n = 0;
for (size_t i = 0; i < columnTitle.size(); i++) {
n = n * 26 + (columnTitle[i] - 'A' + 1);
}
return n;
}JavaScript
var titleToNumber = function(columnTitle) {
let n = 0;
for (let i = 0; i < columnTitle.length; i++) {
n = n * 26 + (columnTitle.charCodeAt(i) - 64);
}
return n;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings