Problem
Given a column title as appear in an Excel sheet, return its corresponding column number. For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
AAA -> 703
Examples
Example 1:
Input: columnTitle = "A"
Output: 1
Example 2:
Input: columnTitle = "AB"
Output: 28
Example 3:
Input: columnTitle = "ZY"
Output: 701
Similar problem
Excel Sheet Column Title Problem
Solution
Method 1 - Using Hashmap
Here is the approach:
- Create a HashMap: Map each character (‘A’ to ‘Z’) to its corresponding integer value (1 to 26).
- Initialize Result: Start with a result variable initialized to 0.
- Process Each Character: Iterate through each character of the input string from left to right.
- Calculate Value:
- Use the HashMap to get the numerical value of the character.
- Update the result using the formula for converting base-26 to base-10:
result = result * 26 + (character_value)
.
- Return Result: The final value of
result
after processing all characters is the column number.
Code
Java
class Solution {
public int titleToNumber(String columnTitle) {
HashMap<Character, Integer> charToValue = new HashMap<>();
// Create the mapping from 'A' to 'Z'
for (char ch = 'A'; ch <= 'Z'; ch++) {
charToValue.put(ch, ch - 'A' + 1);
}
int ans = 0;
for (int i = 0; i < columnTitle.length(); i++) {
ans = ans * 26 + charToValue.get(columnTitle.charAt(i));
}
return ans;
}
}
Python
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
char_to_value = {chr(i + ord('A')): i + 1 for i in range(26)}
ans: int = 0
for char in columnTitle:
ans = ans * 26 + char_to_value[char]
return ans
- ⏰ Time complexity:
O(n)
, wheren
is the length of the input string, as we process each character once, and HashMap lookups areO(1)
. - 🧺 Space complexity:
O(1)
, since the HashMap size is fixed with 26 entries regardless of the input size.
Method 2 - Simple multiplication by 26
Actually using a hashmap is not necessary here. Here is the approach:
- Initialize Result: Start with a result variable initialized to 0.
- Process Each Character: Iterate through each character of the input string from left to right.
- Calculate Value:
- Convert the character to its corresponding numerical value (e.g., ‘A’ to 1, ‘B’ to 2, etc.).
- Update the result using the formula for converting base-26 to base-10:
result = result * 26 + (character_value)
.
- Return Result: The final value of
result
after processing all characters is the column number.
Code
Java
class Solution {
public int titleToNumber(String columnTitle) {
int ans = 0;
for (int i = 0; i < columnTitle.length(); i++) {
ans = ans * 26 + (columnTitle.charAt(i) - 'A' + 1);
}
return ans;
}
}
Python
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
ans: int = 0
for char in columnTitle:
ans = ans * 26 + (ord(char) - ord('A') + 1)
return ans
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the input string, as we process each character once. - 🧺 Space complexity:
O(1)