#168

Excel Sheet Column Title

Easy
MathStringMathematical conversionsString manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a mathematical understanding of the base-26 number system. Instead of building the string backwards, we directly compute the characters based on the column number's value.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize an empty string to store the result.
  2. 2Step 2: While columnNumber is greater than 0, do the following:
  3. 3Step 3: Decrement columnNumber by 1 to adjust for zero-based indexing.
  4. 4Step 4: Calculate the character corresponding to the current columnNumber using modulo 26.
  5. 5Step 5: Prepend the character to the result string.
  6. 6Step 6: Update columnNumber by dividing it by 26.
solution.py7 lines
1def convertToTitle(columnNumber):
2    result = ''
3    while columnNumber > 0:
4        columnNumber -= 1
5        result = chr(columnNumber % 26 + 65) + result
6        columnNumber //= 26
7    return result

Complexity note: The time complexity is O(n) because we loop through the digits of the base-26 representation of the column number, and the space complexity is O(n) for the resulting string.

  • 1Understanding the mapping of numbers to letters is crucial, as it resembles a base-26 numeral system.
  • 2The adjustment of columnNumber by subtracting 1 is necessary to align with zero-based indexing.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.