Skip to main content

Excel Sheet Column Number

LeetCode 171 | Difficulty: Easy​

Easy

Problem Description​

Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...

Example 1:

Input: columnTitle = "A"
Output: 1

Example 2:

Input: columnTitle = "AB"
Output: 28

Example 3:

Input: columnTitle = "ZY"
Output: 701

Constraints:

- `1 <= columnTitle.length <= 7`

- `columnTitle` consists only of uppercase English letters.

- `columnTitle` is in the range `["A", "FXSHRXW"]`.

Topics: Math, String


Approach​

Mathematical​

Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.

When to use

Problems with clear mathematical structure, counting, number properties.

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 76 ms)​

MetricValue
Runtime76 ms
Memory36 MB
Date2022-02-22
Solution
public class Solution {
public int TitleToNumber(string s) {
int result=0, len = s.Length;
for (int i = 0; i <len ; i++)
{
result = (result*26) + (s[i]-'A'+1);
}
return result;
}
}
πŸ“œ 2 more C# submission(s)

Submission (2022-02-22) β€” 103 ms, 36.5 MB​

public class Solution {
public int TitleToNumber(string s) {
int result=0;
for (int i = 0; i <s.Length ; i++)
{
result = (result*26) + (s[i]-'A'+1);
}
return result;
}
}

Submission (2018-03-30) β€” 336 ms, N/A​

public class Solution {
public int TitleToNumber(string s) {
int result=0;
for (int i = 0; i <s.Length ; i++)
{
result = (result*26) + (s[i]-'A'+1);
}
return result;
}
}

Complexity Analysis​

ApproachTimeSpace
Solution$O(n)$$O(1) to O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.