Watch 10 video solutions for Excel Sheet Column Title, a easy level problem involving Math, String. This walkthrough by Knowledge Center has 34,289 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
Example 1:
Input: columnNumber = 1 Output: "A"
Example 2:
Input: columnNumber = 28 Output: "AB"
Example 3:
Input: columnNumber = 701 Output: "ZY"
Constraints:
1 <= columnNumber <= 231 - 1Problem Overview: Given a positive integer representing a column number in Excel, convert it to the corresponding column title. Excel uses a 1-indexed alphabet system: 1 → A, 2 → B, ..., 26 → Z, 27 → AA, 28 → AB.
Approach 1: Base 26 Conversion (O(log n) time, O(1) space)
This problem behaves like a base-26 number system but with a twist: digits range from 1–26 instead of 0–25. The fix is to decrement the number before each modulo operation. Repeatedly compute (n - 1) % 26 to determine the current character, map it to 'A' + remainder, append it to the result, and divide the number by 26 using integer division. Continue until the number becomes zero, then reverse the constructed string. The algorithm processes one character per iteration, so the runtime is O(log26 n), and only constant auxiliary space is used aside from the output string. This approach relies on simple arithmetic from Math and basic manipulation of a String.
Approach 2: Recursive Solution (O(log n) time, O(log n) space)
The same base‑26 idea can be expressed recursively. If the column number is zero, return an empty string. Otherwise, reduce the problem size by converting (n - 1) / 26 recursively, then append the current character derived from (n - 1) % 26. Each recursive call processes one “digit” in the Excel title representation. The recursion depth equals the number of characters in the final title, which is O(log26 n). Time complexity remains O(log n), but recursion introduces call stack overhead, giving O(log n) space complexity. This version is useful when practicing Recursion patterns or when building the string from left to right naturally.
Recommended for interviews: The iterative base‑26 conversion is the expected solution. It shows you understand the off‑by‑one detail caused by Excel’s 1-indexed alphabet mapping. Interviewers often look for the n-- adjustment before modulo. The recursive version is clean and expressive, but the iterative approach is simpler, avoids stack usage, and demonstrates stronger control over numeric conversions.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Base 26 Conversion (Iterative) | O(log n) | O(1) | Best general solution. Efficient and commonly expected in interviews. |
| Recursive Conversion | O(log n) | O(log n) | Useful for practicing recursion or when expressing base conversions recursively. |