We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Cells in a Range on an Excel Sheet

Number: 2304

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a string representing a rectangular range of cells on an Excel sheet (formatted as ":"), return a list of all cell names within that range. Each cell is represented as a string with its column (as an uppercase letter) followed by its row (as a digit). The cells must be returned in increasing order first by column and then by row.


Key Insights

  • The input string can be split into two parts: the starting cell and the ending cell.
  • The column letters can be iterated by converting from character to its ASCII code.
  • The row values are simple integers; iterate in a standard numeric loop.
  • The final list is generated using two nested loops: one for columns and one for rows.

Space and Time Complexity

Time Complexity: O(C * R), where C is the number of columns in the range and R is the number of rows. Space Complexity: O(C * R), which is needed to store the resulting list of cell strings.


Solution

We first extract the starting and ending cell parts from the input string. For the columns, we convert the letters to their ASCII values and iterate from the start character to the end character inclusively. For each column letter, we iterate through the row numbers (which are given as digits) from the starting row to the ending row. For every combination, we concatenate the column letter and the row number to form the cell string and add it to the result list. This iterates through every cell in the defined range in the required order.


Code Solutions

# Define the function to generate the range of cells
def cellsInRange(s: str) -> list:
    # Extract start and end parts of the string like "K1" and "L2"
    start, end = s.split(':')
    
    # Unpack the starting and ending cell properties
    start_col, start_row = start[0], int(start[1])
    end_col, end_row = end[0], int(end[1])
    
    result = []
    # Iterate over columns from start to end using ASCII values
    for col in range(ord(start_col), ord(end_col) + 1):
        # Iterate over rows from start to end
        for row in range(start_row, end_row + 1):
            # Convert the current column number back to character and combine with row
            result.append(chr(col) + str(row))
    return result

# Example usage:
print(cellsInRange("K1:L2"))
← Back to All Questions