NeetCode #881LC-168EasyMath & GeometryNC 250
← Back to All Problems#881 · #168 · Excel Sheet Column Title(Excel 表列名称)
📌 Problem Statement & Constraints
Given an integer
columnNumber, return its corresponding column title as it appears in Excel, where column 1 is A, column 26 is Z, column 27 is AA, and so on. Constraints: 1 <= columnNumber <= 2^31 - 1.💡 Core Algorithmic Approaches
- Excel titles use bijective base-26: there is no zero digit, so
Arepresents1rather than0. - Subtract one before taking the remainder; this converts the representation into an ordinary base-26 with digits
0..25. - Map the remainder to a letter, append it, then divide by
26and repeat. - Because the least significant digit is produced first, reverse the collected letters at the end.
💻 Benchmark Python3 Implementation
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
res = []
while columnNumber > 0:
columnNumber -= 1 # shift to zero-based
res.append(chr(ord("A") + columnNumber % 26))
columnNumber //= 26
return "".join(reversed(res))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log_26 n): the value shrinks by a factor of 26 each iteration.
💾 Space Complexity
O(log_26 n): the output string.
⚠️ Interview Pitfalls & Follow-ups
- Using plain base-26 without the
- 1:26would becomeZplus a carry, producingAZinstead ofZ. - Taking the remainder before subtracting one: every non-leading digit would be off by one.
- Building the string left to right: digits are generated least-significant first, so a reversal is needed.
- Special-casing
columnNumber % 26 == 0: the- 1trick handles that case uniformly and avoids branching.