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 Title

Number: 168

Difficulty: Easy

Paid? No

Companies: Google, Microsoft, Amazon, Apple, Bloomberg, Meta, Oracle, Yext, Zenefits


Problem Description

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example, 1 corresponds to "A", 28 corresponds to "AB", and 701 corresponds to "ZY".


Key Insights

  • This problem is analogous to converting a number to a base-26 numeral system.
  • The column title is like a number in base 26 but without a zero digit; letters A-Z correspond to values 1-26.
  • A common trick is to subtract 1 from columnNumber before modulo operations to properly map the "digit" to a character.
  • Repeated division and modulo will generate letters from the least significant one to the most significant, thus they need to be reversed at the end.

Space and Time Complexity

Time Complexity: O(log26(n)) — The number of iterations is proportional to the number of letters in the resulting string. Space Complexity: O(1) — The extra space used does not depend on the size of columnNumber.


Solution

The solution uses a greedy algorithm approach:

  1. While columnNumber > 0, subtract 1 from it to adjust for the 1-indexed letter mapping.
  2. Compute the remainder (columnNumber % 26) to find the corresponding letter.
  3. Convert the remainder to a character by adding it to the ASCII value of 'A'.
  4. Append or prepend the letter to a result string.
  5. Divide columnNumber by 26 and continue until it becomes zero. The resulting string, after reversing (if built in reverse order) or by inserting at the front, gives the final Excel sheet column title.

Code Solutions

# Python solution for converting a column number to Excel sheet column title
def convertToTitle(columnNumber: int) -> str:
    result = []  # list to collect column letters
    while columnNumber > 0:
        columnNumber -= 1  # adjust to 0-indexed
        remainder = columnNumber % 26  # determine current letter index
        # Convert remainder to corresponding uppercase letter
        letter = chr(ord('A') + remainder)
        result.append(letter)  # add the letter to the result list
        columnNumber //= 26  # update columnNumber for next iteration
    # Since letters are computed in reverse, reverse them before joining
    return ''.join(reversed(result))

# Example usage:
print(convertToTitle(1))   # Output: "A"
print(convertToTitle(28))  # Output: "AB"
print(convertToTitle(701)) # Output: "ZY"
← Back to All Questions