Cells in a Range on an Excel Sheet

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def cellsInRange(self, s: str) -> List[str]:
        start, end = s.split(':')
        start_col, start_row = ord(start[0]) - 64, int(start[1])
        end_col, end_row = ord(end[0]) - 64, int(end[1])

        result = []
        for col in range(start_col, end_col + 1):
            for row in range(start_row, end_row + 1):
                cell = chr(col + 64) + str(row)
                result.append(cell)
        return result

In this code:

  1. The input string s is split into start and end parts at the ‘:’ character.
  2. The column and row for start and end are separated and the ASCII value of the column character is converted to its corresponding integer (A = 1, B = 2, etc.) using ord().
  3. Empty list result is initialized to hold the resulting cell names.
  4. Two nested loops iterate over all columns and rows within the given range.
  5. For each cell in the range, its name is created by converting the column number back to a letter using chr() and appending the row number as a string.
  6. The cell name is then added to the result list.
  7. The list of all cell names within the range is returned.