-
Notifications
You must be signed in to change notification settings - Fork 0
/
CodilityAlgorithmsAllInOne.cpp
1554 lines (1344 loc) · 52.2 KB
/
CodilityAlgorithmsAllInOne.cpp
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
// Lesson 1
// Iterations
// -------------------------------------------------
// 1. BinaryGap.
/**
* A binary gap within a positive integer N is any maximal sequence of consecutive zeros
* that is surrounded by ones at both ends in the binary representation of N.
*
* Write a function:
* class Solution { public int solution(int N); }
* that, given a positive integer N, returns the length of its longest binary gap.
* The function should return 0 if N doesn't contain a binary gap.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [1..2,147,483,647].
*/
#include <algorithm>
int binaryGap(int N)
{
int lastOne = 32,
answer = 0;
// Iterate through each bit of N from the least significant bit to the most significant bit.
for (int i = 0; i < 32; ++i) {
// Check if the current bit is set (equal to 1).
if (N & (1 << i)) {
// Calculate the length of the binary gap between the current set bit and the previous set bit.
answer = std::max(answer, i - lastOne - 1);
lastOne = i;
}
}
return answer;
}
// Lesson 2
// Arrays
// -------------------------------------------------
// 1. CyclicRotation.
/**
* An array A consisting of N integers is given.
* Rotation of the array means that each element is shifted right by one index,
* and the last element of the array is moved to the first place.
*
* For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]
* (elements are shifted right by one index and 6 is moved to the first place).
*
* The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
*
* Write a function:
* class Solution { public int[] solution(int[] A, int K); }
* that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
*
* Assume that:
* • N and K are integers within the range [0..100];
* • each element of array A is an integer within the range [−1,000..1,000].
* In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
*/
#include <vector>
std::vector<int> cyclicRotation(std::vector<int>& A, int K)
{
if (A.empty() || !K) {
return A;
}
// Calculate the effective rotation amount.
K %= A.size();
// Rotate the vector elements by k positions to the right.
std::rotate(std::rbegin(A), std::rbegin(A) + K, std::rend(A));
return A;
}
// 2. OddOccurrencesInArray.
/**
* A non-empty array A consisting of N integers is given.
* The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value,
* except for one element that is left unpaired.
*
* For example, in array A such that:
* A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9
* • the elements at indexes 0 and 2 have value 9,
* • the elements at indexes 1 and 3 have value 3,
* • the elements at indexes 4 and 6 have value 9,
* • the element at index 5 has value 7 and is unpaired.
*
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.
*
* Write an efficient algorithm for the following assumptions:
* • N is an odd integer within the range [1..1,000,000];
* • each element of array A is an integer within the range [1..1,000,000,000];
* • all but one of the values in A occur an even number of times.
*/
#include <vector>
int oddOccurrencesInArray(std::vector<int>& A)
{
int unpairedElement = 0;
for (int num : A) {
// Perform bitwise XOR operation with the current element.
// XOR operation cancels out paired elements and keeps the unpaired element.
unpairedElement ^= num;
}
return unpairedElement;
}
// Lesson 3
// Time Complexity
// -------------------------------------------------
/**
* A small frog wants to get to the other side of the road.
* The frog is currently located at position X and wants to get to a position greater than or equal to Y.
* The small frog always jumps a fixed distance, D.
*
* Count the minimal number of jumps that the small frog must perform to reach its target.
*
* Write a function:
* class Solution { public int solution(int X, int Y, int D); }
* that, given three integers X, Y and D,
* returns the minimal number of jumps from position X to a position equal to or greater than Y.
*
* Write an efficient algorithm for the following assumptions:
* • X, Y and D are integers within the range [1..1,000,000,000];
* • X ≤ Y.
*/
#include <cmath>
int frogJmp(int X, int Y, int D)
{
// Divide the distance to be covered (Y - X) by the distance of each jump (D).
// Use std::ceil to round up the result to the nearest integer.
// This ensures that the frog reaches or surpasses the target position.
return std::ceil((Y - X) / (double)D);
}
// 2. PermMissingElem.
/**
* An array A consisting of N different integers is given.
* The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
*
* Your goal is to find that missing element.
*
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given an array A, returns the value of the missing element.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [0..100,000];
* • the elements of A are all distinct;
* • each element of array A is an integer within the range [1..(N + 1)].
*/
#include <vector>
int permMissingElem(std::vector<int>& A)
{
const int n = A.size();
int missingElement = n + 1;
// XOR all the elements in the vector and the consecutive integers.
for (int i = 0; i < n; ++i) {
missingElement ^= A[i] ^ (i + 1);
}
return missingElement;
}
// 3. TapeEquilibrium.
/**
* A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.
*
* Any integer P, such that 0 < P < N, splits this tape into two non-empty parts:
* A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
*
* The difference between the two parts is the value of:
* |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
*
* In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
*
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [2..100,000];
* • each element of array A is an integer within the range [−1,000..1,000].
*/
#include <cmath>
#include <numeric>
#include <vector>
#include <algorithm>
int tapeEquilibrium(std::vector<int>& A)
{
int minDifference = std::numeric_limits<int>::max(),
length = (int)A.size(),
sumLeftPart = 0,
sumRightPart = 0,
totalSum = std::accumulate(std::begin(A), std::end(A), 0);
for (int i = 0; i < length - 1; ++i) {
sumLeftPart += A[i];
sumRightPart = totalSum - sumLeftPart;
minDifference = std::min(minDifference, std::abs(sumLeftPart - sumRightPart));
}
return minDifference;
}
// Lesson 4
// Counting Elements
// -------------------------------------------------
// 1. FrogRiverOne.
/**
* A small frog wants to get to the other side of a river.
* The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X + 1).
* Leaves fall from a tree onto the surface of the river.
*
* You are given an array A consisting of N integers representing the falling leaves.
* A[K] represents the position where one leaf falls at time K, measured in seconds.
*
* The goal is to find the earliest time when the frog can jump to the other side of the river.
* The frog can cross only when leaves appear at every position across the river from 1 to X
* (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves).
* You may assume that the speed of the current in the river is negligibly small,
* i.e. the leaves do not change their positions once they fall in the river.
*
* Write a function:
* class Solution { public int solution(int X, int[] A); }
* that, given a non-empty array A consisting of N integers and integer X,
* returns the earliest time when the frog can jump to the other side of the river.
* If the frog is never able to jump to the other side of the river, the function should return −1.
*
* Write an efficient algorithm for the following assumptions:
* • N and X are integers within the range [1..100,000];
* • each element of array A is an integer within the range [1..X].
*/
#include <vector>
int frogRiverOne(int X, std::vector<int>& A)
{
std::vector<bool> leafPositions(X, false);
int jumpCount = 0;
const int length = (int)A.size();
for (int sec = 0; sec < length; ++sec) {
int pos = A[sec];
// If the leaf position is greater than X, skip it.
if (pos > X) {
continue;
}
// If this leaf position has not been encountered before, mark it as encountered.
if (!leafPositions[pos - 1]) {
leafPositions[pos - 1] = true;
// If the frog has covered all positions from 1 to X, return the current second.
if (++jumpCount == X) {
return sec;
}
}
}
return -1;
}
// 2. PermCheck.
/**
* A non-empty array A consisting of N integers is given.
* A permutation is a sequence containing each element from 1 to N once, and only once.
*
* For example, array A such that:
* A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2
* is a permutation, but array A such that:
* A[0] = 4 A[1] = 1 A[2] = 3
* is not a permutation, because value 2 is missing.
*
* The goal is to check whether array A is a permutation.
*
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given an array A, returns 1 if array A is a permutation and 0 if it is not.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [1..100,000];
* • each element of array A is an integer within the range [1..1,000,000,000].
*/
#include <vector>
int permCheck(std::vector<int>& A)
{
int N = (int)A.size(),
result = 0;
for (int i = 0; i < N; ++i) {
// Perform an XOR operation on the expected values from 1 to N and the values in the array A.
// XOR (^) is used to check if all values from 1 to N are present in A only once.
result ^= (i + 1) ^ A[i];
}
return !result;
}
// 3. MaxCounters.
/**
* You are given N counters, initially set to 0, and you have two possible operations on them:
* • increase(X) − counter X is increased by 1,
* • max counter − all counters are set to the maximum value of any counter.
*
* A non-empty array A of M integers is given. This array represents consecutive operations:
* • if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
* • if A[K] = N + 1 then operation K is max counter.
*
* For example, given integer N = 5 and array A such that:
* A[0] = 3
* A[1] = 4
* A[2] = 4
* A[3] = 6
* A[4] = 1
* A[5] = 4
* A[6] = 4
*
* the values of the counters after each consecutive operation will be:
* (0, 0, 1, 0, 0)
* (0, 0, 1, 1, 0)
* (0, 0, 1, 2, 0)
* (2, 2, 2, 2, 2)
* (3, 2, 2, 2, 2)
* (3, 2, 2, 3, 2)
* (3, 2, 2, 4, 2)
*
* The goal is to calculate the value of every counter after all operations.
*
* Write a function:
* class Solution { public int[] solution(int N, int[] A); }
* that, given an integer N and a non-empty array A consisting of M integers,
* returns a sequence of integers representing the values of the counters.
* Result array should be returned as an array of integers.
*
* Write an efficient algorithm for the following assumptions:
* • N and M are integers within the range [1..100,000];
* • each element of array A is an integer within the range [1..N + 1].
*/
#include <vector>
#include <algorithm>
std::vector<int> maxCounters(int N, std::vector<int>& A)
{
std::vector<int> result(N, 0);
int max = 0, curMax = 0; // Keep track of the maximum value and current maximum.
for (int i : A) {
if (i > N) {
// If the value in A is greater than N, it means it's a "max counter" operation.
// Set the 'max' variable to the current maximum value of counters.
max = curMax;
} else {
// If the value in A is in the range [1, N], it's an "increase(X)" operation.
// Update the value in the 'result' vector accordingly.
result[i - 1] = result[i - 1] < max ? max + 1 : ++result[i - 1];
curMax = std::max(curMax, result[i - 1]);
}
}
// After processing all operations, some counters may still be less than 'max'.
// Transform the 'result' vector to ensure that all counters have a minimum value of 'max'.
std::transform(std::cbegin(result), std::cend(result), std::begin(result), [max](int i) {
return i < max ? max : i;
});
return result;
}
// 4. MissingInteger.
/**
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given an array A of N integers,
* returns the smallest positive integer (greater than 0) that does not occur in A.
*
* For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [1..100,000];
* • each element of array A is an integer within the range [−1,000,000..1,000,000].
*/
#include <vector>
#include <algorithm>
int missingInteger(std::vector<int>& A)
{
int min = 1;
// Sort the array A in ascending order.
std::sort(std::begin(A), std::end(A));
for (int i : A) {
if (i == min) {
min++;
} else if (i > min) {
return min;
}
}
return min;
}
// Lesson 5
// Prefix Sums
// -------------------------------------------------
// 1. PassingCars.
/**
* A non-empty array A consisting of N integers is given.
* The consecutive elements of array A represent consecutive cars on a road.
* Array A contains only 0s and/or 1s:
* • 0 represents a car traveling east,
* • 1 represents a car traveling west.
*
* The goal is to count passing cars.
* We say that a pair of cars (P, Q), where 0 ≤ P < Q < N,
* is passing when P is traveling to the east and Q is traveling to the west.
*
* For example, consider array A such that:
* A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1
*
* We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
*
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given a non-empty array A of N integers,
* returns the number of pairs of passing cars.
*
* The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [1..100,000];
* • each element of array A is an integer that can have one of the following values: 0, 1.
*/
#include <vector>
int passingCars(std::vector<int>& A)
{
int carsTravelingEast = 0,
carPasses = 0;
for (int i : A) {
if (!i) {
carsTravelingEast++;
} else if (i == 1) {
carPasses += carsTravelingEast;
if (carPasses > 1000000000) {
return -1;
}
}
}
return carPasses;
}
// 2. CountDiv.
/**
* Write a function:
* class Solution { public int solution(int A, int B, int K); }
* that, given three integers A, B and K,
* returns the number of integers within the range [A..B] that are divisible by K, i.e.:
* { i : A ≤ i ≤ B, i mod K = 0 }
*
* For example, for A = 6, B = 11 and K = 2, your function should return 3,
* because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
*
* Write an efficient algorithm for the following assumptions:
* • A and B are integers within the range [0..2,000,000,000];
* • K is an integer within the range [1..2,000,000,000];
* • A ≤ B.
*/
int countDiv(int A, int B, int K)
{
if (A % K) {
// If A is not divisible by K, increment A to the next multiple of K.
A += (K - A % K);
}
// Reduce B to the largest multiple of K not exceeding B.
B -= B % K;
// Divide the range size by K and add 1 to account for the first multiple.
return (B - A) / K + 1;
}
// Lesson 6
// Sorting
// -------------------------------------------------
// 1. Distinct.
/**
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given an array A consisting of N integers,
* returns the number of distinct values in array A.
*
* For example, given array A consisting of six elements such that:
* A[0] = 2 A[1] = 1 A[2] = 1
* A[3] = 2 A[4] = 3 A[5] = 1
* the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [0..100,000];
* • each element of array A is an integer within the range [−1,000,000..1,000,000].
*/
#include <vector>
#include <unordered_set>
int distinct(std::vector<int>& A)
{
return (int)std::unordered_set<int>(std::begin(A), std::end(A)).size();
}
// 2. MaxProductOfThree.
/**
* A non-empty array A consisting of N integers is given.
* The product of triplet (P, Q, R) equates to A[P] * A[Q] * A[R] (0 ≤ P < Q < R < N).
*
* For example, array A such that:
* A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6
*
* contains the following example triplets:
* • (0, 1, 2), product is −3 * 1 * 2 = −6
* • (1, 2, 4), product is 1 * 2 * 5 = 10
* • (2, 4, 5), product is 2 * 5 * 6 = 60
*
* Your goal is to find the maximal product of any triplet.
*
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given a non-empty array A,
* returns the value of the maximal product of any triplet.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [3..100,000];
* • each element of array A is an integer within the range [−1,000..1,000].
*/
#include <vector>
#include <algorithm>
int maxProductOfThree(std::vector<int>& A)
{
int n = (int)A.size();
if (n < 3) {
return 0;
}
// Sort the input vector in ascending order.
std::sort(std::begin(A), std::end(A));
// The maximum product of the 3 elements in a sorted vector can take on one of 4 values:
// 1. Multiplying the first 3 elements.
// 2. Multiplying the last 3 elements (which may signify the highest positive values).
// 3. Multiplying the first element with the last 2 elements.
// 4. Multiplying the first 2 elements with the last element
// (accounting for the potential scenario of 2 first large negative values becoming positive when multiplied
// and also multiplied with the last positive value).
int tripletProduct1 = A[0] * A[1] * A[2],
tripletProduct2 = A[n - 1] * A[n - 2] * A[n - 3],
tripletProduct3 = A[0] * A[n - 1] * A[n - 2],
tripletProduct4 = A[0] * A[1] * A[n - 1];
return std::max(std::max(tripletProduct1, tripletProduct2),
std::max(tripletProduct3, tripletProduct4));
}
// 3. Triangle.
/**
* An array A consisting of N integers is given.
* A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and:
* • A[P] + A[Q] > A[R],
* • A[Q] + A[R] > A[P],
* • A[R] + A[P] > A[Q].
*
* For example, consider array A such that:
* A[0] = 10 A[1] = 2 A[2] = 5
* A[3] = 1 A[4] = 8 A[5] = 20
* Triplet (0, 2, 4) is triangular.
*
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given an array A consisting of N integers,
* returns 1 if there exists a triangular triplet for this array and returns 0 otherwise.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [0..100,000];
* • each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
*/
#include <vector>
#include <algorithm>
int triangle(std::vector<int>& A)
{
const unsigned int N = A.size();
if (N < 3) {
return 0;
}
std::vector<long> ordered(std::begin(A), std::end(A));
// Sort the 'ordered' vector in ascending order.
std::sort(std::begin(ordered), std::end(ordered));
for (unsigned int i = 0; i < N - 2; ++i) {
// Check if the current elements satisfy the triangular triplet conditions.
if (ordered[i] + ordered[i + 1] > ordered[i + 2]) {
return 1;
}
}
return 0;
}
// Lesson 7
// Stacks and Queues
// -------------------------------------------------
// 1. Brackets.
/**
* A string S consisting of N characters is considered to be properly nested
* if any of the following conditions is true:
* • S is empty;
* • S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
* • S has the form "VW" where V and W are properly nested strings.
*
* For example, the string "{[()()]}" is properly nested but "([)()]" is not.
*
* Write a function:
* class Solution { public int solution(String S); }
* that, given a string S consisting of N characters,
* returns 1 if S is properly nested and 0 otherwise.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [0..200,000];
* • string S is made only of the following characters: '(', '{', '[', ']', '}' and/or ')'.
*/
#include <string>
#include <stack>
int brackets(std::string& S)
{
std::stack<char> brackets; // A stack to store opening brackets.
for (char c : S) {
if (c == '(' || c == '{' || c == '[') {
// If the character is an opening bracket, push it onto the stack.
brackets.push(c);
} else {
// If the character is a closing bracket, check if it matches the top of the stack.
if (brackets.empty() || (brackets.top() == '(' && c != ')')
|| (brackets.top() == '{' && c != '}')
|| (brackets.top() == '[' && c != ']')) {
return 0;
}
// Pop the top from the stack when an appropriate closing bracket is found.
brackets.pop();
}
}
return brackets.empty();
}
// 2. Fish.
/**
* You are given two non-empty arrays A and B consisting of N integers.
* Arrays A and B represent N voracious fish in a river,
* ordered downstream along the flow of the river.
*
* The fish are numbered from 0 to N − 1.
* If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q.
* Initially, each fish has a unique position.
*
* Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish.
* All its elements are unique. Array B contains the directions of the fish.
* It contains only 0s and/or 1s, where:
* • 0 represents a fish flowing upstream,
* • 1 represents a fish flowing downstream.
*
* If two fish move in opposite directions and there are no other (living) fish between them,
* they will eventually meet each other. Then only one fish can stay alive −
* the larger fish eats the smaller one.
* More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0,
* and there are no living fish between them. After they meet:
* • If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,
* • If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.
*
* We assume that all the fish are flowing at the same speed.
* That is, fish moving in the same direction never meet.
* The goal is to calculate the number of fish that will stay alive.
*
* For example, consider arrays A and B such that:
* A[0] = 4 B[0] = 0
* A[1] = 3 B[1] = 1
* A[2] = 2 B[2] = 0
* A[3] = 1 B[3] = 0
* A[4] = 5 B[4] = 0
* Initially all the fish are alive and all except fish number 1 are moving upstream.
* Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too.
* Finally, it meets fish number 4 and is eaten by it.
* The remaining two fish, number 0 and 4, never meet and therefore stay alive.
*
* Write a function:
* class Solution { public int solution(int[] A, int[] B); }
* that, given two non-empty arrays A and B consisting of N integers,
* returns the number of fish that will stay alive.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [1..100,000];
* • each element of array A is an integer within the range [0..1,000,000,000];
* • each element of array B is an integer that can have one of the following values: 0, 1;
* • the elements of A are all distinct.
*/
#include <vector>
#include <stack>
int fish(std::vector<int>& A, std::vector<int>& B)
{
if (A.size() == 1) {
return 1;
}
int alive = A.size();
std::stack<int> downstreamStack;
for (size_t i = 0; i < A.size(); i++)
{
if (B[i] == 1) {
downstreamStack.push(i);
} else {
while (!downstreamStack.empty()) {
// Check if the current fish swimming upstream can eat the fish swimming downstream,
// which is at the top of the stack.
if (A[downstreamStack.top()] < A[i]) {
downstreamStack.pop();
alive--;
} else {
alive--;
break; // The current upstream fish is eaten by the downstream fish, stop checking.
}
}
}
}
return alive;
}
// 3. Nesting.
/**
* A string S consisting of N characters is called properly nested if:
* • S is empty;
* • S has the form "(U)" where U is a properly nested string;
* • S has the form "VW" where V and W are properly nested strings.
*
* For example, string "(()(())())" is properly nested but string "())" isn't.
*
* Write a function:
* class Solution { public int solution(String S); }
* that, given a string S consisting of N characters,
* returns 1 if string S is properly nested and 0 otherwise.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [0..1,000,000];
* • string S is made only of the characters '(' and/or ')'.
*/
#include <string>
#include <stack>
int nesting(std::string& S)
{
std::stack<char> brackets; // A stack to store opening brackets.
for (char c : S) {
// If the character is an opening bracket, push it onto the stack.
if (c == '(') {
brackets.push(c);
} else {
// If the character is a closing bracket, check if it matches the top of the stack.
if (brackets.empty() || (brackets.top() == '(' && c != ')')) {
return 0;
}
// Pop the top from the stack when a closing bracket is encountered.
brackets.pop();
}
}
return brackets.empty();
}
// 4. StoneWall
/**
* You are going to build a stone wall.
* The wall should be straight and N meters long, and its thickness should be constant;
* however, it should have different heights in different places.
* The height of the wall is specified by an array H of N positive integers.
* H[I] is the height of the wall from I to I+1 meters to the right of its left end.
* In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.
*
* The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular).
* Your task is to compute the minimum number of blocks needed to build the wall.
*
* Write a function:
* class Solution { public int solution(int[] H); }
*
* that, given an array H of N positive integers specifying the height of the wall,
* returns the minimum number of blocks needed to build it.
*
* For example, given array H containing N = 9 integers:
* H[0] = 8 H[1] = 8 H[2] = 5
* H[3] = 7 H[4] = 9 H[5] = 8
* H[6] = 7 H[7] = 4 H[8] = 8
* the function should return 7. The figure shows one possible arrangement of seven blocks.
*
* .....
* : :
* : :
* ........ : :.... .....
* : : : : : : :
* : : ...:...:...:... : :
* : : : : : :
* : : : : : :
* : :.....:.............: : :
* : : : : :
* : : :...:...:
* : : : :
* : : : :
* : : : :
* : : : :
* : : : :
* : : : :
* :......:...................:.......:
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [1..100,000];
* • each element of array H is an integer within the range [1..1,000,000,000].
*/
#include <vector>
#include <stack>
int stoneWall(std::vector<int>& H)
{
std::stack<int> stonesInUse;
int stoneCount = 0;
for (int height : H) {
while (!stonesInUse.empty() && stonesInUse.top() > height) {
stonesInUse.pop();
}
if (stonesInUse.empty() || stonesInUse.top() < height) {
// Add a new block to the stack only if reusing other blocks is impossible.
stoneCount++;
stonesInUse.push(height);
}
}
return stoneCount;
}
// Lesson 8
// Leader
// -------------------------------------------------
// 1. Dominator.
/**
* An array A consisting of N integers is given.
* The dominator of array A is the value that occurs in more than half of the elements of A.
*
* For example, consider array A such that
* A[0] = 3 A[1] = 4 A[2] = 3
* A[3] = 2 A[4] = 3 A[5] = -1
* A[6] = 3 A[7] = 3
*
* The dominator of A is 3 because it occurs in 5 out of 8 elements of A
* (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8.
*
* Write a function:
* class Solution { public int solution(int[] A); }
* that, given an array A consisting of N integers,
* returns index of any element of array A in which the dominator of A occurs.
* The function should return −1 if array A does not have a dominator.
*
* Write an efficient algorithm for the following assumptions:
* • N is an integer within the range [0..100,000];
* • each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
*/
#include <vector>
#include <stack>
int dominator(std::vector<int>& A)
{
std::stack<int> auxStack; // A stack to track candidate elements.
// If the sequence has a leader, removing different-value element pairs
// won't change the remaining sequence's leader.
for (int i : A) {
if (auxStack.empty()) {
auxStack.push(i);
} else {
if (auxStack.top() == i) {
auxStack.push(i);
} else {
auxStack.pop();
}
}
}
if (auxStack.empty()) {
return -1;
}
int candidate = auxStack.top(),
candidateIndex = -1,
length = (int)A.size(),
count = 0;
for (int i = 0; i < length; ++i) {
if (A[i] == candidate) {
count++;
if (candidateIndex < 0) {
candidateIndex = i;
}
}
}
if (count > length / 2) {
return candidateIndex;
}
return -1;
}
// 2. EquiLeader.
/**
* A non-empty array A consisting of N integers is given.
* The leader of this array is the value that occurs in more than half of the elements of A.
*
* An equi leader is an index S such that 0 ≤ S < N − 1
* and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.
*
* For example, given array A such that:
* A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2
* we can find two equi leaders:
* • 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
* • 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4.
*
* The goal is to count the number of equi leaders.
*
* Write a function:
* class Solution { public int solution(int[] A); }