-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoding-test.c
1481 lines (1207 loc) · 36.4 KB
/
coding-test.c
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
/* Copyright © 2021-2023 Chee Bin HOH. All rights reserved.
*
* Coding test questions from Apple (at least internet claim it :)) and many
* others.
*
* https://www.codinginterview.com/apple-interview-questions, I also include
* questions that is similar I come across from friend or online.
*
* All answers are done by me with some assumption sometimes to make it easy for
* me :) I do some reading about some topic to refresh my knowledge about
* certain theory, like AVL before I start coding it.
*
* Happy coding!
*/
#include "avlbstree.h"
#include "btree.h"
#include "search-sort.h"
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Test 1:
*
* Given an array of integers and a sum value, determine if there are any three
* integers in the array whose sum up equals the given sum value. And assume
* that the integers positive numbers and unique.
*
* If the array of integers are unsorted, a simple but inefficient way to find
* if there are integers add up to the sum is to have 3 loops as below.
*
* This is still inefficient and the logic is quadratic in term of O(n^3).
*/
int deteremineIf3NumberSumToValue(int array[], int size, int sum) {
int i;
int j;
int k;
for (i = 0; i < size - 2; i++) {
for (j = i + 1; j < size - 1; j++) {
for (k = j + 1; k < size; k++) {
if ((array[i] + array[j] + array[k]) == sum)
goto found;
}
}
}
return 0;
found:
return 1;
}
/* How do we improve the performance from previous code? one way is to keep the
* array in sorted, so we traverse from start (smaller number), if the current
* value at i and j already add up exceeding sum, then we can skip the k loop
* (assume that all our numbers are positive value) as we are not going to find
* a sum of i + j + i that is equal to sum.
*
* The solution is still made up of 3 nested loops, but traverse backward to
* find a value at i (1st loop) where after minus it from sum, we have remaining
* sum that is greater than 0.
*
* Then in the j (2nd loop), we start the j with index 1 smaller than i (as we
* the next number add up to sum will be smaller than where ith value), and
* remaining sum minus the value at jth should be 1 or more.
*/
int determineIf3NumberSumToValueBySort(int array[], int size, int sum) {
int i;
int j;
int k;
int remaining;
quickSort(array, size);
// selectionSort(array, size);
remaining = sum;
for (i = size - 1; i > 1; i--) {
if ((remaining - array[i]) > 0) {
remaining -= array[i];
for (j = i - 1; j > 0; j--) {
if ((remaining - array[j]) > 0) {
remaining -= array[j];
for (k = j - 1; k >= 0; k--) {
if ((remaining - array[k]) == 0)
goto found;
}
remaining += array[j];
}
}
remaining += array[i];
}
}
return 0;
found:
return 1;
}
/* In this approach, we have 3 loops too, but we do not search through the
* whole list of array in each loop (which is O(n^3), instead we do this:
*
* in 1st loop, we find the index in the array for the largest value that is
* smaller than sum, we use binary search to quickly do so (based on the fact
* that the list of numbers are > 0 and unique).
*
* in the 2nd loop, we find the index in the array (from 0 up to 1st loop
* current index) for the largest value that is smaller than sum - 1st loop'
* value, we use binary search to do so.
*
* in the 3rd loop, we find the index in the array (from 0 up to 2nd loop index)
* for the value that is matching to the sum - (1st loop' value + 2nd loop'
* value).
*
* This is much efficient approach if we have a long list of array and where the
* values are unique, spread apart, example, [1, 5, 100, 2000, 2001, 2002, ...
* 4000, 4020, ... 5000].
*
* A binary search to locate the largest value smaller than the remaining value
* allows us to quickly slide down the search space in next loop.
*/
int determineLargestValueSmallerThanN(int array[], int size, int n) {
int start;
int mid;
int end;
start = 0;
end = size - 1;
while (start <= end) {
mid = start + ((end - start) / 2);
if (array[mid] == n) {
return mid - 1;
} else if (array[mid] < n) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return mid;
}
int deteremineIf3NumberSumToValueInDivAndConquer(int array[], int size,
int sum) {
int i;
int j;
int k;
int remaining;
int largestValueSmallerThanN;
quickSort(array, size);
// selectionSort(array, size);
largestValueSmallerThanN =
determineLargestValueSmallerThanN(array, size, sum);
if (largestValueSmallerThanN == -1) {
return 0;
}
for (i = largestValueSmallerThanN; i >= 0; i--) {
remaining = sum - array[i];
largestValueSmallerThanN =
determineLargestValueSmallerThanN(array, i, remaining);
if (largestValueSmallerThanN == -1) {
continue;
}
for (j = largestValueSmallerThanN; j >= 0; j--) {
remaining -= array[j];
for (k = j - 1; k >= 0; k--) {
if (remaining == array[k]) {
return 1;
}
}
remaining += array[j];
}
}
return 0;
}
/* Brute force in recursive approach is simple to understand:
*
* if nNum is 1, the exit condition is to find an element that
* matches the sum.
*
* if nNum is more than 1, then we reduce sum by the current
* element, and search to determine if there are elements add up
* to sum - current element for the remaining nNum -1.
*/
int determineIfnNumSumToValueRecursive(int array[], int size, int sum,
int nNum) {
int i;
assert(nNum > 0);
for (i = 0; i < size; i++) {
if (nNum == 1) {
if (sum == array[i]) {
return 1;
}
} else {
if (determineIfnNumSumToValueRecursive(&array[i + 1], size - (i + 1),
sum - array[i], nNum - 1)) {
return 1;
}
}
}
return 0;
}
int deteremineIf3NumberSumToValueRecursive(int array[], int size, int sum) {
return determineIfnNumSumToValueRecursive(array, size, sum, 3);
}
void runDeteremineIf3NumberSumToValue(void) {
int number[] = {3, 7, 1, 2, 8, 4, 5};
int found;
printf("Test 1 description: given an array of integers and a value, "
"determine if there are any three\n"
"integers in the array whose sum equals the given value.\n");
printf("\n");
printf("The integer array is ");
printIntegerArray(number, sizeof(number) / sizeof(number[0]));
printf("\n");
printf("Use brute force method\n");
found = deteremineIf3NumberSumToValue(number,
sizeof(number) / sizeof(number[0]), 20);
if (found) {
printf("There are 3 numbers sum up to %d\n", 20);
} else {
printf("There are no 3 numbers sum up to %d\n", 20);
}
found = deteremineIf3NumberSumToValue(number,
sizeof(number) / sizeof(number[0]), 21);
if (found) {
printf("There are 3 numbers sum up to %d\n", 21);
} else {
printf("There are no 3 numbers sum up to %d\n", 21);
}
printf("\n");
printf("Sort it before attempting it\n");
found = determineIf3NumberSumToValueBySort(
number, sizeof(number) / sizeof(number[0]), 20);
if (found) {
printf("There are 3 numbers sum up to %d\n", 20);
} else {
printf("There are no 3 numbers sum up to %d\n", 20);
}
found = determineIf3NumberSumToValueBySort(
number, sizeof(number) / sizeof(number[0]), 21);
if (found) {
printf("There are 3 numbers sum up to %d\n", 21);
} else {
printf("There are no 3 numbers sum up to %d\n", 21);
}
printf("\n");
printf("Use Divide & Conquer and Binary way of brute force method\n");
found = deteremineIf3NumberSumToValueInDivAndConquer(
number, sizeof(number) / sizeof(number[0]), 20);
if (found) {
printf("There are 3 numbers sum up to %d\n", 20);
} else {
printf("There are no 3 numbers sum up to %d\n", 20);
}
found = deteremineIf3NumberSumToValueInDivAndConquer(
number, sizeof(number) / sizeof(number[0]), 21);
if (found) {
printf("There are 3 numbers sum up to %d\n", 21);
} else {
printf("There are no 3 numbers sum up to %d\n", 21);
}
printf("\n");
printf("Use brute force but simple recursive method\n");
found = deteremineIf3NumberSumToValueRecursive(
number, sizeof(number) / sizeof(number[0]), 20);
if (found) {
printf("There are 3 numbers sum up to %d\n", 20);
} else {
printf("There are no 3 numbers sum up to %d\n", 20);
}
found = deteremineIf3NumberSumToValueRecursive(
number, sizeof(number) / sizeof(number[0]), 21);
if (found) {
printf("There are 3 numbers sum up to %d\n", 21);
} else {
printf("There are no 3 numbers sum up to %d\n", 21);
}
printf("\n");
}
/* Test 2:
*
* Given a list of intervals, merge all the overlapping intervals to produce a
* list that has only mutually exclusive intervals.
*
* Assumption = it is arranged in ordering of interval start and end.
*/
int collapseOverlapInterval(int start[], int end[], int size) {
int i;
int prev;
prev = 0;
i = 1;
while (i < size) {
if (start[i] >= start[prev] && start[i] <= end[prev]) {
if (end[i] > end[prev]) {
end[prev] = end[i];
}
} else {
prev++;
if (i - prev > 0) {
start[prev] = start[i];
end[prev] = end[i];
}
}
i++;
}
return (size < 2) ? size : prev + 1;
}
void printInterval(int start[], int end[], int size) {
int i;
for (i = 0; i < size - 1; i++) {
printf("%d...%d, ", start[i], end[i]);
}
if (size > 0)
printf("%d...%d\n", start[i], end[i]);
}
void runCollapseOverlapInterval(void) {
int start[] = {1, 4, 5, 9, 10, 14, 17};
int end[] = {3, 6, 8, 12, 15, 16, 18};
int size = sizeof(start) / sizeof(start[0]);
printf("Test 2 description: given a list of intervals, merge all the "
"overlapping intervals to produce a list\n"
"that has only mutually exclusive intervals.\n");
printf("\n");
printInterval(start, end, size);
size = collapseOverlapInterval(start, end, size);
printf("after merged\n");
printf("\n");
printInterval(start, end, size);
}
/* Test 3:
*
* Search for a given number in a sorted array, with unique elements,
* that has been rotated by some arbitrary number. Return -1 if the number
* does not exist.
*/
void runBinarySearchOnRotatedSortedList(void) {
int array[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int arrayRotated[] = {15, 17, 19, 1, 3, 5, 7, 9, 11, 13};
int key;
int i;
printf(
"Test 3 description: search for a given number in a sorted array, with "
"unique elements,\n"
"that has been rotated by some arbitrary number. Return -1 if the "
"number does not exist.\n");
printf("\n");
printf("On none-rotated list\n");
for (i = 0; i < sizeof(array) / sizeof(array[0]); i++)
printf("%d, ", array[i]);
printf("\n");
key = binarySearch(array, sizeof(array) / sizeof(array[0]), 3);
printf("data %2d, key = %d\n", 3, key);
key = binarySearch(array, sizeof(array) / sizeof(array[0]), 7);
printf("data %2d, key = %d\n", 7, key);
key = binarySearch(array, sizeof(array) / sizeof(array[0]), 8);
printf("data %2d, key = %d\n", 8, key);
key = binarySearch(array, sizeof(array) / sizeof(array[0]), 17);
printf("data %2d, key = %d\n", 17, key);
printf("\n");
printf("On rotated list\n");
for (i = 0; i < sizeof(arrayRotated) / sizeof(arrayRotated[0]); i++)
printf("%d, ", arrayRotated[i]);
printf("\n");
key = binarySearch(arrayRotated,
sizeof(arrayRotated) / sizeof(arrayRotated[0]), 3);
printf("data %2d, key = %d\n", 3, key);
key = binarySearch(arrayRotated,
sizeof(arrayRotated) / sizeof(arrayRotated[0]), 7);
printf("data %2d, key = %d\n", 7, key);
key = binarySearch(arrayRotated,
sizeof(arrayRotated) / sizeof(arrayRotated[0]), 8);
printf("data %2d, key = %d\n", 8, key);
key = binarySearch(arrayRotated,
sizeof(arrayRotated) / sizeof(arrayRotated[0]), 17);
printf("data %2d, key = %d\n", 17, key);
}
/* Test 4:
*
* Given a positive integer, target, print all possible combinations of positive
* integers that sum up to the target number.
*
* For example, if we are given input ‘5’, these are the possible sum
* combinations.
*
* 4, 1
* 3, 2
* 3, 1, 1
* 2, 3
* 2, 2, 1
* 2, 1, 1, 1,
* 1, 4
* 1, 3, 1
* 1, 2, 1, 1
* 1, 1, 1, 1, 1
*/
void findAllSumCombinationRecursive(int target, int start, int remaining) {
int i;
printf(", %d", remaining);
i = target - (start + remaining);
while (i-- > 0)
printf(", %d", 1);
remaining--;
if (remaining <= 0)
return;
printf("\n");
printf("%d", start);
findAllSumCombinationRecursive(target, start, remaining);
}
void findAllSumCombination(int target) {
int i;
i = target - 1;
while (i > 0) {
printf("%d", i);
findAllSumCombinationRecursive(target, i, target - i);
printf("\n");
i--;
}
}
void runFindAllSumCombination(void) {
printf("Test 4 description: given a positive integer, target, print all "
"possible combinations of\n"
"positive integers that sum up to the target number.\n");
printf("\n");
printf("find all sum combination of 5\n");
findAllSumCombination(5);
}
/* Test 5:
*
* Reverse the order of words in a given sentence (an array of characters).
*
* "123 45 67 89" ==> "89 67 45 123"
*
* This is much simple solution of reversing words in a string, we first
* reverse whole string, the result of that last character is moved to 1st
* position, 2nd last is moved to 2nd character.
*
* The result of it is a string with characters of the each word reversed,
* then we continue to reverse characters of a word that is broad definition
* consists of a consecutive sequence of none-space characters or a consecutive
* space of space characters. :)
*/
void reverseWords1(char s[]) {
char *p;
char *pEnd;
char tmp;
int swpCount;
// find the end of the string.
pEnd = s;
while ('\0' != *pEnd) {
pEnd++;
}
// reverse characters in the whole string.
swpCount = (pEnd - s) / 2;
pEnd--;
p = s;
while (swpCount > 0) {
tmp = *p;
*p = *pEnd;
*pEnd = tmp;
p++;
pEnd--;
swpCount--;
}
// reverse consecutive of none-space characters or consecutive sequence
// of space characters in each chunk.
p = s;
if ('\0' != *p) {
int isSpace;
int nextIsSpace;
char *pEndWord;
pEnd = p;
isSpace = isspace(*pEnd);
while ('\0' != *pEnd) {
nextIsSpace = isspace(*pEnd);
if (isSpace != nextIsSpace) {
pEndWord = pEnd - 1;
swpCount = (pEndWord - p + 1) / 2;
while (swpCount > 0) {
tmp = *p;
*p = *pEndWord;
*pEndWord = tmp;
pEndWord--;
p++;
swpCount--;
}
isSpace = nextIsSpace;
p = pEnd;
}
pEnd++;
}
// There are two ways to remove duplicated code of reversing letters of a
// word (inside above while loop and after while loop).
//
// one way is that we generalize the logic in while loop above so that if we
// detect an '\0' for next pEnd, we also reverse the letters of the word. I
// think this is a bad choice as the logic inside the whole loop will become
// more complicated with trailing conditions.
//
// the other way is that we put the logic inside a method or macro (for
// performance reason), it will remove duplicated code, but it will also
// mean that anyone reading the code will have to context switch to another
// method. :)
pEndWord = pEnd - 1;
swpCount = (pEndWord - p + 1) / 2;
while (swpCount > 0) {
tmp = *p;
*p = *pEndWord;
*pEndWord = tmp;
pEndWord--;
p++;
swpCount--;
}
} // if ( '\0' != *p )
}
void runReverseWords(void) {
char str[] = "1 23 45 6 789";
char str2[] = " abc xyz ";
printf("Test 5 description: reverse the order of words in a given sentence "
"(an array of characters).\n");
printf("\n");
printf("String = \"%s\"\n", str);
reverseWords1(str);
printf("Reversing words, result string = \"%s\"\n", str);
reverseWords1(str);
printf("Reversing words again, result string = \"%s\"\n", str);
printf("\n");
printf("String = \"%s\"\n", str2);
reverseWords1(str2);
printf("Reversing words, result string = \"%s\"\n", str2);
reverseWords1(str2);
printf("Reversing words again, result string = \"%s\"\n", str2);
}
/* Test 6:
*
* Find total ways to achieve a given sum with `n` throws of dice having `k`
* faces
*
* Example if throw is 2 and sum value is 10, then we have the following:
* (6, 4), (4, 6), (5, 5)
*/
void printAllWayToThrowDiceEqualToSumRecursive(int sum, int maxThrow,
int throwValue[], int throwCnt) {
int i;
int dice;
int total;
total = 0;
for (i = 0; i < throwCnt; i++) {
total += throwValue[i];
}
if (throwCnt >= maxThrow) {
if (total == sum) {
for (i = 0; i < throwCnt - 1; i++)
printf("%d, ", throwValue[i]);
printf("%d\n", throwValue[i]);
}
return;
}
dice = 1;
while (dice <= 6) {
if ((dice + total) <= sum) {
throwValue[throwCnt] = dice;
printAllWayToThrowDiceEqualToSumRecursive(sum, maxThrow, throwValue,
throwCnt + 1);
}
dice++;
}
}
void printAllWayToThrowDiceEqualToSum(int sum, int maxThrow) {
int throwValue[100];
printAllWayToThrowDiceEqualToSumRecursive(sum, maxThrow, throwValue, 0);
}
void runAllWayToThrowDiceEqualToSum() {
printf("Test 6 description: find total ways to achieve a given sum with `n` "
"throws of dice having `k` faces\n"
"if throw is 2 and sum value is 10, then we have the following: (6, "
"4), (4, 6), (5, 5).\n");
printf("\n");
printf("Number of throws = %d, desired sum = %d\n", 2, 10);
printAllWayToThrowDiceEqualToSum(10, 2);
printf("\n");
printf("Number of throws = %d, desired sum = %d\n", 3, 8);
printAllWayToThrowDiceEqualToSum(8, 3);
}
/* Test 7:
*
* You are given a double, x and an integer n, write a function to calculate x
* raised to the power n.
*
* 2 ^ 5 = 32
* 3 ^ 4 = 81
* 1.5 ^ 3 = 3.375
* 2 ^ -2 = 0.25
*/
double power(double value, int power) {
double result;
int isNegativeExponent;
int isNegativeBase;
isNegativeExponent = 0;
isNegativeBase = 0;
if (value < 0.0) {
isNegativeBase = 1;
value = value * -1.0;
}
if (power < 0.0) {
isNegativeExponent = 1;
power = power * -1;
}
result = value;
while (--power > 0)
result = result * value;
if (isNegativeExponent)
result = 1.0 / result;
if (isNegativeBase)
result = -1.0 * result;
return result;
}
void runCalculatePowerOfDoubleValue(void) {
printf("Test 7 description: given a double, x and an integer n, write a "
"function to calculate x raised to the power n.\n");
printf("\n");
printf(" 2 ^ 5 = %lf\n", power(2.0, 5));
printf(" 3 ^ 4 = %lf\n", power(3.0, 4));
printf("1.5 ^ 3 = %lf\n", power(1.5, 3));
printf(" 2 ^ -2 = %lf\n", power(2.0, -2));
}
/* Test 8:
*
* Given that integers are read from a data stream. Find median of elements
* read so for in efficient way. For simplicity assume there are no duplicates.
*/
struct medianData {
int count;
int positions[2];
int values[2];
};
void calculateMedian(struct TreeNode *node, int pos, int *stop, void *data) {
struct medianData *pData = data;
int i;
for (i = 0; i < pData->count; i++) {
if (pos == pData->positions[i])
pData->values[i] = node->val;
}
}
double addIntegerAndReturnMedian(int val) {
static struct TreeNode *root = NULL;
struct medianData data;
int count;
root = addTreeNodeAndRebalanceTree(root, val);
count = findTotalNumberOfTreeNode(root);
if ((count % 2) == 0) {
data.count = 2;
data.positions[0] = (count / 2) - 1;
data.positions[1] = data.positions[0] + 1;
} else {
data.count = 1;
data.positions[0] = count / 2;
}
data.values[0] = 0;
data.values[1] = 0;
traverseTreeNodeInOrder(root, calculateMedian, &data);
return (data.values[0] + data.values[1]) / (double)data.count;
}
void runFindMedianOfStreamOfIntegers(void) {
printf("Test 8 description: given that integers are read from a data stream. "
"Find median of elements\n"
"read so for in efficient way. For simplicity assume there are no "
"duplicates.\n");
printf("\n");
printf("Adding 5, median = %5.2f\n", addIntegerAndReturnMedian(5));
printf("Adding 15, median = %5.2f\n", addIntegerAndReturnMedian(15));
printf("Adding 1, median = %5.2f\n", addIntegerAndReturnMedian(1));
printf("Adding 3, median = %5.2f\n", addIntegerAndReturnMedian(3));
printf("Adding 2, median = %5.2f\n", addIntegerAndReturnMedian(2));
printf("Adding 4, median = %5.2f\n", addIntegerAndReturnMedian(4));
}
/* Test 9:
*
* the permutations of string ABC is "ABC ACB BAC BCA CBA CAB"
*/
void printPermutationsOfString(char s[]) {
int len;
int i;
int j;
char tmp;
len = strlen(s);
for (i = 0; i < len; i++) {
printf("%s\n", s);
for (j = 1; j < len - i; j++) {
tmp = s[j];
s[j] = s[0];
s[0] = tmp;
printf("%s\n", s);
tmp = s[j];
s[j] = s[0];
s[0] = tmp;
}
for (j = 0; j < len - 1; j++) {
tmp = s[j];
s[j] = s[j + 1];
s[j + 1] = tmp;
}
}
}
void runPermutationsOfString(void) {
char s[] = "ABC";
printf("Test 9 description: the permutations of string ABC is \"ABC ACB BAC "
"BCA CBA CAB\".\n");
printf("\n");
printPermutationsOfString(s);
printf("\n");
}
/* Test 10: implementing AVL (Adelson-Velsky and Landis) self-balancing tree
*/
void runAVLSelfbalanceTree(void) {
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
struct TreeNode *root = NULL;
int i;
printf("Test 10 description: implementing AVL (Adelson-Velsky and Landis) "
"self-balancing binary search tree.\n");
printf("\n");
printf("Adding a list of integer arrays in the following order");
printIntegerArray(array, sizeof(array) / sizeof(array[0]));
for (i = 0; i < sizeof(array) / sizeof(array[0]); i++)
root = addTreeNodeAndRebalanceTree(root, array[i]);
printf("The tree topology:\n");
printf("\n");
printTreeNodeInTreeTopology(root);
}
/* Test 11:
*
* The maximum subarray problem is the task of finding the largest possible sum
* of a contiguous subarray, within a given one-dimensional array A[1…n] of
* numbers
*/
void printMaximumSubarrayNumber(int array[], int size) {
int i;
int j;
int sum;
int largestSum;
int largestSumStart;
int largestSumEnd;
i = 0;
largestSum = array[i];
largestSumStart = i;
largestSumEnd = i;
do {
sum = array[i];
for (j = i + 1; j < size - 1; j++) {
if ((sum + array[j]) >= sum)
sum += array[j];
else
break;
}
if (j < size - 1) {
if (sum >= largestSum) {
largestSum = sum;
largestSumStart = i;
largestSumEnd = j - 1;
}
}
i++;
} while (i < size - 1);
printIntegerArray(&array[largestSumStart],
largestSumEnd - largestSumStart + 1);
}
void runMaximumSubarrayNumber(void) {
int array[] = {-4, 2, -5, 1, 2, 3, 6, -5, 1};
int array2[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
printf("Test 11 description: finding the largest possible sum of a "
"contiguous subarray, within\n"
"a given one-dimensional array A[1…n] of numbers.\n");
printf("\n");
printf("The integer array is ");
printIntegerArray(array, sizeof(array) / sizeof(array[0]));
printf("\n");
printf("Maximum subarray is ");
printMaximumSubarrayNumber(array, sizeof(array) / sizeof(array[0]));
}
/* Test 12:
*
* Find the rotating point of an array that is sorted, but the starting point
* can be in middle.
*/
int findRotatingPointInArray(int array[], int size) {
int start;
int end;
int rotatingPoint;
int midpoint;
start = 0;
end = size - 1;
rotatingPoint = 0;
while (start < end && array[start] > array[end]) {
midpoint = (start + end) / 2;
if (array[start] > array[midpoint]) {
end = midpoint - 1;
rotatingPoint = end;
} else {
start = midpoint + 1;
rotatingPoint = start;
}
}
return rotatingPoint;
}
void findRotatingPointInIntegerArray(void) {
int array1[] = {5, 1, 2, 3, 4};
int array2[] = {4, 5, 6, 1, 2, 3};
int array3[] = {4, 5, 6, 7, 8, 0, 1, 2, 3};
int i;
int start;
printf("Test 12 description: Find the rotating point of an array that is "
"sorted, but the starting point can be in middle.\n");
printf("\n");
printf("The integer array1 is ");
printIntegerArray(array1, sizeof(array1) / sizeof(array1[0]));
start = findRotatingPointInArray(array1, sizeof(array1) / sizeof(array1[0]));
printf("The rotating point is at index %d and value is %d\n", start,
array1[start]);
printf("\n");
printf("The integer array2 is ");
printIntegerArray(array2, sizeof(array2) / sizeof(array2[0]));
start = findRotatingPointInArray(array2, sizeof(array2) / sizeof(array2[0]));
printf("The rotating point is at index %d and value is %d\n", start,
array2[start]);
printf("\n");
printf("The integer array3 is ");
printIntegerArray(array3, sizeof(array3) / sizeof(array3[0]));
start = findRotatingPointInArray(array3, sizeof(array3) / sizeof(array3[0]));
printf("The rotating point is at index %d and value is %d\n", start,
array3[start]);
}
/* Test 13:
*
* Check if a binary tree is binary search tree.
*/
struct checkBinarySearchTreeData {
int isValid;