Skip to content

Commit 189ff25

Browse files
authored
Create 3484-design-spreadsheet.java
1 parent 2a056e0 commit 189ff25

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* LeetCode Problem: Design Spreadsheet (Hypothetical Custom Problem)
3+
*
4+
* Problem Link: https://leetcode.com/problems/design-spreadsheet/ (⚠️ replace with actual if exists)
5+
*
6+
* Description:
7+
* Implement a simple spreadsheet where:
8+
* - You can set a cell with a numeric value.
9+
* - You can reset a cell (making its value 0).
10+
* - You can evaluate a formula string of the form "A1+B2+3", where
11+
* tokens may be integers or cell references.
12+
*
13+
* Methods:
14+
* Spreadsheet(int rows) -> initializes spreadsheet
15+
* void setCell(String cell, int value) -> sets a cell value
16+
* void resetCell(String cell) -> resets cell to 0
17+
* int getValue(String formula) -> evaluates a formula string
18+
*
19+
* Example:
20+
* Spreadsheet obj = new Spreadsheet(3);
21+
* obj.setCell("A1", 5);
22+
* obj.setCell("B1", 10);
23+
* obj.getValue("=A1+B1+3"); // returns 18
24+
* obj.resetCell("A1");
25+
* obj.getValue("=A1+B1+3"); // returns 13
26+
*
27+
* Time Complexity:
28+
* - setCell, resetCell: O(1) average (hash map put/get).
29+
* - getValue: O(k) where k = number of terms in the formula.
30+
*
31+
* Space Complexity:
32+
* - O(n) for storing n cells in the map.
33+
*/
34+
35+
import java.util.*;
36+
37+
class Spreadsheet {
38+
39+
private Map<String, Integer> cellMap = new HashMap<>();
40+
41+
public Spreadsheet(int rows) {
42+
// rows parameter can be used for validation if needed
43+
}
44+
45+
public void setCell(String cell, int value) {
46+
cellMap.put(cell, value);
47+
}
48+
49+
public void resetCell(String cell) {
50+
cellMap.put(cell, 0);
51+
}
52+
53+
public int getValue(String formula) {
54+
int sum = 0;
55+
// skip '=' at start
56+
for (String s : formula.substring(1).split("\\+")) {
57+
sum += mapToValue(s.trim());
58+
}
59+
return sum;
60+
}
61+
62+
private int mapToValue(String s) {
63+
return Character.isLetter(s.charAt(0)) ? cellMap.getOrDefault(s, 0) : Integer.parseInt(s);
64+
}
65+
}
66+
67+
/**
68+
* Your Spreadsheet object will be instantiated and called as such:
69+
* Spreadsheet obj = new Spreadsheet(rows);
70+
* obj.setCell(cell,value);
71+
* obj.resetCell(cell);
72+
* int param_3 = obj.getValue(formula);
73+
*/

0 commit comments

Comments
 (0)