171. Excel Sheet Column Number

Dare2Solve

Dare2Solve

171. Excel Sheet Column Number
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Description

The problem is to convert a given Excel column title (as it appears in an Excel sheet) into its corresponding column number. For example, the column title "A" corresponds to 1, "AB" to 28, and "ZY" to 701. The task is to simulate this conversion process and return the correct column number.

Intuition

Excel column titles are based on a base-26 numeral system, where each letter represents a digit, with 'A' corresponding to 1, 'B' to 2, and so on up to 'Z' for 26. The problem is essentially about converting a string from this custom base-26 system into a decimal number. The conversion is similar to how we convert a number from a numeral system like binary or hexadecimal to a decimal number.

Approach

  1. Initialization:

    • Start with a variable count initialized to 0. This will hold the final column number.
  2. Iterate Through the Column Title:

    • Traverse each character of the column title string.
    • For each character, calculate its position in the alphabet (e.g., 'A' corresponds to 1, 'B' to 2, etc.) by subtracting the ASCII value of 'A' and adding 1.
    • Update the count by multiplying the existing value by 26 (since it's base-26) and then adding the positional value of the current character.
  3. Return the Result:

    • After processing all characters, the count variable will contain the final column number.

Complexity

Time Complexity:

O(n), where n is the length of the column title. Each character in the string is processed once.

Space Complexity:

O(1) additional space is required, as the solution only uses a few extra variables for calculations.

Code

C++

class Solution {
public:
    int titleToNumber(string columnTitle) {
        int count = 0;
        for (char c : columnTitle) {
            int currentVal = c - 'A' + 1;
            count = count * 26 + currentVal;
        }
        return count;
    }
};

Python

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        count = 0
        for c in columnTitle:
            currentVal = ord(c) - ord('A') + 1
            count = count * 26 + currentVal
        return count

Java

class Solution {
    public int titleToNumber(String columnTitle) {
        int count = 0;
        for (int i = 0; i < columnTitle.length(); i++) {
            int currentVal = columnTitle.charAt(i) - 'A' + 1;
            count = count * 26 + currentVal;
        }
        return count;
    }
}

JavaScript

var titleToNumber = function(columnTitle) {
    
    let count = 0;
    for(let i=0; i < columnTitle.length; i++){
        let currentVal = columnTitle.charCodeAt(i) - "A".charCodeAt(0) +1;
        count = count * 26 + currentVal
    }
    return count;
};