A spreadsheet names its columns with capital letters: A is column 1, B is 2, and so on to Z, which is 26. After Z the names get a second letter: AA is 27, AB is 28, up to ZZ, and then three letters begin with AAA.
Given a column name, columnTitle, return its column number.
Example 1
Input: columnTitle = "C" Output: 3 Why: C is the third letter
2 more examples and the constraints
Example 2
Input: columnTitle = "BA" Output: 53 Why: 2 × 26 + 1 = 53
Example 3
Input: columnTitle = "CAB" Output: 2056 Why: 3 × 676 + 1 × 26 + 2 = 2,056
Constraints
- 1 ≤ length of columnTitle ≤ 7
- columnTitle uses only capital letters A to Z
- The column number is at most 2,147,483,647 (the title "FXSHRXW")
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sum of place valuesO(n)
- Left to right, times 26O(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 7-letter title | Verdict |
|---|---|---|---|
| Sum of place values | O(n) | Passes; watch the 26^7 overflow | |
| Left to right, times 26 | O(n) | Best; one running total |
n = letters in the title.
Edge cases to test
- One letter. "A" is 1 and "Z" is 26: there is no zero digit.
- Rollover. "Z" is 26 and "AA" is 27, just one more.
- All Zs. "ZZ" is 702, the last two-letter column; "AAA" is 703.
- The largest title. "FXSHRXW" is 2,147,483,647, the largest 32-bit int.
Common mistakes
- Using A = 0, which makes "A" and "AA" look the same.
- Reading letters right to left but multiplying the total by 26, which reverses the digits.
- Letting the place value 26^7 overflow a 32-bit int.
How to talk through it
- 1Clarify. Only capital letters? Is the title always valid and at most 7 letters?
- 2Name the idea. It is base 26 with digits 1 to 26 instead of 0 to 25.
- 3Pick a direction. Left to right: multiply the total by 26, then add the letter.
- 4Check overflow. The biggest title gives exactly 2^31 − 1, which still fits in an int.
- 5Test out loud. Run "A", "Z", "AA" and "ZZ" 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?