Skip to content

Instantly share code, notes, and snippets.

@SuryaPratapK
Created September 19, 2025 13:11
Show Gist options
  • Save SuryaPratapK/d30521ad9b588bc05f4e1521bcb7bc91 to your computer and use it in GitHub Desktop.
Save SuryaPratapK/d30521ad9b588bc05f4e1521bcb7bc91 to your computer and use it in GitHub Desktop.
class Spreadsheet {
using pii = pair<int,int>;
vector<vector<int>> sheet;
pii getRowCol(string cell){
int pos = 0;
int col = -1;
if(cell[0]>='A' and cell[0]<='Z'){
col = cell[0]-'A';
pos++;
}
int row = 0;
while(pos<cell.size()){
row = row*10 + cell[pos]-'0';
pos++;
}
return {row,col};
}
public:
Spreadsheet(int rows) {
sheet.assign(rows+1,vector<int>(26));
}
void setCell(string cell, int value) {
pii row_col = getRowCol(cell);
sheet[row_col.first][row_col.second] = value;
}
void resetCell(string cell) {
pii row_col = getRowCol(cell);
sheet[row_col.first][row_col.second] = 0;
}
int getValue(string formula) {
int pos = formula.find('+');
pii row_col_left = getRowCol(formula.substr(1,pos-1));
pii row_col_right = getRowCol(formula.substr(pos+1));
int r1 = row_col_left.first;
int c1 = row_col_left.second;
int r2 = row_col_right.first;
int c2 = row_col_right.second;
int left = c1==-1? r1 : sheet[r1][c1];
int right = c2==-1? r2 : sheet[r2][c2];
return left + right;
}
};
/**
* Your Spreadsheet object will be instantiated and called as such:
* Spreadsheet* obj = new Spreadsheet(rows);
* obj->setCell(cell,value);
* obj->resetCell(cell);
* int param_3 = obj->getValue(formula);
*/
/*
//JAVA
// Spreadsheet.java
public class Spreadsheet {
private final int ROWS;
private static final int COLS = 26; // A..Z
private final int[][] sheet;
// Parse a token like "A12" or "123". Returns int[]{row, col}.
// If token is a numeric literal, col == -1 and row contains the numeric value.
private int[] getRowCol(String cell) {
if (cell == null || cell.isEmpty())
throw new IllegalArgumentException("Empty cell reference");
int pos = 0;
int col = -1;
char first = cell.charAt(0);
if (first >= 'A' && first <= 'Z') {
col = first - 'A';
pos = 1;
}
int row = 0;
while (pos < cell.length()) {
char ch = cell.charAt(pos);
if (ch < '0' || ch > '9') throw new IllegalArgumentException("Invalid character in cell");
row = row * 10 + (ch - '0');
pos++;
}
return new int[]{row, col};
}
// rows = number of rows (1-indexed); internally allocate rows+1.
public Spreadsheet(int rows) {
if (rows < 1) throw new IllegalArgumentException("rows must be >= 1");
this.ROWS = rows;
this.sheet = new int[rows + 1][COLS];
}
public void setCell(String cell, int value) {
int[] rc = getRowCol(cell);
if (rc[1] == -1) throw new IllegalArgumentException("setCell expects a cell reference (like A1)");
sheet[rc[0]][rc[1]] = value;
}
public void resetCell(String cell) {
int[] rc = getRowCol(cell);
if (rc[1] == -1) throw new IllegalArgumentException("resetCell expects a cell reference (like A1)");
sheet[rc[0]][rc[1]] = 0;
}
// Accepts formulas like "=A1+B2" or "=1+20"
public int getValue(String formula) {
if (formula == null || formula.isEmpty() || formula.charAt(0) != '=')
throw new IllegalArgumentException("Formula must start with '='");
int plusPos = formula.indexOf('+');
if (plusPos == -1) throw new IllegalArgumentException("Formula must contain '+'");
String leftToken = formula.substring(1, plusPos).trim();
String rightToken = formula.substring(plusPos + 1).trim();
int[] leftRC = getRowCol(leftToken);
int[] rightRC = getRowCol(rightToken);
int leftVal = (leftRC[1] == -1) ? leftRC[0] : sheet[leftRC[0]][leftRC[1]];
int rightVal = (rightRC[1] == -1) ? rightRC[0] : sheet[rightRC[0]][rightRC[1]];
return leftVal + rightVal;
}
// Simple self-test / usage example:
public static void main(String[] args) {
Spreadsheet s = new Spreadsheet(10);
s.setCell("A1", 5);
s.setCell("B2", 7);
System.out.println(s.getValue("=A1+B2")); // 12
System.out.println(s.getValue("=1+20")); // 21
}
}
#Python
# spreadsheet.py
class Spreadsheet:
COLS = 26 # A..Z
def __init__(self, rows: int):
if rows < 1:
raise ValueError("rows must be >= 1")
# rows are 1-indexed; allocate rows+1
self.sheet = [[0] * self.COLS for _ in range(rows + 1)]
# Parse "A12" or "123" -> (row, col). If numeric literal, col == -1.
def _get_row_col(self, cell: str):
if not cell:
raise ValueError("Empty cell reference")
pos = 0
col = -1
first = cell[0]
if 'A' <= first <= 'Z':
col = ord(first) - ord('A')
pos = 1
row = 0
while pos < len(cell):
ch = cell[pos]
if not ch.isdigit():
raise ValueError("Invalid character in cell")
row = row * 10 + (ord(ch) - ord('0'))
pos += 1
return row, col
def setCell(self, cell: str, value: int) -> None:
r, c = self._get_row_col(cell)
if c == -1:
raise ValueError("setCell expects a cell reference like 'A1'")
self.sheet[r][c] = value
def resetCell(self, cell: str) -> None:
r, c = self._get_row_col(cell)
if c == -1:
raise ValueError("resetCell expects a cell reference like 'A1'")
self.sheet[r][c] = 0
# Accepts formulas like "=A1+B2" or "=1+20"
def getValue(self, formula: str) -> int:
if not formula or formula[0] != '=':
raise ValueError("Formula must start with '='")
formula = formula.strip()
plus = formula.find('+')
if plus == -1:
raise ValueError("Formula must contain '+'")
left_token = formula[1:plus].strip()
right_token = formula[plus+1:].strip()
r1, c1 = self._get_row_col(left_token)
r2, c2 = self._get_row_col(right_token)
left_val = r1 if c1 == -1 else self.sheet[r1][c1]
right_val = r2 if c2 == -1 else self.sheet[r2][c2]
return left_val + right_val
# Usage example:
if __name__ == "__main__":
s = Spreadsheet(10)
s.setCell("A1", 5)
s.setCell("B2", 7)
print(s.getValue("=A1+B2")) # 12
print(s.getValue("=1+20")) # 21
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment