Repository navigation
Expand file tree
/
Copy pathLeetCode4.cpp
More file actions
5763 lines (4590 loc) · 142 KB
/
Copy pathLeetCode4.cpp
File metadata and controls
5763 lines (4590 loc) · 142 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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <algorithm>
#include <typeinfo>
#include <cctype>
#include <climits>
#include <utility>
#include <cmath>
#include <numeric>
#include <iterator>
#include <functional>
#include <vector>
#include <array>
#include <list>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <tuple>
using namespace std;
// Data Structures
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
// July 2026
// 2812. Find the Safest Path in a Grid, Dijkstra, Multi-Source BFS & Greedy
int maximumSafenessFactor(vector<vector<int>> &grid) {
const int size = grid.size();
vector<vector<int>> dirs = { {0, -1}, {0, 1}, {-1, 0}, {1, 0} };
vector<vector<int>> safeDist(size, vector<int>(size, 1e9));
queue<pair<int, int>> q;
// Multi-Source BFS
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
if(grid[i][j] == 1) {
q.push( {i, j} );
safeDist[i][j] = 0;
}
}
}
// Multi-Source BFS for all theives, Visited not needed as 1e9 check is there
while(!q.empty()) {
auto [x, y] = q.front();
q.pop();
for(vector<int> &dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if(nx >= 0 && nx < size && ny >= 0 && ny < size && safeDist[nx][ny] == 1e9) {
safeDist[nx][ny] = 1 + safeDist[x][y];
q.push( {nx, ny} );
}
}
}
// Reverse Dijkstra
vector<vector<int>> dist(size, vector<int>(size, -1));
// { safeDist, x, y } -> pq vector
priority_queue<array<int, 3>> pq;
dist[0][0] = safeDist[0][0];
pq.push( {dist[0][0], 0, 0} );
while(!pq.empty()) {
auto [d, x, y] = pq.top();
pq.pop();
// Destination reached
if(x == size-1 && y == size-1) {
return d;
}
// No need to update, pq duplicate problem
if(d < dist[x][y]) {
continue;
}
for(vector<int> &dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if(nx >= 0 && nx < size && ny >= 0 && ny < size) {
// Dist will act as weight, we move greedly
// If we are on 10 and we can go to 7 or 9, we would choose 9.
int nextDist = safeDist[nx][ny];
if(min(d, nextDist) > dist[nx][ny]) {
dist[nx][ny] = min(d, nextDist);
pq.push( {dist[nx][ny], nx, ny} );
}
}
}
}
return dist[size-1][size-1];
}
// 3286. Find a Safe Walk Through a Grid, Dijkstra
bool findSafeWalk(vector<vector<int>> &grid, int health) {
const int rSize = grid.size();
const int cSize = grid[0].size();
vector<vector<int>> dirs = { {0, -1}, {0, 1}, {-1, 0}, {1, 0} };
vector<vector<int>> dist(rSize, vector<int>(cSize, 1e9));
priority_queue<array<int, 3>, vector<array<int, 3>>, greater<>> pq;
dist[0][0] = grid[0][0];
pq.push( {grid[0][0], 0, 0} );
// Dijkstra
while(!pq.empty()) {
auto [d, x, y] = pq.top();
pq.pop();
// Destination
if(x == rSize-1 && y == cSize-1) {
return dist[rSize-1][cSize-1] < health;
}
// Priority queue duplicates
if(dist[x][y] < d) {
continue;
}
for(vector<int> &dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if(nx >= 0 && nx < rSize && ny >= 0 && ny < cSize) {
// Cost of jumping from {x, y} -> {nx, ny} is wt
// Weight of grid[nx][ny] is its value itself
int nd = d + grid[nx][ny];
if(nd < dist[nx][ny]) {
dist[nx][ny] = nd;
pq.push( {nd, nx, ny} );
}
}
}
}
return dist[rSize-1][cSize-1] < health;
}
// 3620. Network Recovery Pathways, Shortest Path DAG & BSA
int findMaxPathScore(vector<vector<int>> &edges, vector<bool> &online, long long k) {
const int n = online.size();
vector<vector<pair<int, long long>>> graph(n);
vector<int> inDegree(n, 0);
vector<int> topo;
queue<int> q;
// Constructing graph and inDegree
for(vector<int> &e: edges) {
graph[e[0]].push_back( {e[1], e[2]} );
inDegree[e[1]]++;
}
// Where inDegree is 0, push that in to queue
for(int i = 0; i < n; i++) {
if(inDegree[i] == 0) {
q.push(i);
}
}
// Topo-Sort
while(!q.empty()) {
int node = q.front();
q.pop();
topo.push_back(node);
for(auto &[nbr, wt]: graph[node]) {
inDegree[nbr]--;
if(inDegree[nbr] == 0) {
q.push(nbr);
}
}
}
// DAG shortest graph
auto check = [&](int limit) {
const long long INF = 1e14;
vector<long long> dp(n, INF);
dp[0] = 0;
for(int &u: topo) {
if(dp[u] == INF) {
continue;
}
else if(u != 0 && u != n-1 && !online[u]) {
continue;
}
for(auto &[v, wt] : graph[u]) {
// Weight is atleast 7, we need min of weight so the least weight should be limit
if(wt < limit) {
continue;
}
else if(v != n-1 && !online[v]) {
continue;
}
int nwt = dp[u] + wt;
if(nwt < dp[v]) {
dp[v] = nwt;
}
}
}
return dp[n-1] <= k;
};
// BSA
int low = 0;
int high = 1e9;
int ans = -1;
while(low <= high) {
int mid = low + ((high - low) / 2);
if(check(mid)) {
ans = mid;
low = mid + 1;
}
else {
high = mid - 1;
}
}
return ans;
}
// 2492. Minimum Score of a Path Between Two Cities, BFS
int minScore(int n, vector<vector<int>> &roads) {
int ans = 1e9;
vector<vector<pair<int, int>>> graph(n);
vector<bool> visited(n , false);
queue<int> q;
// Constructing graph
for(vector<int> &r: roads) {
int u = r[0] - 1;
int v = r[1] - 1;
int wt = r[2];
graph[u].push_back({v, wt});
graph[v].push_back({u, wt});
}
// First element for queue
q.push(0);
visited[0] = true;
// BFS
while(!q.empty()) {
int node = q.front();
q.pop();
for(auto &[nbr, wt]: graph[node]) {
// We only need all connected roads and want to find the min of all roads
ans = min(ans, wt);
if(!visited[nbr]) {
q.push(nbr);
visited[nbr] = true;
}
}
}
return ans;
}
// 1301. Number of Paths with Max Score
// Memoization
pair<int, int> pathsWithMaxScoreMemo(int i, int j, const int mod, vector<string> &board, vector<vector<pair<int, int>>> &dp) {
// Base Case
if(i < 0 || j < 0 || board[i][j] == 'X') {
return {-1, 0};
}
if(i == 0 && j == 0) {
return {0, 1};
}
if(dp[i][j].first != -1e9) {
return dp[i][j];
}
// Ways to traverse
pair<int, int> left = pathsWithMaxScoreMemo(i, j-1, mod, board, dp);
pair<int, int> up = pathsWithMaxScoreMemo(i-1, j, mod, board, dp);
pair<int, int> diagonal = pathsWithMaxScoreMemo(i-1, j-1, mod, board, dp);
int maxScore = max({left.first, up.first, diagonal.first});
// Dead-End
if(maxScore == -1) {
return dp[i][j] = {-1, 0};
}
// Ways to reach E
int ways = 0;
if(left.first == maxScore) {
ways = (ways + left.second) % mod;
}
if(up.first == maxScore) {
ways = (ways + up.second) % mod;
}
if(diagonal.first == maxScore) {
ways = (ways + diagonal.second) % mod;
}
// Adding current score
maxScore += (board[i][j] - '0');
return dp[i][j] = {maxScore, ways};
}
// Tabulation
vector<int> pathsWithMaxScoreTab(vector<string> &board) {
const int mod = 1e9 + 7;
const int size = board.size();
vector<vector<pair<int, int>>> dp(size, vector<pair<int, int>>(size, {-1, 0}));
// Changing S to 0 and E to 0
board[size-1][size-1] = '0';
board[0][0] = '0';
// Known values
dp[0][0] = {0, 1};
for(int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
if((board[i][j] == 'X') || (i == 0 && j == 0)) {
continue;
}
// Ways to traverse
pair<int, int> left = {-1, 0};
pair<int, int> up = {-1, 0};
pair<int, int> diagonal = {-1, 0};
// Valid moves
if(j-1 >= 0) {
left = dp[i][j-1];
}
if(i-1 >= 0) {
up = dp[i-1][j];
}
if(i-1 >= 0 && j-1 >= 0) {
diagonal = dp[i-1][j-1];
}
int maxScore = max({left.first, up.first, diagonal.first});
// Dead-End
if(maxScore == -1) {
dp[i][j] = {-1, 0};
continue;
}
// Ways to reach E
int ways = 0;
if(left.first == maxScore) {
ways = (ways + left.second) % mod;
}
if(up.first == maxScore) {
ways = (ways + up.second) % mod;
}
if(diagonal.first == maxScore) {
ways = (ways + diagonal.second) % mod;
}
// Adding current score
maxScore += (board[i][j] - '0');
dp[i][j] = {maxScore, ways};
}
}
auto [maxScore, ways] = dp[size-1][size-1];
return (maxScore == -1) ? (vector<int> {0, 0}) : (vector<int> {maxScore, ways});
}
// Tabulation SO
vector<int> pathsWithMaxScoreTabSO(vector<string> &board) {
const int mod = 1e9 + 7;
const int size = board.size();
vector<pair<int, int>> prev(size, {-1, 0});
// Changing S to 0 and E to 0
board[size-1][size-1] = '0';
board[0][0] = '0';
// Known value
prev[0] = {0, 1};
for(int i = 0; i < size; i++) {
vector<pair<int, int>> curr(size, {-1, 0});
// Known value
if(i == 0) {
curr[0] = {0, 1};
}
for(int j = 0; j < size; j++) {
if((board[i][j] == 'X') || (i == 0 && j == 0)) {
continue;
}
// Ways to traverse
pair<int, int> left = {-1, 0};
pair<int, int> up = {-1, 0};
pair<int, int> diagonal = {-1, 0};
// Valid moves
if(j-1 >= 0) {
left = curr[j-1];
}
if(i-1 >= 0) {
up = prev[j];
}
if(i-1 >= 0 && j-1 >= 0) {
diagonal = prev[j-1];
}
int maxScore = max({left.first, up.first, diagonal.first});
// Dead-End
if(maxScore == -1) {
curr[j] = {-1, 0};
continue;
}
// Ways to reach E
int ways = 0;
if(left.first == maxScore) {
ways = (ways + left.second) % mod;
}
if(up.first == maxScore) {
ways = (ways + up.second) % mod;
}
if(diagonal.first == maxScore) {
ways = (ways + diagonal.second) % mod;
}
// Adding current score
maxScore += (board[i][j] - '0');
curr[j] = {maxScore, ways};
}
// Updation
swap(prev, curr);
}
auto [maxScore, ways] = prev[size-1];
return (maxScore == -1) ? (vector<int> {0, 0}) : (vector<int> {maxScore, ways});
}
vector<int> pathsWithMaxScore(vector<string> &board) {
// Memoization
// const int mod = 1e9 + 7;
// const int size = board.size();
// // Changing S to 0
// board[size-1][size-1] = '0';
// vector<vector<pair<int, int>>> dp(size, vector<pair<int, int>>(size, {-1e9, 0}));
// auto [maxScore, ways] = pathsWithMaxScoreMemo(size-1, size-1, mod, board, dp);
// return (maxScore == -1) ? (vector<int> {0, 0}) : (vector<int> {maxScore, ways});
// Tabulation
// return pathsWithMaxScoreTab(board);
// Tabulation SO
return pathsWithMaxScoreTabSO(board);
}
// 1288. Remove Covered Intervals, Sorting
int removeCoveredIntervals(vector<vector<int>> &intervals) {
const int size = intervals.size();
int ans = 1;
// Sorting according to largest range
sort(intervals.begin(), intervals.end(),
[](const vector<int> &a, const vector<int> &b) {
if(a[0] == b[0]) {
return a[1] > b[1];
}
return a[0] < b[0];
}
);
// First element's end after sorting, start will always be less or equal so no need to check
int maxEnd = intervals[0][1];
for(int i = 1; i < size; i++) {
// Condition
if(intervals[i][1] > maxEnd) {
maxEnd = intervals[i][1];
ans++;
}
}
return ans;
}
// 3754. Concatenate Non-Zero Digits and Multiply by Sum I, Basics
long long sumAndMultiply(int n) {
long long sum = 0;
long long num = 0;
string s = to_string(n);
for(char &ch: s) {
long long digit = ch - '0';
if(digit != 0) {
num *= 10;
num += digit;
sum += digit;
}
}
return num * sum;
}
// 3756. Concatenate Non-Zero Digits and Multiply by Sum II, Prefix
vector<int> sumAndMultiply(string &s, vector<vector<int>> &queries) {
const int size = s.size();
const int qSize = queries.size();
const int mod = 1e9 + 7;
vector<int> ans(qSize);
// Num, No. of digits, Sum
vector<long long> prefVal(size + 1);
vector<int> prefDigits(size + 1);
vector<long long> prefSum(size + 1);
vector<long long> power(size + 1, 1);
// Calculating prefixes
for(int i = 1; i <= size; i++) {
int digit = s[i-1] - '0';
prefVal[i] = prefVal[i-1];
prefDigits[i] = prefDigits[i-1];
prefSum[i] = prefSum[i-1] + digit;
power[i] = (power[i-1] * 10) % mod;
if(digit != 0) {
prefVal[i] = ((prefVal[i-1] * 10) + digit) % mod;
prefDigits[i]++;
}
}
// Queries
for(int i = 0; i < qSize; i++) {
int l = queries[i][0];
int r = queries[i][1];
// Calculations
int len = prefDigits[r + 1] - prefDigits[l];
// 10203004, for [1, 3] -> 1 & 12, to get (020 i.e 2) we need to minus 10 from 12
long long start = (prefVal[l] * power[len]) % mod;
long long end = prefVal[r+1];
// + mod for overflow due to power[len]
long long num = (end - start + mod) % mod;
long long sum = prefSum[r+1] - prefSum[l];
ans[i] = (num * sum) % mod;
}
return ans;
}
// 3532. Path Existence Queries in a Graph I, Sub Graph/Components of graph checking
vector<bool> pathExistenceQueries1(int n, vector<int> &nums, int maxDiff, vector<vector<int>> &queries) {
const int size = queries.size();
vector<bool> ans(size);
vector<int> subGraph(n);
// Same Sub-Graph means connected to each other, reaching any node means reaching the other node
for(int i = 1; i < n; i++) {
// Assuming to be on same Sub-Graph
subGraph[i] = subGraph[i-1];
// Sub-Graph change
if(nums[i] - nums[i-1] > maxDiff) {
subGraph[i]++;
}
}
// Check same Sub-Graph
for(int i = 0; i < size; i++) {
int l = queries[i][0];
int r = queries[i][1];
ans[i] = (subGraph[l] == subGraph[r]);
}
return ans;
}
// 3534. Path Existence Queries in a Graph II, Binary Lifting (Trees and Graph)
vector<int> pathExistenceQueries2(int n, vector<int> &nums, int maxDiff, vector<vector<int>> &queries) {
const int size = queries.size();
vector<int> ans(size);
vector<pair<int, int>> arr(n);
// Distance sorting
for(int i = 0; i < n; i++) {
arr[i] = {nums[i], i};
}
sort(arr.begin(), arr.end());
// After sorting to know which num is on what index of arr we create a map
vector<int> mp(n);
for(int i = 0; i < n; i++) {
// Original index to index on arr
mp[arr[i].second] = i;
}
// Taking log value to know max no. of jumps
int log = 1;
// 1 shifted log times is (1 << log)
while((1 << log) <= n) {
log++;
}
// Binary Lifting
vector<vector<int>> up(n, vector<int>(log));
// Using two pointers as {1, 2, 4, 6}, if 1->6 max then, 2 can also jump to 6, so no need to calculate it again
int r = 0;
// Filling first row, 2^0 jumps i.e 1 jump like know values part from DP
for(int l = 0; l < n; l++) {
// If diff keeps exceeding maxDiff and that no. reaches itself in diff calculation
if(r < l) {
r = l;
}
while( (r + 1 < n) && (arr[r+1].first - arr[l].first <= maxDiff) ) {
r++;
}
up[l][0] = r;
}
// Fill like DP
// j = 1 means r jumps 2 time and j = 2 means r jumps 4 times
for(int j = 1; j < log; j++) {
for(int i = 0; i < n; i++) {
// 2^j = 2^(j-1) + 2^(j-1)
// a = b + c, a wants to jump j times
// a will jump to 2^(j-1) i.e to b and ask b how far it will jump with 2^(j-1) jumps
up[i][j] = up[up[i][j-1]][j-1];
}
}
// Queries
int t = 0;
for(vector<int> &q: queries) {
int src = mp[q[0]];
int dest = mp[q[1]];
// Equal
if(src == dest) {
ans[t++] = 0;
continue;
}
// Swap
if(src > dest) {
swap(src, dest);
}
int curr = src;
int jumps = 0;
for(int i = log-1; i >= 0; i--) {
// We are going to less than destination, last jump remains
if(up[curr][i] < dest) {
curr = up[curr][i];
jumps += (1 << i);
}
}
// Cant Reach
if(up[curr][0] < dest) {
ans[t++] = -1;
}
// 5, 7, 8, 9, if dest is 8 and from 5 we can jump to 9 then we can jump to 8 as well
else {
ans[t++] = jumps + 1;
}
}
return ans;
}
// 1483. Kth Ancestor of a Tree Node, Binary Lifting (Trees and Graph)
class TreeAncestor {
public:
int log;
vector<vector<int>> up;
TreeAncestor(int n, vector<int> &parent) {
// Taking log value to know max no. of jumps
log = 1;
while((1 << log) <= n) {
log++;
}
// Binary Lifting
up = vector<vector<int>> (n, vector<int>(log));
// First ancestors, similar to know values of DP
for(int i = 0; i < n; i++) {
up[i][0] = parent[i];
}
// Fill like DP
for(int j = 1; j < log; j++) {
for(int i = 0; i < n; i++) {
int a = up[i][j-1];
// For -1 as ancestor
up[i][j] = (a == -1) ? -1 : up[a][j-1];
}
}
}
int getKthAncestor(int node, int k) {
for(int i = log-1; i >= 0; i--) {
int powerOf2 = (1 << i);
// Checking power of 2 and no. of jumps
if(powerOf2 <= k) {
node = up[node][i];
k -= powerOf2;
// Cant move further backwards
if(node == -1) {
return -1;
}
}
}
return node;
}
};
// 2685. Count the Number of Complete Components, BFS
int countCompleteComponents(int n, vector<vector<int>> &edges) {
int ans = 0;
vector<vector<int>> adjList(n);
vector<bool> visited(n, false);
queue<int> q;
// Constructing adjList
for(vector<int> &e: edges) {
adjList[e[0]].push_back(e[1]);
adjList[e[1]].push_back(e[0]);
}
for(int i = 0; i < n; i++) {
// BFS for all components
if(!visited[i]) {
int totalNodes = 0;
int totalEdges = 0;
visited[i] = true;
q.push(i);
while(!q.empty()) {
int node = q.front();
q.pop();
totalNodes++;
totalEdges += adjList[node].size();
for(int &nbr: adjList[node]) {
if(!visited[nbr]) {
visited[nbr] = true;
q.push(nbr);
}
}
}
// Required edges formula
int reqEdges = totalNodes * (totalNodes - 1) / 2;
// Edges were counted twice due to adjList
totalEdges /= 2;
// Condition
if(reqEdges == totalEdges) {
ans++;
}
}
}
return ans;
}
// 1331. Rank Transform of an Array, Map
vector<int> arrayRankTransform(vector<int> &arr) {
const int size = arr.size();
int rank = 1;
int lastUsed = INT_MIN;
vector<int> ans = arr;
sort(ans.begin(), ans.end());
unordered_map<int, int> mp;
// Ranking
for(int &val: ans) {
if(val != lastUsed) {
mp[val] = rank++;
lastUsed = val;
}
}
// Storing ans
for(int i = 0; i < size; i++) {
ans[i] = mp[arr[i]];
}
return ans;
}
// 1291. Sequential Digits, Basics
vector<int> sequentialDigits(int low, int high) {
vector<int> ans;
for(int i = 1; i < 9; i++) {
int num = i;
// Generating sequence
for(int digit = i+1; digit <= 9; digit++) {
num *= 10;
num += digit;
if(low <= num && num <= high) {
ans.push_back(num);
}
}
}
// Sorting
sort(ans.begin(), ans.end());
return ans;
}
// 3336. Find the Number of Subsequences With Equal GCD, 3D-DP, GCD
// Memoization
long long subsequencePairCountMemo(int i, int gcd1, int gcd2, const int MOD, vector<int> &nums, vector<vector<vector<long long>>> &dp) {
// Base Case
if(i >= nums.size()) {
// if either gcd1 or gcd2 goes it not pick condition, they remain 0
// gcd(0, x) = abs(x)
return (gcd1 > 0 && gcd2 > 0 && gcd1 == gcd2) ? 1 : 0;
}
if(dp[i][gcd1][gcd2] != -1) {
return dp[i][gcd1][gcd2];
}
// Exclude
long long exclude = subsequencePairCountMemo(i+1, gcd1, gcd2, MOD, nums, dp);
// Include in seq1
long long include1 = subsequencePairCountMemo(i+1, gcd(gcd1, nums[i]), gcd2, MOD, nums, dp);
// Include in seq2
long long include2 = subsequencePairCountMemo(i+1, gcd1, gcd(gcd2, nums[i]), MOD, nums, dp);
return dp[i][gcd1][gcd2] = (exclude + include1 + include2) % MOD;
}
int subsequencePairCount(vector<int> &nums) {
// Memoization
const int size = nums.size();
const int MOD = 1'000'000'007;
// GCD cant be more than 200
vector<vector<vector<long long>>> dp(size, vector<vector<long long>>(201, vector<long long>(201, -1)));
return (int) subsequencePairCountMemo(0, 0, 0, MOD, nums, dp);
}
// 3658. GCD of Odd and Even Sums, Maths, GCD
int gcdOfOddEvenSums(int n) {
// Using sum of digits
int totalSum = n * ((2 * n) + 1);
int evenSum = n * (n+1);
return gcd(totalSum - evenSum, evenSum);
}
// 3867. Sum of GCD of Formed Pairs, Prefix, GCD
long long gcdSum(vector<int> &nums) {
const int size = nums.size();
int maxi = 0;
long long ans = 0;
vector<int> prefixGCD(size, 0);
// Prefix GCD
for(int i = 0; i < size; i++) {
maxi = max(maxi, nums[i]);
prefixGCD[i] = gcd(maxi, nums[i]);
}
// Sorting
sort(prefixGCD.begin(), prefixGCD.end());
// Pair forming
for(int i = 0, j = size-1; i < j; i++, j--) {
ans += gcd(prefixGCD[i], prefixGCD[j]);
}
return ans;
}
// 3312. Sorted GCD Pair Queries, GCD &
// 1979. Find Greatest Common Divisor of Array, GCD
int findGCD(vector<int> &nums) {
int mini = 1e9;
int maxi = -1e9;
// Min and max element
for(int &val: nums) {
mini = min(mini, val);
maxi = max(maxi, val);
}
return gcd(mini, maxi);
}
// 1081. Smallest Subsequence of Distinct Characters, 316. Remove Duplicate Letters, Stack/Deque
string smallestSubsequence(string s) {
const int size = s.size();
string ans = "";
vector<int> last(26, -1);
vector<bool> inStack(26, false);
stack<char> st;
// Storing last index
for(int i = 0; i < size; i++) {
last[s[i] - 'a'] = i;
}
// Traversing string
for(int i = 0; i < size; i++) {
char ch = s[i];
// Already in stack
if(inStack[ch - 'a']) {
continue;
}
// Lexiographical check
while(!st.empty() && last[st.top() - 'a'] >= i && ch < st.top()) {
inStack[st.top() - 'a'] = false;
st.pop();
}
st.emplace(ch);
inStack[ch - 'a'] = true;
}
// Making string
while(!st.empty()) {
ans += st.top();
st.pop();
}
reverse(ans.begin(), ans.end());