Excel Sheet Column Number LeetCode Solution

Difficulty Level Easy
Frequently asked in Adobe Amazon Apple Bloomberg Facebook Goldman Sachs Google Microsoft Uber
ShopeeViews 1274

Problem Statement

Excel Sheet Column Number LeetCode Solution says that Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

Excel Sheet Column Number

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...

 

Example 1:

Input:

 columnTitle = "A"

Output:

 1

Example 2:

Input:

 columnTitle = "AB"

Output:

 28

Example 3:

Input:

 columnTitle = "ZY"

Output:

 701

 

Constraints:

  • 1 <= columnTitle.length <= 7
  • columnTitle consists only of uppercase English letters.
  • columnTitle is in the range ["A", "FXSHRXW"].

Approach

Idea

  1. This is a famous interview problem or you can say it’s a brain teaser. We will look into the detailed approach here.
  2. Essentially, what we are asked to do here is to convert a number in the base 26 numeral system to a decimal number. This is a standard algorithm, where we iterate over the digits from right to left and multiply them by the base to the power of the position of the digit.
  3. While iterating over the string we’ll store the present character value in a.
  4. Here A to Z represents by 1 to 26. No value starts with 0, that’s why we’re adding 1.
  5. Now in its multiply it with 26 and add a with it.
  6. A dry run is explained here. We could this process iteratively. Start by looking at the first digit “B”. Add the int equivalent of “B” to the running sum and continue. Every time we look at the following digit multiply our running sum by 26 adding the next digit to signify we are changing places. “B”=2, “BD”=2*26+4,”BCY”=(2*26+3)*26+25.
  7. Hence, we finally get the required column number.

 

Code

Excel Sheet Column Number C++ Solution:

class Solution {
public:
    int titleToNumber(string columnTitle) {
        int i,n=columnTitle.size();
        int ans=0;
        for(i=0;i<n;i++)
        {
            ans*=26;
            ans+=columnTitle[i]-'A'+1;
        }
        return ans;
    }
};

Excel Sheet Column Number Java Solution:

class Solution {
    public int titleToNumber(String columnTitle) {
        int i,n=columnTitle.length();
        int ans=0;
        for(i=0;i<n;i++)
        {
            ans*=26;
            ans+=columnTitle.charAt(i)-'A'+1;
            
        }
        return ans;
    }
}



Complexity Analysis of Excel Sheet Column Number LeetCode Solution

Time Complexity

Time complexity is O(N), N = size of the input string. We are traversing the string exactly one time hence the complexity is linear.

Space Complexity

Space complexity is O(1). We are not taking any extra space.

Translate »