Facebook Pixel

171. Excel Sheet Column Number

Problem Description

This problem asks you to convert an Excel column title (given as a string) into its corresponding column number.

In Excel, columns are labeled using letters from A to Z, where:

  • A corresponds to column 1
  • B corresponds to column 2
  • C corresponds to column 3
  • ... and so on until
  • Z corresponds to column 26

After Z, the labeling continues with two letters:

  • AA corresponds to column 27
  • AB corresponds to column 28
  • AC corresponds to column 29
  • ... and this pattern continues

The task is to take a column title string (like "A", "AB", or "ZY") and return the integer value representing that column's position.

This is essentially a base-26 number system where each letter represents a digit. The key difference from a standard base-26 system is that there's no zero - the "digits" go from 1 to 26 (A to Z) instead of 0 to 25.

For example:

  • "A" = 1
  • "Z" = 26
  • "AA" = 27 (which is 1 × 26 + 1)
  • "AB" = 28 (which is 1 × 26 + 2)
  • "AZ" = 52 (which is 1 × 26 + 26)
  • "BA" = 53 (which is 2 × 26 + 1)

The solution iterates through each character from left to right, treating it like a base-26 number where A=1, B=2, ..., Z=26. For each character, it multiplies the running total by 26 (to shift previous digits left) and adds the current character's value.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

When we look at how Excel column titles work, we can recognize a pattern similar to how we write numbers in different bases. Think about how we write numbers in decimal (base-10): the number 123 means 1×10² + 2×10¹ + 3×10⁰.

Excel column titles follow a similar pattern but with letters instead of digits and base-26 instead of base-10. For a column title like "AB":

  • The first letter A is in the "26s place" (like the tens place in decimal)
  • The second letter B is in the "ones place"

So "AB" would be A×26 + B, where A=1 and B=2, giving us 1×26 + 2 = 28.

The key insight is that each letter position represents a power of 26, just like each digit position in a decimal number represents a power of 10. Moving from right to left, each position has 26 times more weight than the previous one.

However, there's a subtle difference from standard base conversion: in Excel columns, there's no "0" digit. The letters go from A=1 to Z=26, not from 0 to 25. This is why we add 1 when converting each letter (c - ord("A") + 1).

To process the string efficiently, we can iterate from left to right, multiplying our running total by 26 each time we move to the next character (shifting our previous value to a higher power of 26), then adding the current character's value. This is exactly how we might convert a string like "123" to the integer 123: start with 0, then for each digit, multiply the current result by 10 and add the new digit.

The formula ans = ans * 26 + current_letter_value elegantly captures this base conversion process, building up the final column number one letter at a time.

Solution Approach

The solution implements a base-26 conversion algorithm with a left-to-right iteration through the string. Here's how the implementation works:

Algorithm Steps:

  1. Initialize a result variable: Start with ans = 0 to accumulate the column number.

  2. Iterate through each character: Process the string from left to right using for c in map(ord, columnTitle). The map(ord, columnTitle) converts each character to its ASCII value for easier arithmetic.

  3. Apply the base conversion formula: For each character, use the formula:

    ans = ans * 26 + c - ord("A") + 1

    Breaking down this formula:

    • ans * 26: Shifts the existing value left by one position in base-26 (similar to multiplying by 10 in decimal to shift digits)
    • c - ord("A"): Converts the ASCII value to a 0-based index (A→0, B→1, ..., Z→25)
    • + 1: Adjusts for Excel's 1-based system (A→1, B→2, ..., Z→26)
  4. Return the result: After processing all characters, ans contains the final column number.

Example Walkthrough:

Let's trace through "AB":

  • Initial: ans = 0
  • Process 'A':
    • ans = 0 * 26 + (65 - 65 + 1) = 0 + 1 = 1
  • Process 'B':
    • ans = 1 * 26 + (66 - 65 + 1) = 26 + 2 = 28
  • Result: 28

For a longer example like "ZY":

  • Initial: ans = 0
  • Process 'Z':
    • ans = 0 * 26 + (90 - 65 + 1) = 0 + 26 = 26
  • Process 'Y':
    • ans = 26 * 26 + (89 - 65 + 1) = 676 + 25 = 701
  • Result: 701

The beauty of this approach is its simplicity - it processes the string in a single pass with O(n) time complexity where n is the length of the column title, and uses O(1) extra space.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through converting the Excel column title "BC" to its column number.

Step-by-step process:

  1. Initialize: Start with ans = 0

  2. Process first character 'B':

    • Current value: ans = 0
    • Character 'B' has ASCII value 66
    • Apply formula: ans = ans * 26 + (c - ord("A") + 1)
    • Calculate: ans = 0 * 26 + (66 - 65 + 1) = 0 + 2 = 2
    • After 'B': ans = 2
  3. Process second character 'C':

    • Current value: ans = 2
    • Character 'C' has ASCII value 67
    • Apply formula: ans = ans * 26 + (c - ord("A") + 1)
    • Calculate: ans = 2 * 26 + (67 - 65 + 1) = 52 + 3 = 55
    • After 'C': ans = 55
  4. Return result: The column number for "BC" is 55

Verification:

  • 'B' in the first position represents 2 × 26¹ = 52
  • 'C' in the second position represents 3 × 26⁰ = 3
  • Total: 52 + 3 = 55

The key insight is that each iteration shifts our previous result by multiplying by 26 (moving it one position left in base-26), then adds the current letter's value. This builds up the final number from left to right, just like reading a multi-digit number.

Solution Implementation

1class Solution:
2    def titleToNumber(self, columnTitle: str) -> int:
3        """
4        Convert Excel column title to column number.
5      
6        Args:
7            columnTitle: Excel column title string (e.g., "A", "AB", "ZY")
8          
9        Returns:
10            Corresponding column number (1-indexed)
11        """
12        # Initialize result to store the column number
13        result = 0
14      
15        # Iterate through each character in the column title
16        for char in columnTitle:
17            # Convert character to its position in alphabet (A=1, B=2, ..., Z=26)
18            char_value = ord(char) - ord('A') + 1
19          
20            # Build the result using base-26 conversion
21            # Similar to converting "123" to decimal: 1*10^2 + 2*10^1 + 3*10^0
22            # Here we do: previous_result * 26 + current_char_value
23            result = result * 26 + char_value
24      
25        return result
26
1class Solution {
2    /**
3     * Converts an Excel column title to its corresponding column number.
4     * For example: A -> 1, B -> 2, Z -> 26, AA -> 27, AB -> 28
5     * 
6     * @param columnTitle The Excel column title string (e.g., "AB", "ZY")
7     * @return The corresponding column number
8     */
9    public int titleToNumber(String columnTitle) {
10        int result = 0;
11      
12        // Iterate through each character in the column title
13        for (int i = 0; i < columnTitle.length(); i++) {
14            // Get the current character
15            char currentChar = columnTitle.charAt(i);
16          
17            // Convert character to its corresponding value (A=1, B=2, ..., Z=26)
18            int charValue = currentChar - 'A' + 1;
19          
20            // Build the result using base-26 conversion
21            // Multiply previous result by 26 (like shifting digits in base-26)
22            // Then add the current character's value
23            result = result * 26 + charValue;
24        }
25      
26        return result;
27    }
28}
29
1class Solution {
2public:
3    int titleToNumber(string columnTitle) {
4        // Initialize result to store the column number
5        int result = 0;
6      
7        // Iterate through each character in the column title
8        for (char& ch : columnTitle) {
9            // Convert from base-26 system to decimal
10            // Multiply previous result by 26 (shift left in base-26)
11            // Add current character's value (A=1, B=2, ..., Z=26)
12            result = result * 26 + (ch - 'A' + 1);
13        }
14      
15        // Return the final column number
16        return result;
17    }
18};
19
1/**
2 * Converts an Excel column title to its corresponding column number.
3 * For example: A -> 1, B -> 2, ..., Z -> 26, AA -> 27, AB -> 28, ...
4 * 
5 * @param columnTitle - The Excel column title string (e.g., "A", "AB", "ZY")
6 * @returns The corresponding column number
7 */
8function titleToNumber(columnTitle: string): number {
9    // Initialize result to store the final column number
10    let result: number = 0;
11  
12    // Iterate through each character in the column title
13    for (const character of columnTitle) {
14        // Convert the current result to base 26 and add the current character's value
15        // 'A' corresponds to 1, 'B' to 2, ..., 'Z' to 26
16        result = result * 26 + (character.charCodeAt(0) - 'A'.charCodeAt(0) + 1);
17    }
18  
19    return result;
20}
21

Time and Space Complexity

The time complexity is O(n), where n is the length of the string columnTitle. This is because the code iterates through each character in the string exactly once using the for loop. The map(ord, columnTitle) operation processes each character once, and within each iteration, the operations (ans * 26, addition, and subtraction) are all constant time O(1) operations.

The space complexity is O(1). The algorithm only uses a fixed amount of extra space regardless of the input size. The variable ans stores a single integer, and the loop variable c holds one character's ASCII value at a time. The map() function returns an iterator that doesn't store all values in memory at once, instead generating them on-the-fly, so no additional space proportional to the input size is required.

Common Pitfalls

1. Treating it as a Standard Base-26 System

The most common mistake is thinking this is a regular base-26 number system where digits range from 0-25. In Excel's system, there's no "0" - letters represent values from 1-26, making it a bijective base-26 numeral system.

Incorrect approach:

# Wrong: Treating A as 0 instead of 1
result = result * 26 + (ord(char) - ord('A'))  # Missing the +1

Correct approach:

# Right: A=1, B=2, ..., Z=26
result = result * 26 + (ord(char) - ord('A') + 1)

2. Processing Characters in Wrong Order

Some might try to process the string from right to left (like traditional positional notation), which requires tracking powers of 26 and makes the code more complex.

Inefficient approach:

# Works but unnecessarily complex
result = 0
power = 0
for char in reversed(columnTitle):
    result += (ord(char) - ord('A') + 1) * (26 ** power)
    power += 1

Better approach:

# Simpler left-to-right processing
result = 0
for char in columnTitle:
    result = result * 26 + (ord(char) - ord('A') + 1)

3. Off-by-One Errors in Character Conversion

Forgetting to add 1 when converting from character to value, or using the wrong ASCII base character.

Common mistakes:

# Wrong: Using 'a' instead of 'A' for uppercase letters
char_value = ord(char) - ord('a') + 1

# Wrong: Forgetting the +1 adjustment
char_value = ord(char) - ord('A')

# Wrong: Using wrong offset
char_value = ord(char) - ord('A') - 1

4. Integer Overflow Concerns (Language-Specific)

While Python handles large integers automatically, in languages like Java or C++, you might need to consider overflow for very long column titles.

Solution for languages with fixed integer sizes:

# In Python this isn't needed, but in other languages:
# Use long/long long data types
# Or check for overflow before multiplication:
if result > (MAX_INT - char_value) // 26:
    # Handle overflow
    raise OverflowError("Column number too large")

5. Not Validating Input

Assuming the input is always valid without checking for edge cases.

Robust version with validation:

def titleToNumber(self, columnTitle: str) -> int:
    if not columnTitle:
        raise ValueError("Column title cannot be empty")
  
    result = 0
    for char in columnTitle:
        if not 'A' <= char <= 'Z':
            raise ValueError(f"Invalid character: {char}")
      
        char_value = ord(char) - ord('A') + 1
        result = result * 26 + char_value
  
    return result

The key insight is recognizing that Excel's column naming is a bijective base-26 system where each position's value ranges from 1-26 rather than 0-25, and processing left-to-right with the multiplication method keeps the implementation clean and efficient.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Given a sorted array of integers and an integer called target, find the element that equals to the target and return its index. Select the correct code that fills the ___ in the given code snippet.

1def binary_search(arr, target):
2    left, right = 0, len(arr) - 1
3    while left ___ right:
4        mid = (left + right) // 2
5        if arr[mid] == target:
6            return mid
7        if arr[mid] < target:
8            ___ = mid + 1
9        else:
10            ___ = mid - 1
11    return -1
12
1public static int binarySearch(int[] arr, int target) {
2    int left = 0;
3    int right = arr.length - 1;
4
5    while (left ___ right) {
6        int mid = left + (right - left) / 2;
7        if (arr[mid] == target) return mid;
8        if (arr[mid] < target) {
9            ___ = mid + 1;
10        } else {
11            ___ = mid - 1;
12        }
13    }
14    return -1;
15}
16
1function binarySearch(arr, target) {
2    let left = 0;
3    let right = arr.length - 1;
4
5    while (left ___ right) {
6        let mid = left + Math.trunc((right - left) / 2);
7        if (arr[mid] == target) return mid;
8        if (arr[mid] < target) {
9            ___ = mid + 1;
10        } else {
11            ___ = mid - 1;
12        }
13    }
14    return -1;
15}
16

Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More