TARGET DECK: Leetcode FILE TAGS: Easy


Intuition

  • Letters 1-26 map from A to Z.
  • Therefore, start from the beginning letter, and multiply by how much that place represents.
  • So you can come up with the formula, which is the letter converted to a number multiplied by 26 for however many times it’s position is in.
  • Alternatively, you can directly multiply the current result by 26:
    1. ‘1’ = 1
    2. ‘13’ = (1 x 10) + 3 = 13
    3. ‘133’ = (13 x 10) + 3 = 133
    4. ‘1337’ = (133 x 10) + 7 = 1337
  • This essentially gets a new place for which to insert the new count. But instead, we do the same in base 26:
    1. L = 12
    2. E = (12 x 26) + 5 = 317
    3. E = (317 x 26) + 5 = 8247
    4. T = (8247 x 26) + 20 = 214442

Complexity

Runtime

, where N is the number of letters that make up the column number, since we are looping through each letter, converting it, then multiplying by that amount.

Space

if not including the result.

Code

Directly Multiplying Current Result

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        n = len(columnTitle)
        res = 0
        for i in range(n):
            res *= 26
            res += ord(columnTitle[i]) - ord('A') + 1
        
        return res

Inner for Loop for Letter Occurrence

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        n = len(columnTitle)
        res = 0
        for i in range(n):
            place = ord(columnTitle[i]) - ord('A') + 1
            for i in range(n - i - 1):
                place *= 26
            res += place
        
        return res

Notes

Cards

START Basic Front: Excel Sheet Column Number Back: Letter converted to a number multiplied by 26 for however many times it’s position is in (n - i - 1)

END


References