Taro Logo

Excel Sheet Column Title

#234 Most AskedEasy
Topics:
StringsRecursion

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 - 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible value for the input `columnNumber`, and can it exceed standard integer limits?
  2. Is the input `columnNumber` guaranteed to be a positive integer, or should I handle invalid inputs like zero or negative numbers?
  3. Should the returned column title be strictly uppercase, as standard in Excel?
  4. Are there any memory or space complexity constraints I should keep in mind for extremely large column numbers?
  5. How should I handle extremely large inputs that might cause integer overflow in languages with fixed-size integers?

Brute Force Solution

Approach

Imagine you need to translate a number into its corresponding Excel column letters, but instead of using a clever mathematical formula, you decide to recreate the exact sequence of how columns are named in order. The brute force approach builds and checks every single letter combination from the very beginning until it matches your target number.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first single-letter column name.
  2. Compare it to your target number to see if it matches.
  3. If it does not match, move on to the next single-letter column name in alphabetical order.
  4. Once you run out of single-letter names, start checking all possible two-letter combinations in order.
  5. Continue this process, systematically trying every possible combination of letters by adding more letters whenever you reach the end of the current length.
  6. Keep a running count of each combination you test so you know when you have reached the exact position of your target number.
  7. Stop and output the letter combination the moment your running count matches the target number you were given.

Code Implementation

def convertToTitle(columnNumber):
    import itertools
    
    current_count = 0
    
    # Systematically check every possible length from 1 upwards to match the target position
    for length in range(1, 10):
        for candidate_tuple in itertools.product('ABCDEFGHIJKLMNOPQRSTUVWXYZ', repeat=length):
            current_count += 1
            
            # Stop once the running count matches the target number to ensure correct mapping
            if current_count == columnNumber:
                return ''.join(candidate_tuple)
    
    return ""

Big(O) Analysis

Time Complexity
O(26^log_26(n)) – The input size n represents the target column number we need to reach. The algorithm systematically generates every possible combination of letters starting from length one, two, three, and so on, testing them sequentially until the running count matches n. Since there are 26 single-letter options, 26 squared two-letter options, and 26 to the power of k options for length k, the total number of combinations checked grows exponentially with the length of the string. Summing up all checked combinations up to the required length k yields a geometric series bounded by approximately 26^(k+1), which scales linearly with the target number n. Therefore, the total operations approximate n, simplifying the runtime complexity to O(n).
Space Complexity
O(1) – The brute force approach as described only requires a few primitive variables to maintain the running count and to construct the current letter combination being tested. Because we generate combinations sequentially without storing previous states, the extra memory required remains constant regardless of the target number N. As the input number N grows arbitrarily large, no additional data structures like arrays or hash maps are allocated to scale with N. Therefore, the auxiliary space complexity is strictly constant at O(1).

Optimal Solution

Approach

The goal is to translate a standard counting number into its corresponding Excel column letters, which work just like a regular alphabet-based numbering system. Since Excel columns shift letters instead of using a standard zero-based placeholder, the secret is to continuously peel off the rightmost letter by shifting our perspective of the number step by step.

Here's how the algorithm would work step-by-step:

  1. Start with your given number and get ready to read the letters from right to left, because it is easiest to figure out the final letter first.
  2. Check what letter corresponds to the remainder when you divide your current number by the total number of letters in the alphabet. For instance, a remainder of one matches the first letter, and a remainder of zero matches the final letter.
  3. Record this letter as the next piece of your final answer.
  4. Shrink your main number by dividing it down to represent the remaining chunks of the alphabet, making sure to handle the shift smoothly when you hit the very end of the alphabet.
  5. Repeat this process of finding the remainder and shrinking the number until nothing is left.
  6. Finally, reverse the order of the letters you collected, because you discovered them from right to left, and you need them to read naturally from left to right.

Code Implementation

def convert_to_title(column_number):    collected_letters = []    while column_number > 0:        # Decrementing by one adjusts for 1-based indexing so modulo aligns with alphabet indices correctly.        column_number -= 1        remainder_index = column_number % 26        collected_letters.append(chr(remainder_index + ord('A')))        # Dividing by 26 shifts the number to process the next higher-order character position.        column_number //= 26    # Reversing is required because characters were extracted sequentially from right to left.    return "".join(collected_letters[::-1])

Big(O) Analysis

Time Complexity
O(log n) – The input size is the number n, and the cost is driven by the repeated division of n by 26 in each step of the loop. In every iteration, the number is shrunk by a factor of 26 as we peel off one letter at a time from right to left. The number of operations required to reduce n to zero is proportional to the number of base-26 digits it contains. This leads to a logarithmic number of steps, approximately equal to log base 26 of n, which simplifies in Big O notation to O(log n).
Space Complexity
O(log_26 N) – To analyze the auxiliary space complexity, let N be the input integer representing the Excel column number. The algorithm accumulates characters into an intermediate string or list to store the resulting column title from right to left. The number of characters generated is proportional to the number of base-26 digits in N, which grows logarithmically at a rate of log_26 N. Therefore, the extra memory used by the data structure holding the characters scales logarithmically with the input size N, simplifying to O(log N) auxiliary space.

Edge Cases

Minimum positive input of 1
How to Handle:
The modulo operation correctly maps 1 to A without requiring any special base-offset adjustments.
Exact multiples of 26 such as 26 or 52
How to Handle:
Subtracting 1 before the modulo operation prevents Z from being incorrectly represented as a zero-indexed value.
Column numbers right at the transition boundaries like 26 to 27 or 702 to 703
How to Handle:
The decrement step ensures single-digit titles shift cleanly to double-digit titles without off-by-one errors.
Maximum standard integer limits for 32-bit signed integers
How to Handle:
Using standard 64-bit integers or built-in language types prevents integer overflow during division and scaling.
Inputs with large values requiring deep multi-character titles like ZZZ
How to Handle:
The iterative division loop scales logarithmically and handles arbitrarily large numbers efficiently.
Zero or negative inputs
How to Handle:
The problem statement guarantees a positive integer, so these inputs are out of scope.
0/245 completed