Excel Sheet Column Number

Easymathstring
Category: Fundamentals
Companies that ask this question:
AmazonMicrosoft

Approach

Excel Sheet Column Number

Approach

Convert from base-26 positional notation where A=1, B=2, ..., Z=26.

Algorithm

  1. Initialize result to 0
  2. For each character from left to right:
    • Multiply current result by 26 (shift position)
    • Add character value (A=1, B=2, ..., Z=26)
  3. Return final result

Complexity

  • Time: O(n) - process each character once
  • Space: O(1) - constant extra space

Key Insights

  • Similar to converting from any base to decimal
  • Each position represents 26^i where i is position from right
  • Example: AB = 1×26 + 2 = 28

Solution

java
1class Solution {
2    public int titleToNumber(String columnTitle) {
3        int result = 0;
4        
5        for (char c : columnTitle.toCharArray()) {
6            result = result * 26 + (c - 'A' + 1);
7        }
8        
9        return result;
10    }
11}
Loading visualizer...