Excel Sheet Column Number - Complete Solution Guide
Excel Sheet Column Number is LeetCode problem 171, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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"] .
Detailed Explanation
The problem asks you to convert an Excel-style column title (e.g., "A", "AB", "ZY") into its corresponding column number. The columns are numbered sequentially starting from 1: A=1, B=2, ..., Z=26, AA=27, AB=28, and so on. The input is a string containing only uppercase English letters, and the output is an integer representing the column number. The constraints specify that the input string length is between 1 and 7 characters, and it falls within a specific range.
Solution Approach
The solution uses a iterative approach. It traverses the input string character by character. For each character, it calculates its numerical value (1 for 'A', 2 for 'B', ..., 26 for 'Z') and adds this value to the running total after multiplying the total by 26. This multiplication by 26 effectively shifts the place value in the base-26 system, similar to multiplying by 10 when working in base-10.
Step-by-Step Algorithm
- Step 1: Initialize a variable `result` to 0. This variable will store the final column number.
- Step 2: Iterate through the characters of the input string `columnTitle`.
- Step 3: For each character, calculate its value: `char_value = ord(char) - ord('A') + 1`. This subtracts the ASCII value of 'A' from the character's ASCII value and adds 1, effectively mapping 'A' to 1, 'B' to 2, and so on.
- Step 4: Update `result`: `result = result * 26 + char_value`. This performs the base-26 conversion.
- Step 5: After iterating through all characters, return `result`.
Key Insights
- Insight 1: Recognizing that the column numbering system is essentially a base-26 number system where A=1, B=2, ..., Z=26.
- Insight 2: Understanding that we can iterate through the column title string from left to right, multiplying the accumulated result by 26 for each character and adding the character's value.
- Insight 3: The use of ASCII values (ord() in Python) to efficiently convert characters to their numerical representation is crucial for an optimal solution.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Math, String.
Companies
Asked at: Docusign, Zoho, razorpay.