Spreadsheets name their columns with letters: A to Z for columns 1 to 26, then AA, AB, and so on up to ZZ, then AAA, and onward.
Given a positive whole number columnNumber, return the name of that column.
Example 1
Input: columnNumber = 3 Output: "C" Why: the third letter
2 more examples and the constraints
Example 2
Input: columnNumber = 52 Output: "AZ" Why: 1 × 26 + 26 = 52
Example 3
Input: columnNumber = 2024 Output: "BYV" Why: 2 × 676 + 25 × 26 + 22 = 2024
Constraints
- 1 ≤ columnNumber ≤ 2,147,483,647 (the largest 32-bit integer)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Find the length firstO(log n)
- Base 26, shifted by oneO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for the largest input | Verdict |
|---|---|---|---|
| Find the length first | O(log n) | Correct; two loops to explain | |
| Base 26, shifted by one | O(log n) | Best; one short loop |
n = columnNumber. Both run at most 7 rounds of each loop.
Edge cases to test
- Exactly 26. Must give "Z", not "A@" or "AZ". The shift by one handles it.
- Just past a block. 27 is "AA" and 703 is "AAA": a new length begins.
- All Z. 702 is "ZZ" and 18,278 is "ZZZ".
- The largest input. 2,147,483,647 is "FXSHRXW", seven letters.
Common mistakes
- Treating it as plain base 26, so multiples of 26 produce a missing digit.
- Forgetting to reverse the letters, which come out right to left.
- Letting a block size or running total overflow a 32-bit int near the upper limit.
How to talk through it
- 1Clarify. Is column 1 "A"? Are inputs always positive?
- 2Spot the base. It looks like base 26, but the digits run 1 to 26 and there is no zero.
- 3Show the trap. Plain base 26 breaks on 26: the remainder is 0 and no letter means 0.
- 4Shift each digit. Subtract 1 before % and //. O(log n) time.
- 5Test out loud. Run 26, 27, 52 and 702 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?