## Similar Problems

Similar Problems not available

# Excel Sheet Column Title - Leetcode Solution

LeetCode: Excel Sheet Column Title Leetcode Solution

Difficulty: Easy

Problem Statement:

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

columnNumber = 1 -> Returns "A" columnNumber = 28 -> Returns "AB"

Example 1:

Input: columnNumber = 1 Output: "A"

Example 2:

Input: columnNumber = 701 Output: "ZY"

Approach:

In this problem, we have to convert an integer column number into an Excel sheet column title. Suppose we want to convert a column number ‘n’ to its corresponding column title, the algorithm follows these steps:

- Divide the given column number by 26 and add the remainder character to the title string.
- If the remainder is zero, then the last character should be “Z” instead of “0”.
- Reduce the column number by dividing it by 26.
- Repeat steps 1 to 3 until the column number becomes zero.

For example, suppose we want to convert the column number 28 to its corresponding column title:

- 28/26 = 1 remainder 2, add the second character ‘B’ to the title string.
- Reduce the column number by 2/26 = 0. We get column number = 1.
- Since remainder is not zero, add corresponding character ‘A’ to the title string. Title string becomes “AB”.

Now let's look at the solution:

Java Code:

class Solution { public String convertToTitle(int columnNumber) { StringBuilder title = new StringBuilder(); while(columnNumber>0){ int rem = (columnNumber-1)%26; //Turning 1 to 26 to 0 to 25 title.append((char)('A'+rem)); columnNumber = (columnNumber-1)/26; //Turning back 0 to 25 to 1 to 26 } return title.reverse().toString(); } }

Python Code:

class Solution: def convertToTitle(self, columnNumber: int) -> str: title = "" while columnNumber: rem = (columnNumber-1)%26 #Turning 1 to 26 to 0 to 25 title += chr(ord('A')+rem) columnNumber = (columnNumber-1)//26 #Turning back 0 to 25 to 1 to 26 return title[::-1]

We have used StringBuilder in Java and a simple string in Python to store the title. We run a while loop until the columnNumber becomes zero. In each iteration, we calculate the remainder and add the corresponding character to the title. We also reduce the column number in each iteration. Finally, we return the reversed title string.

The time complexity of this algorithm is O(logn) as we keep dividing the column number by 26. The space complexity is also O(logn) as we store the title string, which can have a maximum length of logn.

## Excel Sheet Column Title Solution Code

`1`