LeetCode 171: Excel Sheet Column Number Solution in Python Explained

Converting an Excel column title to its corresponding number might feel like cracking a code hidden in letters, and LeetCode 171: Excel Sheet Column Number is an easy-level challenge that makes it approachable! Given a string columnTitle representing an Excel column label (e.g., "A", "AB", "ZY"), you need to return its corresponding column number, where A=1, B=2, ..., Z=26, AA=27, and so on, in a base-26 system. In this blog, we’ll solve it with Python, exploring two solutions—Base-26 Conversion with Iteration (our best solution) and Recursive Base-26 Conversion (a practical alternative). With step-by-step examples, detailed code breakdowns, and tips, you’ll master this problem. Let’s decode those numbers!

Problem Statement

Section link icon

In LeetCode 171, you’re given a string columnTitle consisting of uppercase letters representing an Excel column label. Your task is to convert it to its corresponding column number, where:

  • "A" maps to 1, "B" to 2, ..., "Z" to 26.
  • "AA" maps to 27, "AB" to 28, and so on, following a 1-based base-26 system.

This is the reverse of LeetCode 168: Excel Sheet Column Title, and differs from data structure design like LeetCode 170: Two Sum III - Data Structure Design, focusing on string-to-number conversion.

Constraints

  • 1 <= columnTitle.length <= 7
  • columnTitle consists only of uppercase English letters
  • Represents a valid column number between 1 and 2^31 - 1

Example

Let’s see some cases:

Input: columnTitle = "A"
Output: 1
Explanation: "A" maps directly to 1.
Input: columnTitle = "AB"
Output: 28
Explanation: "AB" = 1*26^1 + 2*26^0 = 26 + 2 = 28.
Input: columnTitle = "ZY"
Output: 701
Explanation: "ZY" = 26*26^1 + 25*26^0 = 676 + 25 = 701.

These examples show we’re converting base-26 titles to numbers.

Understanding the Problem

Section link icon

How do you solve LeetCode 171: Excel Sheet Column Number in Python? Take columnTitle = "A". It’s simply 1. For "AB", it’s 126 + 2 = 28 (A=1, B=2). For "ZY", it’s 2626 + 25 = 701 (Z=26, Y=25). This is a base-26 system where A=1 to Z=26, not 0-based, so we calculate each position’s contribution (e.g., 26^power * letter_value). This isn’t a majority element task like LeetCode 169: Majority Element; it’s about letter-to-number mapping. We’ll use: 1. Base-26 Conversion with Iteration: O(n) time, O(1) space—our best solution. 2. Recursive Base-26 Conversion: O(n) time, O(n) space—an alternative.

Let’s dive into the best solution.

Best Solution: Base-26 Conversion with Iteration Approach

Section link icon

Explanation

Base-26 Conversion with Iteration processes the string from left to right, building the number:

  • For each character, multiply the current result by 26 (shift left in base-26).
  • Add the value of the current letter (A=1, B=2, ..., Z=26).
  • Continue until all characters are processed.

This achieves O(n) time complexity (n = string length), O(1) space (no extra structures beyond variables), and simplicity by mimicking base conversion iteratively.

For "AB":

  • Start: result=0.
  • A: 0*26 + 1 = 1.
  • B: 1*26 + 2 = 28.

Step-by-Step Example

Example 1: columnTitle = "A"

Goal: Return 1.

  • Start: result = 0.
  • Step 1: char = 'A', value = 1, result = 0 * 26 + 1 = 1.
  • Finish: Return 1.

Example 2: columnTitle = "AB"

Goal: Return 28.

  • Start: result = 0.
  • Step 1: char = 'A', value = 1, result = 0 * 26 + 1 = 1.
  • Step 2: char = 'B', value = 2, result = 1 * 26 + 2 = 26 + 2 = 28.
  • Finish: Return 28.

Example 3: columnTitle = "ZY"

Goal: Return 701.

  • Start: result = 0.
  • Step 1: char = 'Z', value = 26, result = 0 * 26 + 26 = 26.
  • Step 2: char = 'Y', value = 25, result = 26 * 26 + 25 = 676 + 25 = 701.
  • Finish: Return 701.

How the Code Works (Base-26 Conversion with Iteration) – Detailed Line-by-Line Explanation

Here’s the Python code with a thorough breakdown:

def titleToNumber(columnTitle: str) -> int:
    # Line 1: Initialize result
    result = 0
    # Starting number (e.g., 0)

    # Line 2: Iterate through characters
    for char in columnTitle:
        # Process each letter (e.g., 'A', 'B')

        # Line 3: Shift result left (base-26)
        result *= 26
        # Multiply by 26 (e.g., 0→0, then 1→26)

        # Line 4: Add current letter’s value
        value = ord(char) - ord('A') + 1
        # Convert A=1, B=2, etc. (e.g., 'A'→1, 'B'→2)
        result += value
        # Add value (e.g., 0+1=1, 26+2=28)

    # Line 5: Return final number
    return result
    # e.g., 28 for "AB"

This detailed breakdown clarifies how base-26 conversion with iteration efficiently computes the column number.

Alternative: Recursive Base-26 Conversion Approach

Section link icon

Explanation

Recursive Base-26 Conversion uses recursion to compute the number:

  • Base case: If string length is 1, return its value (A=1, Z=26).
  • Recursive case: Process the first character, multiply by 26^(length-1), add the result of the rest.

It’s a practical alternative, O(n) time (n = string length, recursive calls), O(n) space (recursion stack), but less efficient due to stack overhead.

For "AB":

  • "A" → 1 * 26^1 + "B" → 26 + 2 = 28.

Step-by-Step Example (Alternative)

For "ZY":

  • Step 1: "Z" → 26 * 26^1 + "Y".
  • Step 2: "Y" → 25, total = 26*26 + 25 = 701.
  • Finish: Return 701.

How the Code Works (Recursive)

def titleToNumberRecursive(columnTitle: str) -> int:
    if len(columnTitle) == 1:
        return ord(columnTitle[0]) - ord('A') + 1
    return (ord(columnTitle[0]) - ord('A') + 1) * (26 ** (len(columnTitle) - 1)) + titleToNumberRecursive(columnTitle[1:])

Complexity

  • Base-26 Conversion with Iteration:
    • Time: O(n) – single pass through string.
    • Space: O(1) – constant space.
  • Recursive Base-26 Conversion:
    • Time: O(n) – recursive calls.
    • Space: O(n) – recursion stack.

Efficiency Notes

Base-26 Conversion with Iteration is the best solution with O(n) time and O(1) space, offering efficiency and simplicity—Recursive Base-26 Conversion matches time complexity but uses O(n) space due to recursion, making it elegant but less space-efficient.

Key Insights

  • Base-26: A=1 to Z=26 mapping.
  • Iterative: Builds incrementally.
  • Recursive: Stacks contributions.

Additional Example

Section link icon

For columnTitle = "AZ":

  • Goal: 52.
  • Iterative: A→1, 1*26+26=52, return 52.

Edge Cases

Section link icon
  • Single Letter: "A"1.
  • Max Single: "Z"26.
  • Multi-Letter: "AA"27.

Both solutions handle these well.

Final Thoughts

Section link icon

LeetCode 171: Excel Sheet Column Number in Python is a fun string-to-number challenge. The Base-26 Conversion with Iteration solution excels with its efficiency and clarity, while Recursive Base-26 Conversion offers a recursive perspective. Want more? Try LeetCode 168: Excel Sheet Column Title for the reverse problem or LeetCode 94: Binary Tree Inorder Traversal for tree skills. Ready to practice? Solve LeetCode 171 on LeetCode with "AB", aiming for 28—test your skills now!