Sponsored
Sponsored
This approach involves treating each character of the column title string as a digit in a base-26 number system. We iterate over the string from left to right, calculating its contribution to the overall number at each step by multiplying with an appropriate power of 26.
Time Complexity: O(n), where n is the length of the column title.
Space Complexity: O(1), as no additional space is used that scales with input size.
1function titleToNumber(columnTitle) {
2 let result = 0;
3 for (let i = 0; i < columnTitle.length; i++) {
4 result = result * 26 + (columnTitle.charCodeAt(i) - 'A'.charCodeAt(0) + 1);
5 }
6 return result;
7}
8
9// Example Usage
10console.log(titleToNumber("ZY"));
JavaScript's charCodeAt() function is used to convert characters to numeric values. We process each character in the input string using a loop to compute the result in a base-26 system.
This approach uses recursion to compute the column number. Starting from the first character, the function recursively converts the rest of the string and adds the current character's contribution by treating it as a digit in a 26-based number system. This implements a divide-and-conquer strategy.
Time Complexity: O(n)
Space Complexity: O(n), due to recursion stack space.
1
In the Python recursive solution, we define a helper function that recursively computes the column number by processing one character at a time, using recursion to handle the rest.