↓Skip to main content
  1. LeetCode/

LeetCode 171: Excel Sheet Column Number

·1 min· ·
LeetCode Easy Math String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-21

  • Submissions: Runtime Error → Accepted ×7

Approach
#

The reverse of LC 168 (Math Template 7): each letter is worth ord(c) - ord("A") + 1, and scanning left to right with res = res * 26 + value works just like parsing a decimal string.

My Attempts
#

Attempt 1 wrote for i, n in columnTitle[::-1] without enumerate, so unpacking failed (ValueError). Adding it passed.

Solution
#

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        res = 0
        for c in columnTitle:
            res = res * 26 + ord(c) - ord("A") + 1
        return res

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • A is 1, not 0.
  • Use enumerate when both the index and the character are needed.

Interview Explanation
#

Scanning left to right, I multiply the running result by 26 and add the letter’s value, with A as 1. Time O(n).

Related

LeetCode 168: Excel Sheet Column Title
·2 mins
LeetCode Easy Math String
LeetCode 168 note: Excel columns are base 26 without a zero digit; take (n - 1) % 26 as the letter, then n = (n - 1) // 26
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 13: Roman to Integer
·1 min
LeetCode Easy Hash-Table Math String
LeetCode 13 note: add each symbol’s value left to right, subtracting instead when it is smaller than the symbol to its right
LeetCode 202: Happy Number
·1 min
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 note: repeatedly take the sum of squared digits, which reaches 1 or enters a cycle; detect it with a set of seen numbers or fast and slow pointers
LeetCode 205: Isomorphic Strings
·2 mins
LeetCode Easy Hash-Table String
LeetCode 205 note: characters must map one to one; it holds when the distinct characters and distinct pairs all have the same count
LeetCode 125: Valid Palindrome
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 125 note: two pointers skip non-alphanumeric characters and compare lowercase letters, with digits included