[LeetCode] Design SQL

2408. Design SQL

You are given n tables represented with two arrays names and columns, where names[i] is the name of the ith table and columns[i] is the number of columns of the ith table.

You should be able to perform the following operations:

  • Insert a row in a specific table. Each row you insert has an id. The id is assigned using an auto-increment method where the id of the first inserted row is 1, and the id of each other row inserted into the same table is the id of the last inserted row (even if it was deleted) plus one.
  • Delete a row from a specific table. Note that deleting a row does not affect the id of the next inserted row.
  • Select a specific cell from any table and return its value.

Implement the SQL class:

  • SQL(String[] names, int[] columns) Creates the n tables.
  • void insertRow(String name, String[] row) Adds a row to the table namerow is equal to the number of columns in the table.
  • void deleteRow(String name, int rowId) Removes the row rowId from the table name
  • String selectCell(String name, int rowId, int columnId) Returns the value of the cell in the row rowId and the column columnId from the table name.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class SQL {
unordered_map<string, int> ids;
unordered_map<string, vector<vector<string>>> table;
int incr(string name) {
int id = ids[name];
ids[name] += 1;
return id;
}
public:
SQL(vector<string>& names, vector<int>& columns) {
for(int i = 0; i < names.size(); i++) {
string name = names[i];
ids[name] = 1;
table[name].push_back(vector<string>(columns[i]));
}
}

void insertRow(string name, vector<string> row) {
if(!ids.count(name)) return;
int id = incr(name);
table[name].push_back(row);
}

void deleteRow(string name, int rowId) {
if(!table.count(name)) return;
if(table[name].size() <= rowId) return;
table[name][rowId] = {};
}

string selectCell(string name, int rowId, int columnId) {
if(!table.count(name)) return "";
if(table[name].size() <= rowId) return "";
if(table[name][rowId].size() < columnId) return "";
return table[name][rowId][columnId-1];
}
};

/**
* Your SQL object will be instantiated and called as such:
* SQL* obj = new SQL(names, columns);
* obj->insertRow(name,row);
* obj->deleteRow(name,rowId);
* string param_3 = obj->selectCell(name,rowId,columnId);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/01/PS/LeetCode/design-sql/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.