Command Palette

Search for a command to run...

Problem 39.4 · Math for Coding InterviewsEasy

Excel Sheet Column Number

What it teaches: Base 26 with digits 1–26.

Practise it on judges as “Excel Sheet Column Number”.

In plain words

Spreadsheet columns count A to Z, then AA, AB, … It is like counting in base 26 where A = 1 and Z = 26. Read the letters left to right; each new letter shifts the value so far by one place (× 26) and adds its own value, just like reading 3, then 37, then 375 in base 10.

Return the column number. Example: "ZY" → 701.

The problem

Convert a column title (A = 1, Z = 26, AA = 27, …) to its number.

Example 1

Input: columnTitle = "ZY"
Output: 701

Constraints

  • 1 ≤ length ≤ 7

Pattern clues in the wording

  • → Letters as digits

These clues point to Number Theory and Combinatorics: GCD, primes, modular arithmetic, fast power and counting formulas that turn loops into a few lines of math.

Stuck? Take one hint at a time

Solution · starter
class Solution {
    public int titleToNumber(String columnTitle) {
        return 0;
    }
}

Write your solution locally or in your editor for now. Pick Java, Python, C++, JavaScript or Go above: every solution on this page switches with it. The in-browser runner will run these tests right here.

Test cases

#InputExpected
1
columnTitle = "A"
1
2
columnTitle = "AB"
28
3
columnTitle = "ZY"
701

From slow to fast

Approaches

1

Horner's rule in base 26

Time O(n) Space O(1)

Read left to right, multiplying by 26 each step.

▶ Dry run: value = value × 26 + lettercolumnTitle = "ZY"
Z
0
Y
1

vars(vars)

value: 0

Step 1/3Start with 0.

Approach 1
class Solution {
    public int titleToNumber(String columnTitle) {
        int value = 0;
        for (char c : columnTitle.toCharArray()) value = value * 26 + (c - 'A' + 1);
        return value;
    }
}

Verdict: Same as parsing a decimal number.

Before you submit

Edge cases and common mistakes

Test these inputs

  • Single letter
  • "FXSHRXW" (the largest int-sized title)

Mistakes people make

  • Treating A as 0.

Interview

Follow-up questions

And the reverse (number to title)?

Connect the dots

Where this shows up in real systems