Excel Sheet Column Title

Easy · Math & Geometry · Explanation and code example

Iteration

How it works

The iterative approach works from right to left, building the result string in reverse. At each step, we extract the rightmost character, then reduce the number for the next iteration. Since we build characters from least significant to most significant, we reverse the result at the end.

This avoids recursion overhead and makes the process explicit: subtract 1, find the character via modulo, divide by 26, and repeat until the number becomes 0.

Steps

  1. Initialize an empty list res to collect characters.
  2. While columnNumber > 0:
    • Decrement columnNumber by 1.
    • Compute the offset as columnNumber % 26.
    • Append the character chr('A' + offset) to res.
    • Divide columnNumber by 26.
  3. Reverse res and join to form the final string.

Complexity

  • Time complexity: O(log n)
  • Space complexity: O(1) extra space.

Where n is the given column number.

Things to watch for

Treating It as Standard Base-26 Conversion

Unlike standard base conversion where digits range from 0 to 25, Excel columns use a 1-indexed system where A=1 and Z=26. Forgetting to subtract 1 before taking modulo will cause off-by-one errors. For example, column 26 should be "Z", but without the subtraction, you would incorrectly compute the character for position 0.

Forgetting to Reverse the Result in Iterative Approach

When building the string iteratively by repeatedly taking modulo and dividing, you generate characters from least significant (rightmost) to most significant (leftmost). If you forget to reverse the accumulated characters at the end, "ABC" would incorrectly become "CBA". Either build the string in reverse or explicitly reverse it before returning.

Python code example

class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        res = []
        while columnNumber > 0:
            columnNumber -= 1
            offset = columnNumber % 26
            res += chr(ord('A') + offset)
            columnNumber //= 26

        return ''.join(reversed(res))

C++ code example

class Solution {
public:
    string convertToTitle(int columnNumber) {
        string res;
        while (columnNumber > 0) {
            columnNumber--;
            int offset = columnNumber % 26;
            res += ('A' + offset);
            columnNumber /= 26;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations