# 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 26^{1} * 1 + 26^{0} * 2.

If you notice, this is equivalent of saying 26^{i} * 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:
`26`

^{i}+ 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.

### Recommended Posts

##### Water Flow | InterviewBit | Solution Explained

May 11, 2022