Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

171. Excel Sheet Column Number - Leetcode Solution

Code Implementation

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        result = 0
        for char in columnTitle:
            result = result * 26 + (ord(char) - ord('A') + 1)
        return result
      
class Solution {
public:
    int titleToNumber(string columnTitle) {
        int result = 0;
        for (char c : columnTitle) {
            result = result * 26 + (c - 'A' + 1);
        }
        return result;
    }
};
      
class Solution {
    public int titleToNumber(String columnTitle) {
        int result = 0;
        for (char c : columnTitle.toCharArray()) {
            result = result * 26 + (c - 'A' + 1);
        }
        return result;
    }
}
      
var titleToNumber = function(columnTitle) {
    let result = 0;
    for (let i = 0; i < columnTitle.length; i++) {
        result = result * 26 + (columnTitle.charCodeAt(i) - 'A'.charCodeAt(0) + 1);
    }
    return result;
};
      

Problem Description

Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

For example, A corresponds to 1, B to 2, ..., Z to 26, AA to 27, AB to 28, and so on.

  • Each letter can only be an uppercase English letter ('A' to 'Z').
  • There is exactly one valid mapping for each input string.
  • You do not need to handle invalid input or reuse elements; just compute the number for the given columnTitle.

Thought Process

At first glance, the problem looks similar to converting a number from one base to another, except instead of digits 0-9, we use letters 'A'-'Z' to represent numbers 1-26. For example, 'A' is 1, 'B' is 2, ..., 'Z' is 26, then 'AA' is 27 (like how 10 is after 9 in decimal).

A brute-force approach might try to enumerate all possible combinations, but that's unnecessary. Instead, we can recognize that this is a "base-26" system, but with no zero digit—'A' represents 1, not 0. This means that for each character, we can multiply the current result by 26 and add the value of the current character.

The challenge is to correctly map each character to its corresponding value and accumulate the result in a way similar to how you convert a string of digits to an integer.

Solution Approach

  • Step 1: Initialize a variable (e.g., result) to 0. This will store the final column number.
  • Step 2: Loop through each character in the columnTitle string from left to right.
  • Step 3: For each character, convert it to a number: ord(char) - ord('A') + 1 (or similar logic in other languages). This maps 'A' to 1, 'B' to 2, ..., 'Z' to 26.
  • Step 4: Update the result by multiplying it by 26 (shifting the previous digits left, as in base conversion) and adding the value of the current character.
  • Step 5: After processing all characters, return the result.

This method is efficient because it processes each character exactly once and uses simple arithmetic.

Example Walkthrough

Let's walk through the example columnTitle = "AB":

  1. Start with result = 0.
  2. Process first character: 'A'
    • 'A' maps to 1
    • result = 0 * 26 + 1 = 1
  3. Process second character: 'B'
    • 'B' maps to 2
    • result = 1 * 26 + 2 = 28
  4. Final result is 28, which matches the Excel column numbering for 'AB'.

Another example: columnTitle = "ZY"

  • First: 'Z' → 26, result = 0 * 26 + 26 = 26
  • Second: 'Y' → 25, result = 26 * 26 + 25 = 701

Time and Space Complexity

  • Brute-force approach: If you tried to enumerate all possible column strings up to the given one, the time would grow exponentially and be highly inefficient.
  • Optimized approach (used here):
    • Time Complexity: O(n), where n is the length of columnTitle. We process each character once.
    • Space Complexity: O(1), as we only use a few variables and do not store any intermediate lists or arrays.

Summary

The problem is a classic example of converting a string representation from a custom base (here, base-26 with letters) to a number. Recognizing the analogy to base conversion allows for a simple, efficient solution that processes each character in the string once. The elegance of this solution comes from its direct mapping of the Excel column system to math we already know, making the implementation short and clear.