# Excel Column Number | InterviewBit | Solution Explained

Excel Column Number is a math problem on InterviewBit. I explain the solution using a simple approach. Problem Link.

This solution is the inverse of: Excel Column Title | InterviewBit | Solution Explained

## 0. Excel Column Number: Problem Discussion

### 0.0. IO Format

• input:
• a string of characters
• output:
• an integer, which is the equivalent of the input string
• constraints:
• characters given are capital English letters
• solution must be better than O(N) time and space each

### 0.1. Examples

The problem statement is weird, so let’s take a look at some examples.

• A -> 1
• B -> 2
• Z -> 26
• AA -> 27
• AZ -> 52

And so on.

## 1. Excel Column Number: Observations & Logic

### 1.0. Intuitions

Right away it is clear that we are dealing with characters that have different significances on each position.

For example, AB -> 28 since A = 1, but is at the position 1 – so we actually do 26 * 1 for A. Then, since B is at the position 0, we just add +2. This gives us the answer as 261 * 1 + 260 * 2.

If you notice, this is equivalent of saying 26i * val(X) where X is the character.

### 1.1. Formal Logic

• reverse the string: `AB -> BA`
• keep a track of the index: `i = 0 -> 1 -> 2 -> ...`
• find the value of a character: `val = ord(c) - ord('A') + 1`
• then finally add to total: `26i + val`

## 2. Excel Column Number: Implementation

### 2.0. Code

```class Solution:
def titleToNumber(self, A):
ans = 0
for i, c in enumerate(reversed(A)):
ans += (26**i) * (ord(c)-ord('A') + 1)
return ans
```

### 2.1. Complexity Analysis

• Time: `O(N)`, to iterate over all the elements in the string, where N is the length of the input string.
• Space: `O(N)`, since reversing the string in python creates a new copy of it, and thus takes O(N) space.
##### Tanishq Chaudhary Producing high-quality intuitive explanations of interview problems. Currently covering LeetCode and InterviewBit.

### Recommended Posts

##### Gas Station | InterviewBit | Solution Explained

June 13, 2022

##### Majority Element | InterviewBit | Solution Explained

June 13, 2022

##### Assign Mice to Holes | InterviewBit | Solution Explained

June 13, 2022

1. Srishti Chopra :July 23, 2022 at 11:29 am

2. Makarand :August 16, 2022 at 11:06 am
3. Gopal :November 14, 2022 at 5:53 pm