Cells in a Range on an Excel Sheet solution and explanation
9 more videos on this problem
2194. Cells in a Range on an Excel Sheet || Leetcode Weekly Contest 283 || Leetcode 2194Bro Coders · 5:02 · 2K views
Cells in a Range on an Excel Sheet | Leetcode 2194 | Contest 283 | Easy matrix🔥🔥Coding Decoded · 4:05 · 1K views
2194. Cells in a Range on an Excel Sheet (Leetcode Easy)Programming Live with Larry · 3:46 · 730 views
LeetCode 2194. Cells in a Range on an Excel SheetProgramming Interviews Preparation · 6:43 · 386 views
Cells in a Range on an Excel Sheet - LeetCode 2194 - Java Solutionalgobest - Computer Science · 4:02 · 343 views
Solve LeetCode 2194 Quickly: Excel Range Cell Identifier Tutorial!CodingForBeginners · 10:15 · 121 views
2194 Cells in a Range on an Excel Sheet - Javascript - Time: O(n) Space: O(n) - LeetcodeAaron Sadino Coding · 26:36 · 89 views
Cells in a Range on an Excel Sheet (LeetCode 2194 problem) - Java solution guide step by stepCoding Club Lambda · 1:17 · 89 views
LeetCode 2194 | Cells in a Range on an Excel Sheet | String | JavaSleepy Cracker · 4:02 · 51 views
Cells in a Range on an Excel Sheet - LeetCode II Simple And Optimized Solution for BeginnersYour Code Buddy · 10:18 · 51 views
The problem
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where:
<col>denotes the column numbercof the cell. It is represented by alphabetical letters.- For example, the
1stcolumn is denoted by'A', the2ndby'B', the3rdby'C', and so on.
- For example, the
<row>is the row numberrof the cell. Therthrow is represented by the integerr.
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.
Example 1:
Input: s = "K1:L2" Output: ["K1","K2","L1","L2"] Explanation: The above diagram shows the cells which should be present in the list. The red arrows denote the order in which the cells should be presented.
Example 2:
Input: s = "A1:F1" Output: ["A1","B1","C1","D1","E1","F1"] Explanation: The above diagram shows the cells which should be present in the list. The red arrow denotes the order in which the cells should be presented.
Constraints:
s.length == 5'A' <= s[0] <= s[3] <= 'Z''1' <= s[1] <= s[4] <= '9'sconsists of uppercase English letters, digits and':'.
Approach overview
Problem Overview: The input is a string like "A1:C3" representing a rectangular range on an Excel sheet. You need to return every cell coordinate inside that range in lexicographic order (column first, then row). Each coordinate is formatted like A1, B2, etc.
Approach 1: Iterate through Columns and Rows (Time: O(k), Space: O(1) excluding output)
The range always contains a starting column, starting row, ending column, and ending row. Extract these four values directly from the string. Then iterate column-by-column from the start column to the end column, and inside that loop iterate row-by-row from the start row to the end row. For every pair, construct the coordinate string using the column character and row digit. This works because Excel ranges expand in a simple grid pattern, so a nested loop naturally generates the correct order.
This approach is essentially a small grid traversal. The total work depends on the number of cells in the range (k). Since the problem guarantees single-letter columns and single-digit rows, parsing is constant time and the nested iteration is straightforward. This is the most direct and commonly used solution for problems involving string parsing and simple simulation.
Approach 2: Using Cartesian Product (Time: O(k), Space: O(k))
Another way to view the problem is as a Cartesian product between the column range and the row range. First generate the list of columns (for example A, B, C) and the list of rows (1, 2, 3). Then combine every column with every row to produce the final coordinates. Many languages provide helpers for Cartesian products (such as itertools.product in Python), which makes this approach concise.
The key idea is separating the two dimensions of the grid before combining them. While the time complexity is still O(k), this version often creates intermediate lists for rows and columns, which slightly increases auxiliary memory usage. It is conceptually clean and useful when solving broader combinatorial or grid enumeration problems.
Recommended for interviews: The nested column-row iteration is what interviewers typically expect. It demonstrates clear string parsing and controlled iteration without unnecessary abstractions. The Cartesian product approach is equally correct but may feel like overengineering unless the language provides a very concise helper.
Approach 1: Iterate through Columns and Rows
This approach involves parsing the input string to extract the start and end columns and rows. We then use nested loops; the outer loop traverses through the column range, and the inner loop processes the row range. For each combination of column and row, we construct the cell name and add it to the result list.
def cellsInRange(s: str) -> [str]:
return [f'{chr(c)}{r}' for c in range(ord(s[0]), ord(s[3]) + 1) for r in range(int(s[1]), int(s[4]) + 1)]import java.util.ArrayList;
import java.util.List;
public List<String> cellsInRange(String s) {
List<String> result = new ArrayList<>();
for (char col = s.charAt(0); col <= s.charAt(3); col++) {
for (char row = s.charAt(1); row <= s.charAt(4); row++) {
result.add("" + col + row);
}
}
return result;
}#include <vector>
#include <string>
std::vector<std::string> cellsInRange(std::string s) {
std::vector<std::string> result;
for (char col = s[0]; col <= s[3]; ++col) {
for (char row = s[1]; row <= s[4]; ++row) {
result.push_back(std::string() + col + row);
}
}
return result;
}function cellsInRange(s) {
let result = [];
for (let col = s.charCodeAt(0); col <= s.charCodeAt(3); col++) {
for (let row = s[1]; row <= s[4]; row++) {
result.push(String.fromCharCode(col) + row);
}
}
return result;
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** cellsInRange(char * s, int* returnSize){
int colStart = s[0];
int colEnd = s[3];
int rowStart = s[1] - '0';
int rowEnd = s[4] - '0';
*returnSize = (colEnd - colStart + 1) * (rowEnd - rowStart + 1);
char **result = malloc(*returnSize * sizeof(char*));
int index = 0;
for (char col = colStart; col <= colEnd; col++) {
for (int row = rowStart; row <= rowEnd; row++) {
result[index] = malloc(3 * sizeof(char));
snprintf(result[index], 3, "%c%d", col, row);
index++;
}
}
return result;
}using System;
using System.Collections.Generic;
public class Solution {
public IList<string> CellsInRange(string s) {
List<string> result = new List<string>();
for (char col = s[0]; col <= s[3]; col++) {
for (char row = s[1]; row <= s[4]; row++) {
result.Add($"{col}{row}");
}
}
return result;
}
}The Python solution utilizes list comprehension with nested loops to construct the required cells in range. The chr and ord functions handle character transformations for column indices.
Time Complexity: O((c2 - c1 + 1) * (r2 - r1 + 1))
Space Complexity: O((c2 - c1 + 1) * (r2 - r1 + 1))
Approach 2: Simulation
We directly traverse all the cells within the range and add them to the answer array.
The time complexity is O(m times n), and the space complexity is O(m times n), where m and n are the range of rows and columns, respectively.
function cellsInRange(s: string): string[] {
const ans: string[] = [];
for (let i = s.charCodeAt(0); i <= s.charCodeAt(3); ++i) {
for (let j = s.charCodeAt(1); j <= s.charCodeAt(4); ++j) {
ans.push(String.fromCharCode(i) + String.fromCharCode(j));
}
}
return ans;
}func cellsInRange(s string) (ans []string) {
for i := s[0]; i <= s[3]; i++ {
for j := s[1]; j <= s[4]; j++ {
ans = append(ans, string(i)+string(j))
}
}
return
}Complexity comparison
| Approach | Complexity |
|---|---|
| Iterate through Columns and Rows | Time Complexity: O((c2 - c1 + 1) * (r2 - r1 + 1)) |
| Simulation | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterate through Columns and Rows | O(k) | O(1) | Best general solution. Simple nested loops generate cells directly in lexicographic order. |
| Cartesian Product of Rows and Columns | O(k) | O(k) | Useful when a language provides product utilities or when modeling the grid as two independent sets. |
Frequently asked questions
Is Cells in a Range on an Excel Sheet easy or hard?
Cells in a Range on an Excel Sheet is classified as an Easy problem on LeetCode with an acceptance rate above 80%. The task focuses on basic string parsing and simple nested iteration, making it a common warm-up problem for beginners practicing array or string manipulation.
Cells in a Range on an Excel Sheet Python/Java solution
Both Python and Java implementations follow the same idea: parse the four boundary characters from the range string and run nested loops over columns and rows. Python often uses character iteration with chr/ord or itertools.product, while Java typically uses char loops and string concatenation. Both achieve O(k) time complexity.
How to solve Cells in a Range on an Excel Sheet in O(n)?
Treat the Excel range as a small grid. Extract the start column, end column, start row, and end row from the string, then use two loops: the outer loop iterates columns and the inner loop iterates rows. For each pair, concatenate the column character and row digit to form the cell name. This generates all cells in O(k) time where k is the number of coordinates produced.
What is the best approach for Cells in a Range on an Excel Sheet?
The most practical solution iterates through columns and rows using nested loops. Parse the starting and ending column and row from the input string, then generate each coordinate by combining the current column and row. This runs in O(k) time where k is the number of cells in the range and uses O(1) extra space aside from the output list.
Is Cells in a Range on an Excel Sheet asked at Google/Amazon/Meta?
This problem is categorized as an easy string parsing and simulation question. Variations of grid enumeration and coordinate generation appear in interviews at companies like Amazon and Google, especially in early rounds where candidates demonstrate basic iteration and string handling skills.
What data structure is used in Cells in a Range on an Excel Sheet?
The solution primarily uses strings and a dynamic list or array to store the generated coordinates. The algorithm relies on simple iteration rather than advanced data structures, making it a straightforward string manipulation and simulation problem.
What is the time complexity of Cells in a Range on an Excel Sheet?
The time complexity is O(k), where k is the number of cells inside the specified Excel range. Each cell coordinate is generated exactly once by iterating over the column range and row range. Space complexity is O(1) auxiliary space, not counting the output list.
