Excel Sheet Column Number
EasyPrompt
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnTitle = "A"
Output: 1Example 2:
Input: columnTitle = "AB"
Output: 28Example 3:
Input: columnTitle = "ZY"
Output: 701
Constraints:
1 <= columnTitle.length <= 7columnTitleconsists only of uppercase English letters.columnTitleis in the range["A", "FXSHRXW"].
Approaches
2 approaches with complexity analysis and trade-offs.
This method solves the problem by defining it in terms of itself. The column number for a title like "ABC" can be seen as the column number for "AB" multiplied by 26, plus the value of 'C'. This forms a recursive relationship that can be implemented with a function that calls itself on a smaller version of the input string.
Algorithm
- Define a function
titleToNumber(columnTitle). - Base Case: If
columnTitleis empty, return 0. - Recursive Step:
- a. Get the prefix of the string (all characters except the last).
- b. Get the value of the last character (
lastChar - 'A' + 1). - c. Return
titleToNumber(prefix) * 26 + value_of_last_char.
Walkthrough
The core idea is to break down the problem. For a given columnTitle, we can separate the last character from the rest of the string (the prefix). The final number is 26 * (number for prefix) + (value of last character).
- The base case for the recursion is an empty string, which corresponds to the number 0.
- For any non-empty string, the function recursively calls itself with the prefix (the string without its last character) and uses the result to compute the final number.
- For example,
titleToNumber("ZY")would be calculated astitleToNumber("Z") * 26 + 25. The call totitleToNumber("Z")would in turn betitleToNumber("") * 26 + 26. SincetitleToNumber("")is 0, the result unfolds back to(0 * 26 + 26) * 26 + 25 = 701.
class Solution { public int titleToNumber(String columnTitle) { // Base case: if the string is empty, its value is 0. if (columnTitle == null || columnTitle.isEmpty()) { return 0; } // Recursive step: // Get the prefix (all but the last character) String prefix = columnTitle.substring(0, columnTitle.length() - 1); // Get the last character char lastChar = columnTitle.charAt(columnTitle.length() - 1); // The value of the last character (A=1, B=2, ...) int lastCharValue = lastChar - 'A' + 1; // The recursive formula return titleToNumber(prefix) * 26 + lastCharValue; }}Complexity
Time
O(N^2)
Space
O(N^2)
Trade-offs
Pros
Provides a clear, declarative solution that directly models the mathematical recurrence relation.
Cons
Inefficient due to the overhead of recursive calls and repeated string manipulations (like
substring).Can lead to a
StackOverflowErrorfor very long strings, although not an issue with the problem's constraints.Higher space complexity due to the recursion stack.
This is the most efficient approach. It interprets the Excel column title as a number represented in base-26. The letters 'A' through 'Z' correspond to digits 1 through 26. The algorithm iterates through the string from left to right, building the final number in a way that is analogous to converting a number string (like "123") to an integer.
Algorithm
-
- Initialize an integer
resultto 0.
- Initialize an integer
-
- Iterate through the
columnTitlestring from left to right using a loop.
- Iterate through the
-
- In each iteration, for the current character
c:
- a. Calculate its corresponding value:
d = c - 'A' + 1. - b. Update the
result:result = result * 26 + d.
- In each iteration, for the current character
-
- After the loop completes, return the final
result.
- After the loop completes, return the final
Walkthrough
We initialize a variable result to 0. Then, we scan the columnTitle string from left to right. For each character, we update the result. The update rule is result = result * 26 + character_value. This works because each time we move one position to the right in the string, the value of the preceding part is multiplied by the base (26).
Let's trace columnTitle = "ZY":
- Initialize
result = 0. - Process 'Z':
- Value of 'Z' is
'Z' - 'A' + 1 = 26. result = result * 26 + 26=>result = 0 * 26 + 26 = 26.
- Value of 'Z' is
- Process 'Y':
- Value of 'Y' is
'Y' - 'A' + 1 = 25. result = result * 26 + 25=>result = 26 * 26 + 25 = 676 + 25 = 701.
- Value of 'Y' is
- After iterating through all characters, the final
resultis 701. This method is simple, fast, and uses minimal memory.
class Solution { public int titleToNumber(String columnTitle) { int result = 0; for (int i = 0; i < columnTitle.length(); i++) { char c = columnTitle.charAt(i); // The value of the character (A=1, B=2, ...) int d = c - 'A' + 1; // Update result: shift previous result by base 26 and add new digit result = result * 26 + d; } return result; }}Complexity
Time
O(N)
Space
O(1)
Trade-offs
Pros
Optimal time and space efficiency.
Simple, intuitive, and easy to implement without recursion overhead.
Cons
This approach has no significant drawbacks and is the standard solution for this type of problem.
Solutions
Solution
public class Solution { public int TitleToNumber(string columnTitle) { int ans = 0; foreach(char c in columnTitle) { ans = ans * 26 + c - 'A' + 1; } return ans; }}class Solution {public int titleToNumber(String columnTitle) { int res = 0; for (char c : columnTitle.toCharArray()) { res = res * 26 + (c - 'A' + 1); } return res; }}class Solution {public: int titleToNumber(string columnTitle) { int res = 0; for (char c : columnTitle) { res = res * 26 + (c - 'A' + 1); } return res; }};class Solution: def titleToNumber(self, columnTitle: str) -> int: res = 0 for c in columnTitle: res = res * 26 + (ord(c) - ord('A') + 1) return resVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.