Practice Problem Link: Excel Column Number | Practice Problem
Please make sure to try solving the problem yourself before looking at the editorial.
Problem Statement
Given an excel column number, find the numerical column number.
Naive Approach
The naive approach will be to try all possible combinations of characters sequentially, and when the current string matches the target string, return its number in the queue.
Analysis
- Time Complexity: O(26n)
- Space Complexity: O(1)
Optimal Approach
We observe that here all the characters in the string lie between A to Z, ie 26 characters. So, calculating the column number is equivalent to calculating the value of the string in base 26, if the characters are numbered as A = 1, B = 2, …., Z = 26.
Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
Implementation
C++
int getColumnNumber(string excelColumnNumber) {
int powerOf26 = 1;
int result = 0;
reverse(excelColumnNumber.begin(), excelColumnNumber.end());
for(char c: excelColumnNumber) {
result += (c - 'A' + 1) * powerOf26;
powerOf26 *= 26;
}
return result;
}Java
class Solution {
int getColumnNumber(String excelColumnNumber) {
int powerOf26 = 1;
int result = 0;
for(int i = excelColumnNumber.length() - 1; i >= 0; i--) {
char c = excelColumnNumber.charAt(i);
result += (c - 'A' + 1) * powerOf26;
powerOf26 *= 26;
}
return result;
}
}