algoadvance

Leetcode 171. Excel Sheet Column Number

Problem Statement

You are given a string columnTitle that represents the column title as appear in an Excel sheet. For example:

You need to return its corresponding column number.

Example 1:

Input: columnTitle = "A"
Output: 1

Example 2:

Input: columnTitle = "AB"
Output: 28

Example 3:

Input: columnTitle = "ZY"
Output: 701

Constraints:

Clarifying Questions:

  1. Q: Should the result be an integer that matches the Excel column numbering system? A: Yes.

  2. Q: Are there any special characters in columnTitle? A: No, columnTitle consists only of uppercase English letters.

  3. Q: Can the input be an empty string? A: No, the constraints ensure that columnTitle.length is at least 1.

Strategy:

To convert each character in columnTitle into its corresponding number:

This can be visualized with the example “AB”:

Code:

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

    public static void main(String[] args) {
        Solution sol = new Solution();
        // Test cases
        System.out.println(sol.titleToNumber("A")); // 1
        System.out.println(sol.titleToNumber("AB")); // 28
        System.out.println(sol.titleToNumber("ZY")); // 701
    }
}

Time Complexity:

The time complexity of the solution is O(n), where n is the length of the columnTitle string. This is because we are processing each character in the string exactly once.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI