Solving Leetcode Interviews in Seconds with AI: Excel Sheet Column Number
Introduction
In this blog post, we will explore how to solve the LeetCode problem "171" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
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"].
Explanation
- The core idea is to treat the column title as a base-26 number, where 'A' represents 1, 'B' represents 2, and so on, up to 'Z' representing 26.
- Iterate through the string from left to right, updating the result by multiplying the current result by 26 and adding the value of the current character.
- The value of each character is determined by its position relative to 'A' in the alphabet.
- Runtime Complexity: O(n), where n is the length of the column title. Storage Complexity: O(1).
Code
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
result = 0
for char in columnTitle:
result = result * 26 + (ord(char) - ord('A') + 1)
return result