Problem

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

OR

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB

Examples

Example 1:

Input: columnNumber = 1
Output: "A"

Example 2:

Input: columnNumber = 28
Output: "AB"

Example 3:

Input: columnNumber = 701
Output: "ZY"

Similar problem

Excel Sheet Column Number Problem

Notes

This is just like base 26 number conversion.

Think of it like this. How would you convert a number to binary ? Can you apply the same principle here now that the base is different ?

Solution

Method 1 - Using string builder and division by 26

To solve the problem of converting a positive integer to its corresponding Excel column title, we need to understand the mapping from numbers to Excel column titles (‘A’ to ‘Z’, ‘AA’, ‘AB’, …, etc.), which can be thought of as a base-26 number system but starts from 1 instead of 0.

Steps:

  1. Initialize Result: Use a StringBuilder or a string to collect characters in reverse order as we process the number.
  2. Convert Number to Title:
    • Repeat while the number is greater than 0:
      • Decrement the number by 1 (to handle the 1-based indexing).
      • Compute the remainder when dividing by 26 to get the correct character (from ‘A’ to ‘Z’).
      • Append the computed character to the result.
      • Update the number by integer division with 26.
  3. Reverse and Return Result: After building the result in reverse order, reverse the collected characters to get the final column title.

Code

Java
class Solution {
    public String convertToTitle(int n) {
        StringBuilder ans = new StringBuilder();
        
        while (n > 0) {
            n--;  // Decrement n to handle 1-based indexing
            char ch = (char) (n % 26 + 'A');
            ans.append(ch);
            n /= 26;
        }
        
        // Reverse and convert StringBuilder to string
        return ans.reverse().toString();
    }
}
Python
class Solution:
    def convertToTitle(self, n: int) -> str:
        ans: List[str] = []
        
        while n > 0:
            n -= 1  # Decrement n to handle 1-based indexing
            ans.append(chr(n % 26 + ord('A')))
            n //= 26
        
        # Reverse the list and join to form the final string
        return ''.join(ans[::-1])

Complexity

  • ⏰ Time complexity: O(log_{26}(n)), where n is the integer being converted. This is because we repeatedly divide the number by 26.
  • 🧺 Space complexity: O(log_{26}(n)) because we store characters proportional to the number of digits in base-26.