#171
Excel Sheet Column Number
EasyMathStringBase ConversionString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is essentially the same as the brute force but emphasizes the mathematical properties of base-26 conversion. We can calculate the column number directly using a single pass through the string.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to hold the result as 0.
- 2Step 2: Iterate through each character in the string from left to right.
- 3Step 3: For each character, calculate its value and update the result using the formula: result = result * 26 + (value of character).
solution.py5 lines
1def titleToNumber(columnTitle):
2 result = 0
3 for char in columnTitle:
4 result = result * 26 + (ord(char) - ord('A') + 1)
5 return resultℹ
Complexity note: The time complexity remains O(n) as we still process each character once. The space complexity is O(1) since we use a fixed amount of space.
- 1Understanding how Excel columns map to numbers is crucial.
- 2Recognizing the base-26 nature of the problem helps in forming the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.