Excel Sheet | Part-2

Easy
0/40
Average time to solve is 15m
profile
Contributed by
219 upvotes
Asked in companies
IBMGoldman SachsLowe's

Problem statement

You are given a string STR representing the column title in an Excel Sheet. You need to find its corresponding column number.

For example: A corresponds to 1, B to 2, C to 3, … , Z to 26, AA to 27, .. and so on.

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains a single integer T, representing the number of test cases or queries to be run. 

Then the T test cases follow.

The first and only line of each test case contains a string STR denoting the column title. It is guaranteed that all the characters would be capital English alphabets.
Output Format:
For each test case, you need to return the corresponding excel column number of STR.

The output of each query must be printed in a new line.

Note:

You are not required to print the expected output, it has already been taken care of. Just implement the function.
Constraints:
1 ≤ T ≤ 50
1 ≤ |STR| ≤ 12

where 'T' denotes number of testcases, and |STR| denotes the length of the string.

Time Limit : 1 sec 
Sample Input 1:
3
A
AB
F
Sample Output 1:
1
28
6
Explanation of Input 1:
The first test case, STR = “A”. This corresponds to column number 1.

The second test case, STR = “AB”. This corresponds to column number 28.

The third test case, STR = “F”. This corresponds to column number 6.
Sample Input 2:
3
AZ
COD
ZZZ
Sample Output 2
52
2422
18278
Hint

Can you relate this to base conversion of numbers?

Approaches (1)
Optimal Solution
  • The solution to this problem is like base 26 number conversion. Why 26? Because the number of capital english alphabets is 26.
  • For example, while converting binary to decimal, we take base as 2 and then convert it to base 10. We would be doing the same thing here as well.
  • To find the conversion, we would traverse through the given string from left to right, while calculating the answer.
  • For every character, str[i] we would do the following: title = title*26 + (str[i] - ‘A’ + 1).
  • Finally we would return this answer.
Time Complexity

O(N), Where N is the size of the given string. 

 

This is because we would be traversing in the given string once.

Space Complexity

O(1)

 

Because in the worst case, we are using constant space.

Code Solution
(100% EXP penalty)
Excel Sheet | Part-2
Full screen
Console