cswork / libraryOpen practice workspace

Coding questions · Houzz

Convert a Column Number to an Excel-Style Label

Convert one-based spreadsheet columns into A-through-Z and AA-through-ZZ labels, with correct handling of multiples of 26.

Convert a one-based spreadsheet column number into its Excel-style column label. Columns 1 through 26 are A through Z; column 27 is AA, and the sequence continues through ZZ at column 702.

Implement column_label(n: int) -> string and return the label as an uppercase string.

Constraints & Assumptions

  • n is an integer in the inclusive range 1 through 702.
  • This is a column label only; do not append a row number.
  • The numbering is one-based. There is no zero digit and no label for column zero.
  • The input is valid; error handling for out-of-range values is outside this callable's contract.

Examples

  • column_label(26) returns "Z".
  • column_label(27) returns "AA".

Hint: Account for the missing zero digit

Before taking a remainder by 26, align the current one-based position with the zero-based offsets used to select letters from A through Z.

Convert a Column Number to an Excel-Style Label

Hints

  1. Check labels on each side of a 26-column boundary.

Approach

At each step subtract one to convert the current one-based position to a zero-based offset. The remainder modulo 26 identifies the final letter; the quotient is the remaining prefix position. Each iteration removes precisely the last letter of the desired label, so reversing the collected letters produces the label in order. The loop ends when no prefix remains. The stated range needs at most two letters.

  • Time complexity: O(log_26 n), bounded by two iterations in this domain
  • Space complexity: O(log_26 n) for the output, at most two letters