Intuition

  • The Arabs invented the number 0.
  • This number is useful in exactly this case, since it allows for you to convert the column number to a mapping from A to Z, with A starting at 0 and Z ending at 25.
  • This is useful to avoid the edge case of getting 0, but 0 mapping to Z, which causes a bunch of problems, such as the number 1 mapping to A, but not needing A since we already found Z from the remainder being 0.

Complexity

Runtime

since we are dividing by 26 each time until we reach 0, meaning , which becomes .

Space

to store result, or if you don’t consider the result as part of the space complexity.

Code

class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        res = deque()
        while columnNumber > 0:
            columnNumber -= 1
            columnNumber, remainder = divmod(columnNumber, 26)
            res.appendleft(chr(ord('A') + remainder))
 
        return ''.join(res)

Notes

Cards

START Basic Front: Excel Sheet Column Title Back: Subtract by 1 to convert to base 26, with A starting at 0 and Z ending at 25, thereby making divmod work.

END


References

Excel Sheet Column Title