Excel Sheet Column Title - Complete Solution Guide
Excel Sheet Column Title is LeetCode problem 168, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 <= 2 31 - 1
Detailed Explanation
The problem asks you to convert a given integer representing a column number in an Excel sheet to its corresponding column title. Excel column titles are represented as letters: A, B, C... Z, AA, AB, etc. The input is an integer `columnNumber` (1 <= `columnNumber` <= 2<sup>31</sup> - 1), and the output is a string representing the Excel column title. For example, 1 corresponds to "A", 28 corresponds to "AB", and 701 corresponds to "ZY".
Solution Approach
The solution uses a base-26 conversion algorithm. The input integer `columnNumber` is repeatedly divided by 26. The remainder of each division represents a letter (A-Z) where 0 corresponds to Z, 1 corresponds to A, and so on. These letters are concatenated to form the final column title. The provided solutions differ slightly in how they handle the letter mapping and string building; some use string concatenation directly, while others use a StringBuilder (Java) for improved efficiency.
Step-by-Step Algorithm
- Step 1: Initialize an empty string or StringBuilder to store the result.
- Step 2: Repeat until `columnNumber` becomes 0:
- Step 3: Decrement `columnNumber` by 1 (to adjust for 0-based indexing of A-Z).
- Step 4: Calculate the remainder when `columnNumber` is divided by 26. This remainder represents the next letter in the column title. Convert the remainder to its corresponding letter (A-Z) using ASCII values (e.g., 'A' + remainder).
- Step 5: Prepend (or append and later reverse) this letter to the result string.
- Step 6: Update `columnNumber` by integer division with 26 (`columnNumber //= 26`).
- Step 7: Return the result string.
Key Insights
- Insight 1: The problem can be solved using a base-26 number system (similar to base-10, but with 26 digits). Each digit represents a letter from A to Z.
- Insight 2: Converting from base-26 requires repeated division by 26 and taking the remainder. The remainders represent the digits in the base-26 representation.
- Insight 3: The order of digits obtained from the remainders needs to be reversed to form the correct column title. (Or, string concatenation is done from left to right).
Complexity Analysis
Time Complexity: O(logN)
Space Complexity: O(logN)
Topics
This problem involves: Math, String.
Companies
Asked at: Accenture, Oracle, Yext, Zenefits, Zoho.