-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path06_AdvancedDesigns.cpp
More file actions
450 lines (363 loc) · 13.5 KB
/
Copy path06_AdvancedDesigns.cpp
File metadata and controls
450 lines (363 loc) · 13.5 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
================================================================================
DESIGN - ADVANCED DATA STRUCTURES
================================================================================
Complex designs combining multiple data structures.
================================================================================
*/
#include <bits/stdc++.h>
using namespace std;
/*
PROBLEM 1: Design Twitter (LeetCode 355) ⭐ GOOGLE FAVORITE
────────────────────────────────────────────────────────────
postTweet, getNewsFeed (10 most recent), follow, unfollow
Design: HashMap for followers, HashMap for tweets, merge K sorted feeds.
Time: O(n log k) for getNewsFeed | Space: O(users * tweets)
*/
class Twitter {
int timestamp;
unordered_map<int, vector<pair<int, int>>> tweets; // userId → [(time, tweetId)]
unordered_map<int, unordered_set<int>> following; // userId → set of followed users
public:
Twitter() : timestamp(0) {}
void postTweet(int userId, int tweetId) {
tweets[userId].push_back({timestamp++, tweetId});
}
vector<int> getNewsFeed(int userId) {
// Merge tweets from user and followed users
auto cmp = [](auto& a, auto& b) { return a.first < b.first; };
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);
// Add user's own tweets
for (auto& [time, id] : tweets[userId]) {
pq.push({time, id});
}
// Add followed users' tweets
for (int followee : following[userId]) {
for (auto& [time, id] : tweets[followee]) {
pq.push({time, id});
}
}
vector<int> feed;
while (!pq.empty() && feed.size() < 10) {
feed.push_back(pq.top().second);
pq.pop();
}
return feed;
}
void follow(int followerId, int followeeId) {
if (followerId != followeeId) {
following[followerId].insert(followeeId);
}
}
void unfollow(int followerId, int followeeId) {
following[followerId].erase(followeeId);
}
};
/*
PROBLEM 2: Design Browser History (LeetCode 1472)
─────────────────────────────────────────────────
visit(url), back(steps), forward(steps)
Time: O(1) | Space: O(n)
*/
class BrowserHistory {
vector<string> history;
int current;
public:
BrowserHistory(string homepage) {
history.push_back(homepage);
current = 0;
}
void visit(string url) {
history.resize(current + 1); // Clear forward history
history.push_back(url);
current++;
}
string back(int steps) {
current = max(0, current - steps);
return history[current];
}
string forward(int steps) {
current = min((int)history.size() - 1, current + steps);
return history[current];
}
};
/*
PROBLEM 3: Design Search Autocomplete System (LeetCode 642)
───────────────────────────────────────────────────────────
input(c): Return top 3 suggestions for prefix.
Design: Trie + priority queue
Time: O(p + n log n) per query | Space: O(total chars)
*/
class AutocompleteSystem {
struct TrieNode {
TrieNode* children[27] = {}; // 26 letters + space
unordered_map<string, int> counts; // sentences with this prefix → count
};
TrieNode* root;
TrieNode* curr;
string prefix;
int charToIdx(char c) {
return c == ' ' ? 26 : c - 'a';
}
public:
AutocompleteSystem(vector<string>& sentences, vector<int>& times) {
root = new TrieNode();
curr = root;
for (int i = 0; i < sentences.size(); i++) {
addSentence(sentences[i], times[i]);
}
}
void addSentence(const string& sentence, int count) {
TrieNode* node = root;
for (char c : sentence) {
int idx = charToIdx(c);
if (!node->children[idx]) {
node->children[idx] = new TrieNode();
}
node = node->children[idx];
node->counts[sentence] += count;
}
}
vector<string> input(char c) {
if (c == '#') {
addSentence(prefix, 1);
prefix = "";
curr = root;
return {};
}
prefix += c;
int idx = charToIdx(c);
if (!curr || !curr->children[idx]) {
curr = nullptr;
return {};
}
curr = curr->children[idx];
// Get top 3
auto cmp = [](auto& a, auto& b) {
if (a.second != b.second) return a.second < b.second;
return a.first > b.first;
};
priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> pq(cmp);
for (auto& [sentence, count] : curr->counts) {
pq.push({sentence, count});
}
vector<string> result;
for (int i = 0; i < 3 && !pq.empty(); i++) {
result.push_back(pq.top().first);
pq.pop();
}
return result;
}
};
/*
PROBLEM 4: Design Excel Sum Formula (LeetCode 631)
──────────────────────────────────────────────────
set(r, c, v), get(r, c), sum(r, c, numbers): numbers like "A1:B2"
Time: O(cells) for sum | Space: O(n * m)
*/
class Excel {
vector<vector<int>> grid;
vector<vector<vector<pair<int,int>>>> formulas; // Store sum dependencies
int H, W;
pair<int, int> parseCell(const string& s) {
int col = s[0] - 'A';
int row = stoi(s.substr(1)) - 1;
return {row, col};
}
int calculateSum(int row, int col) {
int sum = 0;
for (auto& [r, c] : formulas[row][col]) {
sum += grid[r][c];
}
return sum;
}
public:
Excel(int height, char width) : H(height), W(width - 'A' + 1) {
grid.assign(H, vector<int>(W, 0));
formulas.assign(H, vector<vector<pair<int,int>>>(W));
}
void set(int row, char column, int val) {
int r = row - 1, c = column - 'A';
formulas[r][c].clear();
grid[r][c] = val;
}
int get(int row, char column) {
int r = row - 1, c = column - 'A';
if (formulas[r][c].empty()) return grid[r][c];
return calculateSum(r, c);
}
int sum(int row, char column, vector<string> numbers) {
int r = row - 1, c = column - 'A';
formulas[r][c].clear();
for (const string& s : numbers) {
size_t colon = s.find(':');
if (colon == string::npos) {
auto [pr, pc] = parseCell(s);
formulas[r][c].push_back({pr, pc});
} else {
auto [r1, c1] = parseCell(s.substr(0, colon));
auto [r2, c2] = parseCell(s.substr(colon + 1));
for (int i = r1; i <= r2; i++) {
for (int j = c1; j <= c2; j++) {
formulas[r][c].push_back({i, j});
}
}
}
}
grid[r][c] = calculateSum(r, c);
return grid[r][c];
}
};
/*
PROBLEM 5: Design Skiplist (LeetCode 1206)
──────────────────────────────────────────
Probabilistic data structure with O(log n) search, insert, delete.
Time: O(log n) average | Space: O(n)
*/
class Skiplist {
struct Node {
int val;
vector<Node*> next;
Node(int v, int level) : val(v), next(level, nullptr) {}
};
Node* head;
int maxLevel;
float probability;
int randomLevel() {
int level = 1;
while ((float)rand() / RAND_MAX < probability && level < maxLevel) {
level++;
}
return level;
}
public:
Skiplist() : maxLevel(16), probability(0.5) {
head = new Node(-1, maxLevel);
}
bool search(int target) {
Node* curr = head;
for (int i = maxLevel - 1; i >= 0; i--) {
while (curr->next[i] && curr->next[i]->val < target) {
curr = curr->next[i];
}
}
curr = curr->next[0];
return curr && curr->val == target;
}
void add(int num) {
vector<Node*> update(maxLevel, head);
Node* curr = head;
for (int i = maxLevel - 1; i >= 0; i--) {
while (curr->next[i] && curr->next[i]->val < num) {
curr = curr->next[i];
}
update[i] = curr;
}
int level = randomLevel();
Node* newNode = new Node(num, level);
for (int i = 0; i < level; i++) {
newNode->next[i] = update[i]->next[i];
update[i]->next[i] = newNode;
}
}
bool erase(int num) {
vector<Node*> update(maxLevel, head);
Node* curr = head;
for (int i = maxLevel - 1; i >= 0; i--) {
while (curr->next[i] && curr->next[i]->val < num) {
curr = curr->next[i];
}
update[i] = curr;
}
curr = curr->next[0];
if (!curr || curr->val != num) return false;
for (int i = 0; i < curr->next.size(); i++) {
update[i]->next[i] = curr->next[i];
}
delete curr;
return true;
}
};
/*
PROBLEM 6: Text Editor (LeetCode 2296)
──────────────────────────────────────
Cursor at end. addText, deleteText, cursorLeft, cursorRight.
Design: Two stacks (left and right of cursor)
Time: O(k) | Space: O(n)
*/
class TextEditor {
string left, right;
public:
void addText(string text) {
left += text;
}
int deleteText(int k) {
int deleted = min(k, (int)left.size());
left.resize(left.size() - deleted);
return deleted;
}
string cursorLeft(int k) {
while (k-- > 0 && !left.empty()) {
right += left.back();
left.pop_back();
}
return left.substr(max(0, (int)left.size() - 10));
}
string cursorRight(int k) {
while (k-- > 0 && !right.empty()) {
left += right.back();
right.pop_back();
}
return left.substr(max(0, (int)left.size() - 10));
}
};
// ============================================================================
// MAIN
// ============================================================================
int main() {
cout << "=== Advanced Designs ===\n\n";
// 1. Twitter
Twitter twitter;
twitter.postTweet(1, 5);
auto feed = twitter.getNewsFeed(1);
cout << "1. Twitter feed: ";
for (int id : feed) cout << id << " ";
cout << "\n";
// 2. Browser History
BrowserHistory browser("google.com");
browser.visit("facebook.com");
browser.visit("youtube.com");
cout << "2. Browser back(1): " << browser.back(1) << "\n";
cout << " Browser forward(1): " << browser.forward(1) << "\n";
// 5. Skiplist
Skiplist sl;
sl.add(1);
sl.add(2);
sl.add(3);
cout << "5. Skiplist search(1): " << (sl.search(1) ? "true" : "false") << "\n";
sl.erase(2);
cout << " Skiplist search(2): " << (sl.search(2) ? "true" : "false") << "\n";
// 6. Text Editor
TextEditor te;
te.addText("leetcode");
cout << "6. Text Editor delete(4): " << te.deleteText(4) << "\n";
te.addText("practice");
cout << " Left(3): " << te.cursorLeft(3) << "\n";
return 0;
}
/*
================================================================================
SUMMARY
================================================================================
+───────────────────────────────+────────────────────────────────────────────────+
| Design | Key Data Structures |
+───────────────────────────────+────────────────────────────────────────────────+
| Twitter | HashMap + HashMap + merge K sorted |
| Browser History | Vector with current pointer |
| Autocomplete | Trie + counts at each node |
| Excel | Grid + formula dependencies |
| Skiplist | Multi-level linked list |
| Text Editor | Two stacks (left and right of cursor) |
+───────────────────────────────+────────────────────────────────────────────────+
================================================================================
*/