#2194

Cells in a Range on an Excel Sheet

Easy
StringArrayString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution is similar to the brute force approach but focuses on efficiency by directly calculating the range of cells without unnecessary operations. It leverages the fact that we can compute the range directly from the parsed input.

⚙️

Algorithm

5 steps
  1. 1Step 1: Parse the input string to extract the starting and ending columns and rows.
  2. 2Step 2: Convert the column letters to their respective indices (A=1, B=2, ...).
  3. 3Step 3: Create a result list and use a single loop to iterate through the calculated range of columns and rows.
  4. 4Step 4: Format the cell as a string and add it to the result list.
  5. 5Step 5: Return the result list.
solution.py7 lines
1def cellsInRange(s):
2    start_col, start_row, end_col, end_row = s[0], int(s[1]), s[3], int(s[4])
3    result = []
4    for col in range(ord(start_col), ord(end_col) + 1):
5        for row in range(start_row, end_row + 1):
6            result.append(chr(col) + str(row))
7    return result

Complexity note: The time complexity is O(n) because we are iterating through each column and each row only once. The space complexity is O(n) due to the result list storing the cells.

  • 1Understanding how to parse and manipulate strings is crucial.
  • 2Recognizing patterns in the problem can lead to more efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.