Cells in a Range on an Excel Sheet - Problem

A cell (r, c) of an excel sheet is represented as a string <col><row> where:

  • <col> denotes the column number c of the cell. It is represented by alphabetical letters.
    • For example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on.
  • <row> is the row number r of the cell. The rth row is represented by the integer r.

You are given a string s in the format <col1><row1>:<col2><row2>, where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 ≤ r2 and c1 ≤ c2.

Return the list of cells (x, y) such that r1 ≤ x ≤ r2 and c1 ≤ y ≤ c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.

Input & Output

Example 1 — Basic Range
$ Input: s = "K1:L2"
Output: ["K1","K2","L1","L2"]
💡 Note: Start at K1, end at L2. First process column K (rows 1-2): K1, K2. Then column L (rows 1-2): L1, L2.
Example 2 — Single Cell
$ Input: s = "A1:F1"
Output: ["A1","B1","C1","D1","E1","F1"]
💡 Note: Single row across multiple columns A through F, all at row 1.
Example 3 — Single Column
$ Input: s = "A1:A3"
Output: ["A1","A2","A3"]
💡 Note: Single column A with multiple rows 1 through 3.

Constraints

  • s.length == 5
  • 'A' ≤ s[0] ≤ s[3] ≤ 'Z'
  • '1' ≤ s[1], s[2], s[4] ≤ '9'
  • s[2] == ':'
  • s[1] ≤ s[4]

Visualization

Tap to expand
Cells in a Range on an Excel Sheet INPUT s = "K1:L2" Excel Grid Representation K L 1 2 K1 L1 K2 L2 Start: K1 (col K, row 1) End: L2 (col L, row 2) col1='K' row1=1 col2='L' row2=2 ALGORITHM STEPS 1 Parse Input String Extract col1, row1, col2, row2 K1:L2 --> K,1,L,2 2 Outer Loop: Columns Iterate col from 'K' to 'L' for c in ['K','L'] 3 Inner Loop: Rows Iterate row from 1 to 2 for r in [1,2] 4 Build Cell String Concatenate col + row result.add(c + str(r)) Iteration Order: K+1=K1, K+2=K2 L+1=L1, L+2=L2 FINAL RESULT Output Array "K1" "K2" "L1" "L2" [0] [1] [2] [3] Sorting Order 1. First by column (K, L) 2. Then by row (1, 2) Output: ["K1","K2","L1","L2"] OK Key Insight: The problem requires nested iteration: outer loop over columns (alphabetically), inner loop over rows (numerically). This naturally produces the required sorting order. Time Complexity: O((c2-c1+1) * (r2-r1+1)) = O(cells in range). TutorialsPoint - Cells in a Range on an Excel Sheet | Optimal Solution Time: O(n*m) Space: O(n*m)
Asked in
Microsoft 25 Google 15
12.5K Views
Medium Frequency
~8 min Avg. Time
543 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen