Problem 168

Abstract / Summary

Convert a given positive integer to its corresponding excel column title as a string without using special characters or abbreviations.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0168.py

class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        result = ""
        # careful: 1-based numeration scheme
        while columnNumber > 0:
            result = chr(ord("A") + (columnNumber - 1) % 26) + result
            columnNumber = (columnNumber - 1) // 26
        return result
8 lines | 321 bytes | submitted September 5, 2023 | GitHub   14% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 47% (1+ million submissions).

Typical patterns to solve this problem:
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method convertToTitle. The method receives an integer columnNumber and returns its corresponding Excel column title as a string. The algorithm treats the column numbering as a 1-based system, repeatedly extracting the least-significant “digit” in a base-26 representation where the digits are the letters A through Z. The result is built by prepending each derived character, yielding the final title once the input number is reduced to zero.

Key Steps

The conversion proceeds inside a while loop that continues while columnNumber remains greater than zero. The first operation inside the loop computes the character for the current position:

result = chr(ord("A") + (columnNumber - 1) % 26) + result

Here, (columnNumber - 1) % 26 yields a zero-based offset within the alphabet, and chr(ord("A") + offset) converts that offset to the appropriate uppercase letter. The character is concatenated to the front of result, ensuring that the most significant letter ends up at the leftmost position.

The second operation updates columnNumber for the next iteration:

columnNumber = (columnNumber - 1) // 26

Subtracting one before the integer division aligns the 1-based numbering with zero-based arithmetic, effectively moving to the next higher “digit” in the base-26 scheme.

When the loop terminates, the accumulated result string contains the full column title, which the method returns:

return result

Edge Cases

The algorithm gracefully handles the smallest valid input, columnNumber = 1. In this case, the modulo operation yields 0, mapping to 'A', and the division step reduces the number to zero, ending the loop after a single iteration. The result is correctly 'A'.

For inputs that are exact multiples of 26, such as columnNumber = 26 or 52, the subtraction of one before the modulo and division steps ensures that the mapping wraps to 'Z' for the least-significant position and correctly propagates the carry to the next position. For example, 26 yields 'Z' because (26 - 1) % 26 equals 25, which maps to 'Z', and (26 - 1) // 26 becomes 0, terminating the loop.

Larger numbers, including those that produce multi-character titles like 702 ('ZZ') or 703 ('AAA'), are processed through successive iterations. Each iteration reduces the number by a factor of roughly 26, guaranteeing termination after a number of steps proportional to the length of the resulting title.

Performance Optimizations

The implementation achieves optimal performance for this problem class by operating directly on integer arithmetic and character code manipulation without auxiliary data structures. The use of chr and ord avoids the overhead of dictionary lookups or string formatting functions. By constructing the result string through left-concatenation inside the loop, the algorithm avoids the need for a separate reversal step after the loop completes. Since Python strings are immutable, each concatenation creates a new string, but the number of iterations is bounded by the length of the output (at most 7 for 32-bit integers), keeping the total overhead negligible.

The loop condition while columnNumber > 0 ensures that the method performs the minimal number of iterations required to represent the input number, and the integer division (columnNumber - 1) // 26 efficiently computes the next quotient without resorting to floating-point operations. Overall, the method runs in linear time relative to the length of the resulting title and uses only a constant amount of additional memory for the intermediate variables result and columnNumber.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a magical machine that turns numbers into labels for columns in a spreadsheet. This code works like a little robot that repeatedly plays a game of tag to figure out which letter belongs in each spot.

The robot starts with its backpack empty, holding just the big number you gave it. Inside the heart of the machine, it looks at the number and subtracts one because the counting starts at one instead of zero. It uses the remainder after dividing by twenty-six to pick a letter from the alphabet. If the number is one, it picks A. If it is two, it picks B, and so on.

Once it picks a letter, it sticks that letter at the very front of its growing label. Then, it changes the original number by dividing it by twenty-six so it can figure out the next letter to the left. The robot keeps doing this over and over until the number disappears and the label is finished. Think of it like building a tower of blocks where each new block gets added to the bottom until the whole tower spells out the name of the column.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.70 | σ = 0.85

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca Python Java C# Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
54 links | 39 authors | 10 languages

Videos

16 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 easy 6 medium
12 solutions   September 5, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality