# Excel Sheet Column Number
**Difficulty:** EASY
[External](https://leetcode.com/problems/excel-sheet-column-number)
Canonical: https://scaleengineer.com/dsa/problems/excel-sheet-column-number
**Patterns:** [Math](https://scaleengineer.com/dsa/patterns/math)
**Data structures:** String
**Companies:** [Docusign](https://scaleengineer.com/companies/docusign), [Zoho](https://scaleengineer.com/companies/zoho), [razorpay](https://scaleengineer.com/companies/razorpay)
---
## Problem
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding 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"]`.

# Approaches
## Recursive Approach
This method solves the problem by defining it in terms of itself. The column number for a title like "ABC" can be seen as the column number for "AB" multiplied by 26, plus the value of 'C'. This forms a recursive relationship that can be implemented with a function that calls itself on a smaller version of the input string.
**Time:** O(N^2) · **Space:** O(N^2)
**Pros:** Provides a clear, declarative solution that directly models the mathematical recurrence relation.
**Cons:** Inefficient due to the overhead of recursive calls and repeated string manipulations (like `substring`).; Can lead to a `StackOverflowError` for very long strings, although not an issue with the problem's constraints.; Higher space complexity due to the recursion stack.
### Explanation
The core idea is to break down the problem. For a given `columnTitle`, we can separate the last character from the rest of the string (the prefix). The final number is `26 * (number for prefix) + (value of last character)`.

- The base case for the recursion is an empty string, which corresponds to the number 0.
- For any non-empty string, the function recursively calls itself with the prefix (the string without its last character) and uses the result to compute the final number.
- For example, `titleToNumber("ZY")` would be calculated as `titleToNumber("Z") * 26 + 25`. The call to `titleToNumber("Z")` would in turn be `titleToNumber("") * 26 + 26`. Since `titleToNumber("")` is 0, the result unfolds back to `(0 * 26 + 26) * 26 + 25 = 701`.

```java
class Solution {
    public int titleToNumber(String columnTitle) {
        // Base case: if the string is empty, its value is 0.
        if (columnTitle == null || columnTitle.isEmpty()) {
            return 0;
        }
        
        // Recursive step:
        // Get the prefix (all but the last character)
        String prefix = columnTitle.substring(0, columnTitle.length() - 1);
        // Get the last character
        char lastChar = columnTitle.charAt(columnTitle.length() - 1);
        
        // The value of the last character (A=1, B=2, ...)
        int lastCharValue = lastChar - 'A' + 1;
        
        // The recursive formula
        return titleToNumber(prefix) * 26 + lastCharValue;
    }
}
```
### Algorithm
- Define a function `titleToNumber(columnTitle)`.
- **Base Case:** If `columnTitle` is empty, return 0.
- **Recursive Step:**
    - a. Get the prefix of the string (all characters except the last).
    - b. Get the value of the last character (`lastChar - 'A' + 1`).
    - c. Return `titleToNumber(prefix) * 26 + value_of_last_char`.

## Iterative Left-to-Right Approach (Base-26 Conversion)
This is the most efficient approach. It interprets the Excel column title as a number represented in base-26. The letters 'A' through 'Z' correspond to digits 1 through 26. The algorithm iterates through the string from left to right, building the final number in a way that is analogous to converting a number string (like "123") to an integer.
**Time:** O(N) · **Space:** O(1)
**Pros:** Optimal time and space efficiency.; Simple, intuitive, and easy to implement without recursion overhead.
**Cons:** This approach has no significant drawbacks and is the standard solution for this type of problem.
### Explanation
We initialize a variable `result` to 0. Then, we scan the `columnTitle` string from left to right. For each character, we update the `result`. The update rule is `result = result * 26 + character_value`. This works because each time we move one position to the right in the string, the value of the preceding part is multiplied by the base (26).

Let's trace `columnTitle = "ZY"`:
1. Initialize `result = 0`.
2. Process 'Z':
    - Value of 'Z' is `'Z' - 'A' + 1 = 26`.
    - `result = result * 26 + 26` => `result = 0 * 26 + 26 = 26`.
3. Process 'Y':
    - Value of 'Y' is `'Y' - 'A' + 1 = 25`.
    - `result = result * 26 + 25` => `result = 26 * 26 + 25 = 676 + 25 = 701`.
4. After iterating through all characters, the final `result` is 701. This method is simple, fast, and uses minimal memory.

```java
class Solution {
    public int titleToNumber(String columnTitle) {
        int result = 0;
        for (int i = 0; i < columnTitle.length(); i++) {
            char c = columnTitle.charAt(i);
            // The value of the character (A=1, B=2, ...)
            int d = c - 'A' + 1;
            // Update result: shift previous result by base 26 and add new digit
            result = result * 26 + d;
        }
        return result;
    }
}
```
### Algorithm
- 1. Initialize an integer `result` to 0.
- 2. Iterate through the `columnTitle` string from left to right using a loop.
- 3. In each iteration, for the current character `c`:
    - a. Calculate its corresponding value: `d = c - 'A' + 1`.
    - b. Update the `result`: `result = result * 26 + d`.
- 4. After the loop completes, return the final `result`.

# Solutions
### CSharp

```csharp
public class Solution {
    public int TitleToNumber(string columnTitle) {
        int ans = 0;
        foreach(char c in columnTitle) {
            ans = ans * 26 + c - 'A' + 1;
        }
        return ans;
    }
}
```

### Java

```java
class Solution {
public
  int titleToNumber(String columnTitle) {
    int res = 0;
    for (char c : columnTitle.toCharArray()) {
      res = res * 26 + (c - 'A' + 1);
    }
    return res;
  }
}

```

### CPP

```cpp
class Solution {
public:
  int titleToNumber(string columnTitle) {
    int res = 0;
    for (char c : columnTitle) {
      res = res * 26 + (c - 'A' + 1);
    }
    return res;
  }
};

```

### Python

```python
class Solution:
    def titleToNumber(self, columnTitle: str) -> int: res = 0 for c in columnTitle: res = res * 26 + (ord(c) - ord('A') + 1) return res

```
