Excel Sheet Column Title

Easy Top 250
Associated Patterns
Interviewed At (Company Tags)
MicrosoftAmazon

Problem Description

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

For example:

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

Examples

Example 1:

Input: columnNumber = 1 Output: “A”

Example 2:

Input: columnNumber = 28 Output: “AB”

Example 3:

Input: columnNumber = 701 Output: “ZY”


Constraints

  • 1 ≤ columnNumber ≤ 2³¹ - 1

Base-26 Conversion with a Shift

Excel column titles are essentially a base-26 numbering system, but with a twist: they are 1-indexed (A=1) rather than 0-indexed. This means that 26 maps to Z, and 27 starts the next digit place (AA).

In standard base conversion, we find the remainder using modulo % 26 and then divide the number. Because this system is 1-indexed, we must subtract 1 from the number before performing each modulo operation:

  1. columnNumber -= 1
  2. remainder = columnNumber % 26
  3. Convert remainder to a character: (char) ('A' + remainder)
  4. columnNumber /= 26
  5. Repeat until the number becomes 0, then reverse the accumulated characters.

Solution: Base-26 Conversion

class Solution {
    public String convertToTitle(int columnNumber) {
        StringBuilder sb = new StringBuilder();

        while (columnNumber > 0) {
            columnNumber--; // adjust to 0-indexed
            int remainder = columnNumber % 26;
            sb.append((char) ('A' + remainder));
            columnNumber /= 26;
        }

        return sb.reverse().toString();
    }
}
class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        result = []

        while columnNumber > 0:
            columnNumber -= 1  # adjust to 0-indexed
            remainder = columnNumber % 26
            result.append(chr(ord('A') + remainder))
            columnNumber //= 26

        return "".join(reversed(result))
#include <string>
#include <algorithm>

class Solution {
public:
    std::string convertToTitle(int columnNumber) {
        std::string result = "";

        while (columnNumber > 0) {
            columnNumber--; // adjust to 0-indexed
            int remainder = columnNumber % 26;
            result += (char)('A' + remainder);
            columnNumber /= 26;
        }

        std::reverse(result.begin(), result.end());
        return result;
    }
};

Complexity Analysis:

  • Time Complexity: O(log₂₆ N) where N is columnNumber. The loop divides the number by 26 at each step.
  • Space Complexity: O(1) auxiliary space (excluding the output string).

← All Problems