We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Excel Sheet Column Number

Number: 171

Difficulty: Easy

Paid? No

Companies: Amazon, Goldman Sachs, Zoho, Microsoft, Docusign, razorpay, Uber


Problem Description

Given a string columnTitle representing a column title as it appears in an Excel sheet, return its corresponding column number. For example, A maps to 1, B maps to 2, ..., Z maps to 26, AA maps to 27, AB maps to 28, and so on.


Key Insights

  • The problem is similar to converting a base-26 numeral system to a decimal number.
  • Each character in the string represents a digit value where 'A' equals 1, 'B' equals 2, ..., and 'Z' equals 26.
  • Iteratively multiply the accumulated result by 26 and add the numeric value of the current character.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the columnTitle string.
Space Complexity: O(1) due to the use of a constant amount of additional space.


Solution

The solution treats the given column title as a number in base-26. For each character in the string, the algorithm converts the character to its corresponding numeric value (A=1, B=2, …, Z=26) by adjusting with the ASCII value. It then accumulates the result by multiplying the current result by 26 (reflecting a shift in the numeral system) and adding the current digit. This ensures that the overall runtime scales linearly with the length of the input string and uses constant space.


Code Solutions

# Python solution for converting Excel column title to its corresponding column number
def excelColumnNumber(columnTitle):
    # Initialize the result
    result = 0
    # Iterate over each character in the column title
    for char in columnTitle:
        # Convert the character to its corresponding value (A=1, B=2, ..., Z=26)
        value = ord(char) - ord('A') + 1
        # Update the result by shifting previous result by 26 and adding the current value
        result = result * 26 + value
    return result

# Example usage:
print(excelColumnNumber("A"))  # Expected output: 1
print(excelColumnNumber("AB")) # Expected output: 28
print(excelColumnNumber("ZY")) # Expected output: 701
← Back to All Questions