-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemporaryQuestionsPracticeSpace.cpp
More file actions
1341 lines (1119 loc) · 24.6 KB
/
TemporaryQuestionsPracticeSpace.cpp
File metadata and controls
1341 lines (1119 loc) · 24.6 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 <vector>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <algorithm>
#include <queue>
// Dutch national flag problem
class DutchSorter
{
private:
std::vector<int>& arr;
public:
DutchSorter(std::vector<int>& a)
: arr(a)
{
}
void sort()
{
int ptr0 = 0; // points to end of zeros
int ptr1 = 0; // points to end of ones
int high = arr.size() - 1; // end of array
// The pointers will eventually look like this
// 0....0 1.......1 2....2
// | |
// ptr0 ptr1
// Our goal is to make sure the position of ptr1 is correct
while (ptr1 <= high)
{
if (arr[ptr1] == 0)
{
// If 0 is at the position of 1, swap it with 1
// We know ptr1 will always point to 1
std::swap(arr[ptr1], arr[ptr0]);
++ptr0;
++ptr1; // ptr1 is always after ptr0
} else if (arr[ptr1] == 1) {
++ptr1;
} else {
// If 2 is at the position of 1, swap it
// However, we don't know what value we picked up from the
// end -> it could be 0 or 1. So, we just reduce high
std::swap(arr[ptr1], arr[high]);
high--;
}
}
int x = 5;
}
void print()
{
for (int iter : arr)
{
std::cout << iter << " ";
}
std::cout << std::endl;
}
};
// String interleaving problem
class StringInterleaver
{
private:
const std::string& first_str;
const std::string& second_str;
int combinedLength;
public:
StringInterleaver(const std::string& f, const std::string& s)
: first_str(f), second_str(s)
{
combinedLength = first_str.length() + second_str.length();
}
void combine()
{
std::string output;
std::unordered_set<std::string> result;
combineHelper(output, first_str, second_str, result);
for (const std::string& iter : result)
{
std::cout << iter << std::endl;
}
}
private:
void combineHelper(std::string result, const std::string first, const std::string second, std::unordered_set<std::string>& list)
{
//std::cout << "first: " << first << " second: " << second << std::endl;
if (first.empty() && second.empty())
{
list.insert(result);
return;
}
if (!first.empty())
combineHelper(result + first[0], first.substr(1), second, list);
if (!second.empty())
combineHelper(result + second[0], first, second.substr(1), list);
}
};
// Print all substrings of a string
class Substring
{
public:
void compute(const std::string& str)
{
for (int i = 0; i < str.length(); ++i)
{
computeHelper(str.substr(i));
}
}
private:
void computeHelper(std::string str)
{
if (str.empty())
return;
for (int i = 1; i <= str.length(); ++i)
{
std::cout << str.substr(0, i) << std::endl;
}
}
};
// Combination of words from digits : https://www.techiedelight.com/possible-combinations-replacing-given-digits-corresponding-list/
class Combinations
{
private:
const std::vector<std::vector<char>>& chars;
const std::vector<int>& keys;
std::unordered_map<int, char> map;
public:
Combinations(const std::vector<std::vector<char>>& c, const std::vector<int>& k)
: chars(c), keys(k)
{
}
void compute()
{
std::string result;
helper(0, result);
}
private:
void helper(int start, std::string result)
{
if (start == keys.size())
{
std::cout << result << std::endl;
return;
}
std::vector<char> current = chars[keys[start]];
if (map.find(keys[start]) == map.end())
{
for (int i = 0; i < current.size(); ++i)
{
char curr = current[i];
map[keys[start]] = curr;
helper(start + 1, result + curr);
// Backtrack
map.erase(keys[start]);
}
} else {
helper(start + 1, result + map[keys[start]]);
}
}
};
// String reversal
class ReverseString
{
private:
std::string& str;
public:
ReverseString(std::string& s)
: str(s)
{
}
void performWithStack()
{
std::stack<std::string> stack;
int low = 0;
int high = 0;
for (int i = 0; i < str.length(); ++i)
{
if (str[i] == ' ')
{
// Word separator
if (low == 0)
{
// Add space before first word
stack.push(" " + str.substr(low, high - low + 1));
} else {
stack.push(str.substr(low, high - low + 1));
}
low = i;
high = i;
} else {
high = i;
}
}
// Last word (remove the first space and then append)
stack.push(str.substr(low + 1, high - low));
int len = str.length();
std::string str1;
str1.reserve(len);
while (!stack.empty())
{
str1.append(stack.top());
stack.pop();
}
std::cout << "Reversed string is: " << std::endl;
std::cout << str1 << std::endl;
}
void performWithoutStack()
{
int low = 0;
int high = 0;
for (int i = 0; i < str.length(); ++i)
{
// Reverse each word
if (str[i] == ' ')
{
std::reverse(str.begin() + low, str.begin() + high + 1);
low = i + 1;
high = i + 1;
} else {
high = i;
}
}
// Reverse last word
std::reverse(str.begin() + low, str.begin() + high + 1);
// Reverse whole string
std::reverse(str.begin(), str.end());
std::cout << "Reversed string is: " << std::endl;
std::cout << str << std::endl;
}
};
// Combinatios of numbers of certain length
class NumericCombinations
{
private:
const std::vector<int>& arr;
int r;
public:
NumericCombinations(const std::vector<int>& a, int length)
: arr(a), r(length)
{
}
void find()
{
std::vector<int> combinations;
helper(combinations, 0);
}
private:
void helper(std::vector<int> combinations, int start)
{
if (combinations.size() == r)
{
for (int j : combinations)
{
std::cout << j << " ";
}
std::cout << std::endl;
return;
}
for (int i = start; i < arr.size(); ++i)
{
combinations.push_back(arr[i]);
helper(combinations, i + 1);
if (!combinations.empty())
combinations.pop_back();
}
}
};
// Maximize value of expression:
// A[s] - A[r] + A[q] - A[p]
// s > r > q > p
class ValueMaximizer
{
private:
const std::vector<int>& arr;
public:
ValueMaximizer(const std::vector<int>& a)
: arr(a)
{
}
int compute()
{
// Compute maximum value for A[s]
std::vector<int> A_S(arr.size(), 0);
A_S[0] = arr[0];
for (int i = 1; i < A_S.size(); ++i)
A_S[i] = std::max(arr[i], A_S[i - 1]);
int max_A_S = A_S[A_S.size() - 1];
// Compute maximum value for maxAs - A[r] = maxAsMinusAr
// We shrink the size by 1 because, (A[s]) - A[r] can only be done
// for all values less than s.
std::vector<int> A_R(arr.size() - 1, 0);
A_R[0] = arr[0] - max_A_S;
for (int i = 1; i < A_R.size(); ++i)
A_R[i] = std::max(A_R[i - 1], max_A_S - arr[i]);
int max_A_R = A_R[A_R.size() - 1];
// Compute maximum value for maxAsMinusAr + A[q] = maxAsMinusArPlusAq
// We shrink the size by 1 because, (A[s] - A[r]) + A[q] can only be done
// for all values less than r
std::vector<int> A_Q(arr.size() - 2, 0);
A_Q[0] = max_A_R + arr[0];
for (int i = 1; i < A_Q.size(); ++i)
A_Q[i] = std::max(A_Q[i - 1], max_A_R + arr[i]);
int max_A_Q = A_Q[A_Q.size() - 1];
// Compute maximum value for maxAsMinusArPlusAq - A[p] = maxAsMinusArPlusAqMinusAp
std::vector<int> A_P(arr.size() - 3, 0);
A_P[0] = max_A_Q - arr[0];
for (int i = 1; i < A_P.size(); ++i)
A_P[i] = std::max(A_P[i - 1], max_A_Q - arr[i]);
return A_P[A_P.size() - 1];
}
};
// String decoding
class StringDecoder
{
private:
const std::string& pattern;
std::string result;
public:
StringDecoder(const std::string& p)
: pattern(p)
{
}
std::string compute()
{
int curr_indx = 0;
while (curr_indx < pattern.size())
{
if (isNumber(curr_indx))
{
std::string substr;
curr_indx = processNum(curr_indx, substr);
result.append(substr);
} else {
result.append(1, pattern[curr_indx]);
++curr_indx;
}
}
return result;
}
private:
int processNum(int curr_indx, std::string &substr)
{
std::string numstr;
int times = 0;
while (pattern[curr_indx] >= '0' && pattern[curr_indx] <= '9')
{
numstr.append(1, pattern[curr_indx++]);
}
times = std::stoi(numstr);
return replicate(curr_indx + 1, times, substr);
}
bool isNumber(int curr_index)
{
return pattern[curr_index] >= '0' && pattern[curr_index] <= '9';
}
int endParen(int curr, std::string& substr)
{
if (pattern[curr] == ']')
return curr + 1;
if (isNumber(curr))
{
std::string sub;
int stop_indx = processNum(curr, sub);
substr.append(sub);
return endParen(stop_indx, substr);
} else {
substr.append(1, pattern[curr]);
return endParen(curr + 1, substr);
}
}
int replicate(int curr, int times, std::string& substr)
{
int end = endParen(curr, substr);
int count = 0;
int len = substr.length();
while (count < times - 1)
{
substr.append(substr.substr(0, len));
++count;
}
return end;
}
};
// Circular rotations
class CircularRotations
{
private:
const std::vector<int>& arr;
public:
CircularRotations(const std::vector<int>& a)
: arr(a)
{
}
int compute()
{
// We need to find index of smallest element. This element
// will have previous and next values greater than it
int low = 0;
int high = arr.size() - 1;
while (low <= high)
{
if (arr[low] <= arr[high])
return low;
int mid = low + (high - low) / 2;
int next = (mid + 1) % arr.size();
int prev = (mid - 1 + arr.size()) % arr.size();
if ((arr[mid] <= arr[prev]) && (arr[mid] <= arr[next]))
{
return mid;
} else if (arr[mid] >= arr[low]) {
// Left side is sorted, so look at right
low = mid + 1;
} else if (arr[mid] <= arr[high]) {
// Right side is sorted
high = mid - 1;
}
}
return -1;
}
};
// Fibonacci
int fibonacci(int n)
{
int first = 1;
int second = 1;
int third = 0;
for (int i = 2; i < n; ++i)
{
// 1, 1, 2, 3, 5, 8, ...
// f = 1 and s = 1
// third = f + s
// For the next number, f will be
// current third and s will be current
// f
third = first + second;
second = first;
first = third;
}
return third;
}
// kth smallest element in BST
class Node1 {
public:
int data;
Node1* left;
Node1* right;
};
class BinarySearchTree1
{
private:
Node1* root;
public:
BinarySearchTree1()
: root(nullptr)
{
std::vector<int> arr{15, 10, 8, 12, 20, 16, 25};
for (auto iter : arr)
{
insert(iter);
}
}
~BinarySearchTree1()
{
cleanup(root);
}
void insert(int data)
{
insertHelper(root, data);
}
int kthSmallest(int k)
{
Node1* temp = nullptr;
int foundIndex = 0;
kthSmallestHelper(temp, foundIndex, root, k);
if (temp == nullptr)
return -1;
return temp->data;
}
int kthLargest(int k)
{
Node1* temp = nullptr;
int foundIndex = 0;
kthLargestHelper(temp, foundIndex, root, k);
if (temp == nullptr)
return -1;
return temp->data;
}
private:
void kthLargestHelper(Node1*&found, int& foundIndex, Node1* current, int target)
{
if (current == nullptr)
return;
// Traverse right subtree
kthLargestHelper(found, foundIndex, current->right, target);
// Now we have the largest element
foundIndex = foundIndex + 1;
if (foundIndex == target)
{
found = current;
}
// If we have found the node, stop recursing
if (found != nullptr)
return;
// Traverse left subtree
kthLargestHelper(found, foundIndex, current->left, target);
}
void kthSmallestHelper(Node1*&found, int& foundIndex, Node1* current, int target)
{
if (current == nullptr)
return;
// Traverse left subtree
kthSmallestHelper(found, foundIndex, current->left, target);
// Now we have the smallest element
foundIndex = foundIndex + 1;
if (foundIndex == target)
{
found = current;
}
// If we have found the node, stop recursing
if (found != nullptr)
return;
// Traverse right subtree
kthSmallestHelper(found, foundIndex, current->right, target);
}
void insertHelper(Node1*& currnode, int data)
{
if (currnode == nullptr)
{
currnode = new Node1({ data, nullptr, nullptr });
} else {
if (data < currnode->data)
{
insertHelper(currnode->left, data);
} else {
insertHelper(currnode->right, data);
}
}
}
void cleanup(Node1*& currnode)
{
if (currnode)
{
cleanup(currnode->left);
cleanup(currnode->right);
//std::cout << "Deleting " << currnode->data << std::endl;
delete currnode;
currnode = nullptr;
}
}
};
// Duplicate element finder
// https://www.geeksforgeeks.org/find-duplicates-constant-array-elements-0-n-1-o1-space/
class DuplicateElementFinder
{
private:
const std::vector<int>& arr;
public:
DuplicateElementFinder(const std::vector<int>& a)
: arr(a)
{
// Every array value correspons to element link
}
int find()
{
int slow = arr[0];
int fast = arr[arr[0]];
// Check if cycle exists
while (slow != fast)
{
slow = arr[slow];
fast = arr[arr[fast]];
}
// Check entry point
fast = 0;
while (slow != fast)
{
slow = arr[slow];
fast = arr[fast];
}
return fast;
}
};
// Left view of binary tree
class LeftViewBinaryTree
{
private:
Node1* root;
public:
LeftViewBinaryTree()
: root(nullptr)
{
create(root, 1);
create(root->left, 2);
create(root->left->right, 4);
create(root->right, 3);
create(root->right->left, 5);
create(root->right->right, 6);
create(root->right->left->left, 7);
create(root->right->left->right, 8);
}
~LeftViewBinaryTree()
{
cleanup(root);
}
void view()
{
std::queue<Node1*> queue;
queue.push(root);
while (!queue.empty())
{
size_t count = queue.size();
size_t idx = count;
while (idx > 0)
{
Node1* top = queue.front();
queue.pop();
if (idx == count)
std::cout << top->data << " ";
if (top->left)
queue.push(top->left);
if (top->right)
queue.push(top->right);
--idx;
}
}
std::cout << std::endl;
}
private:
void create(Node1*& curr, int data)
{
curr = new Node1({data, nullptr, nullptr});
}
void cleanup(Node1*& curr)
{
if (curr)
{
cleanup(curr->left);
cleanup(curr->right);
delete curr;
curr = nullptr;
}
}
};
// Combinations of words with english alphabets
class EnglishAlphabetWords
{
private:
const std::string alphabets;
std::vector<int>& digits;
public:
EnglishAlphabetWords(std::vector<int>& d)
: alphabets("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), digits(d)
{
}
void compute()
{
std::string output;
helper(0, output);
}
private:
void helper(int start, std::string result)
{
if (start == digits.size())
{
std::cout << result << std::endl;
return;
}
int length = 1;
int dig_count = 0;
int pow_of_ten = 0;
for (int i = start; i < digits.size(); ++i)
{
// Only combinations of 1 and 2 are allowed because alphabets only range from
// 1 to 26
if (length <= 2)
{
dig_count = std::pow(10, pow_of_ten)*dig_count + digits[i];
if (dig_count >= 1 && dig_count <= 26)
{
helper(i + 1, result + alphabets[dig_count - 1]);
}
}
++length;
++pow_of_ten;
}
}
};
// Linked list reversal
struct Node2
{
int data;
Node2* right;
};
class LinkedListReversal
{
private:
Node2* head;
public:
LinkedListReversal()
: head(nullptr)
{
const std::vector<int> arr{ 1, 2, 3, 4, 5 };
for (int j : arr)
{
insert(head, j);
}
}
~LinkedListReversal()
{
cleanup(head);
}
void print()
{
Node2* temp = head;
while (temp)
{
std::cout << temp->data << " ";
temp = temp->right;
}
std::cout << std::endl;
}
void reverse()
{
Node2* prev = nullptr;
reverseHelper(head, prev);
}
private:
void reverseHelper(Node2*& curr, Node2*& prev)
{
if (curr)
{
Node2* current = curr;
Node2* next = current->right;
reverseHelper(next, current);
if (next == nullptr) // We have reached the last element which will become the new head
head = current;
current->right = prev;
}
}
void insert(Node2*& curr, int data)
{
if (curr == nullptr)
{
create(curr, data);
} else {
insert(curr->right, data);
}
}
void create(Node2*& curr, int data)
{
curr = new Node2({data, nullptr});
}
void cleanup(Node2*& curr)
{
if (curr)
{
cleanup(curr->right);
delete curr;
curr = nullptr;
}
}
};
// Preorder traversal of binary tree
class PreorderTreeTraversal
{
private:
Node1* root;
public:
PreorderTreeTraversal()
: root(nullptr)
{
create(root, 1);
create(root->left, 2);
create(root->left->left, 4);
create(root->right, 3);
create(root->right->left, 5);
create(root->right->right, 6);
create(root->right->left->left, 7);
create(root->right->left->right, 8);
}
~PreorderTreeTraversal()
{
cleanup(root);
}
void print()
{
std::stack<Node1*> stack;
stack.push(root);
while (!stack.empty())
{
Node1* top = stack.top();
stack.pop();
std::cout << top->data << " ";
// Push in the opposite direction in which you want to traverse
// This is because, if you insert left first and then right, the
// top of the stack will contain the most recently inserted - the previous
// right position and that is not what you want
if (top->right)
stack.push(top->right);
if (top->left)
stack.push(top->left);
}
std::cout << std::endl;
}
private:
void create(Node1*& curr, int data)
{
curr = new Node1({ data, nullptr, nullptr });
}
void cleanup(Node1*& curr)
{
if (curr)
{
cleanup(curr->left);
cleanup(curr->right);
delete curr;
curr = nullptr;
}
}
};
// Quick sort
class QuickSorter
{
private:
std::vector<int>& arr;
public: