Leetcode 2194: Cells in a Range on an Excel Sheet

grid47
grid47
Exploring patterns and algorithms
Apr 1, 2024 5 min read

You are given a range of cells in an Excel sheet, represented by two cell positions in the format ‘:’, where <col1> and <col2> represent the starting and ending column letters, and <row1> and <row2> represent the starting and ending row numbers. Your task is to return all the cells within the specified range, sorted first by column and then by row.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `s` representing a range of cells in the format '<col1><row1>:<col2><row2>', where `<col1>`, `<row1>`, `<col2>`, and `<row2>` are uppercase letters and digits.
Example: s = 'C2:D4'
Constraints:
• The input string is exactly 5 characters long.
• The column letters are between 'A' and 'Z'.
• The row numbers are between 1 and 9.
Output: The output should be a list of strings, each representing a cell in the range, sorted first by column and then by row.
Example: ["C2", "C3", "C4", "D2", "D3", "D4"]
Constraints:
• The output should list the cells in lexicographically sorted order.
Goal: The goal is to generate all the cells within the given range in lexicographical order.
Steps:
• 1. Extract the starting and ending columns and rows from the input string.
• 2. Iterate over the columns and rows within the specified range.
• 3. Format each cell as a string and add it to the result list.
• 4. Return the sorted list of cells.
Goal: Ensure that the input range is well-formed and falls within the expected bounds.
Steps:
• The input string will always represent a valid range.
• The row numbers will always be valid integers between 1 and 9.
• The column letters will always be uppercase English letters between 'A' and 'Z'.
Assumptions:
• The input string is guaranteed to be formatted correctly.
• The range is guaranteed to be valid with `r1 <= r2` and `c1 <= c2`.
Input: s = 'C2:D4'
Explanation: In this example, we need to generate all cells starting from column 'C' row 2 to column 'D' row 4. This includes cells 'C2', 'C3', 'C4', 'D2', 'D3', and 'D4'.

Input: s = 'A1:E2'
Explanation: In this example, we need to generate all cells from 'A1' to 'E2', which includes cells in a 2-row by 5-column grid.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus