algoadvance

Leetcode 168. Excel Sheet Column Title

Problem Statement

Given a positive 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 
...

Clarifying Questions

  1. What is the range of columnNumber that we need to handle?
    • The value of columnNumber will be a positive integer and can be assumed to be within typical integer bounds for coding contests.
  2. Is the output case sensitive?
    • Yes, Excel column titles are always uppercase.

Code

public class ExcelColumnTitle {
    public static String convertToTitle(int columnNumber) {
        StringBuilder columnTitle = new StringBuilder();

        while (columnNumber > 0) {
            columnNumber--; // adjust columnNumber to be zero-indexed
            int remainder = columnNumber % 26;
            columnTitle.append((char) ('A' + remainder));
            columnNumber = columnNumber / 26;
        }

        return columnTitle.reverse().toString();
    }

    public static void main(String[] args) {
        // Test examples
        System.out.println(convertToTitle(1)); // Output: A
        System.out.println(convertToTitle(28)); // Output: AB
        System.out.println(convertToTitle(701)); // Output: ZY
    }
}

Strategy

  1. Adjust to Zero-Indexed: Decrement columnNumber by 1. This adjustment helps in handling the 1-based index system used in the problem description.
  2. Compute the Remainder and Character: Extract the last character of the column title by taking modulo 26 of the columnNumber. This will give a number between 0 and 25, which corresponds to characters ‘A’ to ‘Z’.
  3. Build Title: Append the character to a StringBuilder.
  4. Update Column Number: Divide the columnNumber by 26 to handle the next ‘digit’ in the sequence.
  5. Reverse the String: After the loop, reverse the accumulated characters in StringBuilder because the characters were appended in a reverse order.

Time Complexity

The problem is approached in a straightforward and efficient manner, using basic operations and a string builder for constructing the final result. This ensures that the solution is both easy to understand and optimal for the given constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI