Excel Sheet Column Number – Solution & Complexity

1. Understand the Pattern

  • The title behaves like a base-26 number, but the digits run 1..26, not 0..25.
  • A contributes 1, Z contributes 26.
  • Reading left to right, each new letter shifts the running total up by a factor of 26.

2. Map a Letter to Its Value

  • Subtract the code point of A and add 1.
  • So A -> 1, B -> 2, ..., Z -> 26.
  • This is the per-digit value for the base-26 sum.
def letter_value(ch):
    return ord(ch) - ord('A') + 1

3. Accumulate Left to Right

  • Start the result at 0.
  • For each letter, multiply the result by 26 and add the letter's value.
  • After the last letter the result is the column number.
def title_to_number(column_title):
    result = 0
    for ch in column_title:
        result = result * 26 + (ord(ch) - ord('A') + 1)
    return result

4. Final Solution and Complexity

  • Each character is visited once.
  • Time complexity is O(L) for a title of length L.
  • Space complexity is O(1).
def title_to_number(column_title: str) -> int:
    result = 0
    for ch in column_title:
        result = result * 26 + (ord(ch) - ord('A') + 1)
    return result

FAQ