Table of Contents
Problem Statement
In this problem we are given a column title as appear in an Excel sheet, we have to return the column number that corresponds to that column title in Excel as shown below.
Example
#1
"AB"
28
#2
"ZY"
701
Approach
To find column number for a particular column title we can think of it like converting from one number system to another number system.
Like in decimal number we have characters 0 to 9 to represent any number in decimal. Similarly in column title the characters are from A to Z to represent any number. There are total of 26 symbols for each place, therefore we can think of a number in a system whose base is 26.
Now question becomes very simple. Like we convert any binary or hexa-decimal number to its decimal form, we have to convert this title string into a decimal number.
For example, if we want to find the decimal value of string “1337”, we can iteratively find the number by traversing the string from left to right as follows:
‘1’ = 1
’13’ = (1 x 10) + 3 = 13
‘133’ = (13 x 10) + 3 = 133
‘1337’ = (133 x 10) + 7 = 1337
Now in this problem as we are dealing with base-26 number system. Based on the same idea, we can just replace 10s with 26s and convert alphabets to numbers.
For a title “LEET”:
L = 12
E = (12 x 26) + 5 = 317
E = (317 x 26) + 5 = 8247
T = (8247 x 26) + 20 = 214442
Implementation
C++ Program for Excel Sheet Column Number Leetcode Solution
#include <bits/stdc++.h> using namespace std; int titleToNumber(string s) { int ans=0; for(auto c:s) { ans= ans*26 + (c-'A'+1); } return ans; } int main() { cout<<titleToNumber("AB") <<endl; return 0; }
28
Java Program for Excel Sheet Column Number Leetcode Solution
class Rextester{ public static int titleToNumber(String s) { int ans=0; for(char c:s.toCharArray()) { ans= ans*26 + (c-'A'+1); } return ans; } public static void main(String args[]) { System.out.println( titleToNumber("AB") ) ; } }
28
Complexity Analysis for Excel Sheet Column Number Leetcode Solution
Time Complexity
O(N) : Where N is the total number of characters in the input string. We iterated once along the characters, hence time complexity will be O(N).
Space Complexity
O(1) : We just used one integer variable for storing the result.