├── Any_Base_to_decimal ├── Breadth-First-Search.c ├── Convert_decimal_to_hexa ├── Count_max_line.cpp ├── Depth-First-Search.c ├── Find_subset_array.cpp ├── Find_variance_of_numbers.c ├── Finding-the-median-of-n-numbers ├── Gaussian_elimination_method.c ├── Integer_to_string.c ├── Mean_finder.c ├── Merge_sort_for_doubly_linked _list.c ├── Merge_sorting_linked_list.c ├── README.md ├── Recursive_Traversals.c ├── Red-BlackTree_implem.c ├── Searching-a-character.java ├── Vertical_ord_binary_tree.cpp ├── array-rotation-reversal-algorithm.cpp ├── array-rotation-through-juggling-algorithm.cpp ├── check-sort-rotate.cpp ├── checking-panagram.cpp ├── chef and prime ├── count-all-pairs-with-given-sum.cpp ├── count-digits.c ├── count-divisible.cpp ├── count-maximum-points-on-single-same-line.cpp ├── cyclically-rotate-array.cpp ├── delete-a-linked-list.cpp ├── element-at-index-rotated.cpp ├── factorial-c.c ├── fibonacci-rec.cpp ├── find-repetitive-element-1-n-1.cpp ├── hash.c ├── iterator.java ├── left-rotate-array.cpp ├── length-of-linked-list.cpp ├── max ├── max-con-1-rotate-binary.cpp ├── max-hamming-distance.cpp ├── max-value-for-sum.cpp ├── maximum-distance-two-occurrences-element-array.cpp ├── maximum-sum-array-in-rotations.cpp ├── min-element-rotated-array.cpp ├── mirror-of-n-array-tree.cpp ├── missing-elem-range.cpp ├── multiple-left-rotations.cpp ├── non-repeat-elem.cpp ├── num-divisor-right-rotate.cpp ├── operation ├── pair with sum hashing.c ├── pair-sum.c ├── pair-sum.cpp ├── pair-with-greatest-product.cpp ├── palindrome.c ├── palindromes.cpp ├── power-recursion.c ├── queries-on-array.cpp ├── queue ├── reversal-rotat-array.cpp ├── rotated-array-pair-sum.cpp ├── rotation-count-Linear-search.cpp ├── search-element-sorted-array.cpp ├── simpsons_method.c ├── snack ├── sort-frequency.cpp ├── split-and-add.cpp ├── sum-digits.c ├── symmetric-pair-in-array.cpp ├── top-three-repeated.cpp ├── trie-delete.c └── trie-search /Any_Base_to_decimal: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(void) 5 | { 6 | int base, i, j; 7 | char number[100]; 8 | unsigned long decimal = 0; 9 | 10 | printf("Enter the base: "); 11 | scanf("%d", &base); 12 | printf("Enter the number: "); 13 | scanf("%s", &number[0]); 14 | 15 | for (i = 0; number[i] != '\0'; i++) 16 | { 17 | if (isdigit(number[i])) 18 | number[i] -= '0'; 19 | else if (isupper(number[i])) 20 | number[i] -= 'A' - 10; 21 | else if (islower(number[i])) 22 | number[i] -= 'a' - 10; 23 | else 24 | number[i] = base + 1; 25 | 26 | if (number[i] >= base) 27 | { 28 | printf("invalid number\n"); 29 | return 0; 30 | } 31 | } 32 | 33 | for (j = 0; j < i; j++) 34 | { 35 | decimal *= base; 36 | decimal += number[j]; 37 | } 38 | 39 | printf("%lu\n", decimal); 40 | } 41 | -------------------------------------------------------------------------------- /Breadth-First-Search.c: -------------------------------------------------------------------------------- 1 | #include 2 | int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1; 3 | 4 | void bfs(int v) { 5 | for(i = 1; i <= n; i++) 6 | if(a[v][i] && !visited[i]) 7 | q[++r] = i; 8 | if(f <= r) { 9 | visited[q[f]] = 1; 10 | bfs(q[f++]); 11 | } 12 | } 13 | 14 | void main() { 15 | int v; 16 | printf("\n Enter the number of vertices:"); 17 | scanf("%d", &n); 18 | 19 | for(i=1; i <= n; i++) { 20 | q[i] = 0; 21 | visited[i] = 0; 22 | } 23 | 24 | printf("\n Enter graph data in matrix form:\n"); 25 | for(i=1; i<=n; i++) { 26 | for(j=1;j<=n;j++) { 27 | scanf("%d", &a[i][j]); 28 | } 29 | } 30 | 31 | printf("\n Enter the starting vertex:"); 32 | scanf("%d", &v); 33 | bfs(v); 34 | printf("\n The node which are reachable are:\n"); 35 | 36 | for(i=1; i <= n; i++) { 37 | if(visited[i]) 38 | printf("%d\t", i); 39 | else { 40 | printf("\n Bfs is not possible. Not all nodes are reachable"); 41 | break; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Convert_decimal_to_hexa: -------------------------------------------------------------------------------- 1 | #include 2 | void decimal2Hexadecimal(long num); 3 | 4 | int main() 5 | { 6 | long decimalnum; 7 | 8 | printf("Enter decimal number: "); 9 | scanf("%ld", &decimalnum); 10 | 11 | decimal2Hexadecimal(decimalnum); 12 | 13 | return 0; 14 | } 15 | 16 | /********function for convert decimal number to hexadecimal 17 | * number****************/ 18 | void decimal2Hexadecimal(long num) 19 | { 20 | long decimalnum = num; 21 | long quotient, remainder; 22 | int i, j = 0; 23 | char hexadecimalnum[100]; 24 | 25 | quotient = decimalnum; 26 | 27 | while (quotient != 0) 28 | { 29 | remainder = quotient % 16; 30 | if (remainder < 10) 31 | hexadecimalnum[j++] = 48 + remainder; 32 | 33 | else 34 | hexadecimalnum[j++] = 55 + remainder; 35 | 36 | quotient = quotient / 16; 37 | } 38 | 39 | // print the hexadecimal number 40 | 41 | for (i = j; i >= 0; i--) 42 | { 43 | printf("%c", hexadecimalnum[i]); 44 | } 45 | 46 | printf("\n"); 47 | } 48 | -------------------------------------------------------------------------------- /Count_max_line.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* C/C++ program to find maximum number of point int 3 | which lie on same line */ 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // method to find maximum colinear point 10 | int maxPointOnSameLine(vector< pair > points) 11 | { 12 | int N = points.size(); 13 | if (N < 2) 14 | return N; 15 | 16 | int maxPoint = 0; 17 | int curMax, overlapPoints, verticalPoints; 18 | 19 | // here since we are using unordered_map 20 | // which is based on hash function 21 | //But by default we don't have hash function for pairs 22 | //so we'll use hash function defined in Boost library 23 | unordered_map, int,boost:: 24 | hash > > slopeMap; 25 | 26 | // looping for each point 27 | for (int i = 0; i < N; i++) 28 | { 29 | curMax = overlapPoints = verticalPoints = 0; 30 | 31 | // looping from i + 1 to ignore same pair again 32 | for (int j = i + 1; j < N; j++) 33 | { 34 | // If both point are equal then just 35 | // increase overlapPoint count 36 | if (points[i] == points[j]) 37 | overlapPoints++; 38 | 39 | // If x co-ordinate is same, then both 40 | // point are vertical to each other 41 | else if (points[i].first == points[j].first) 42 | verticalPoints++; 43 | 44 | else 45 | { 46 | int yDif = points[j].second - points[i].second; 47 | int xDif = points[j].first - points[i].first; 48 | int g = __gcd(xDif, yDif); 49 | 50 | // reducing the difference by their gcd 51 | yDif /= g; 52 | xDif /= g; 53 | 54 | // increasing the frequency of current slope 55 | // in map 56 | slopeMap[make_pair(yDif, xDif)]++; 57 | curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]); 58 | } 59 | 60 | curMax = max(curMax, verticalPoints); 61 | } 62 | 63 | // updating global maximum by current point's maximum 64 | maxPoint = max(maxPoint, curMax + overlapPoints + 1); 65 | 66 | // printf("maximum colinear point 67 | // which contains current point 68 | // are : %d\n", curMax + overlapPoints + 1); 69 | slopeMap.clear(); 70 | } 71 | 72 | return maxPoint; 73 | } 74 | 75 | // Driver code 76 | int main() 77 | { 78 | const int N = 6; 79 | int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2}, 80 | {3, 3}, {3, 4}}; 81 | 82 | vector< pair > points; 83 | for (int i = 0; i < N; i++) 84 | points.push_back(make_pair(arr[i][0], arr[i][1])); 85 | 86 | cout << maxPointOnSameLine(points) << endl; 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /Depth-First-Search.c: -------------------------------------------------------------------------------- 1 | 2 | void visit( int k, int *id, int val[ ], nodePtr adjList[ ] )‏ 3 | { 4 | nodePtr t; 5 | *id++; 6 | val[k] = *id; 7 | t = adjList[k]; 8 | while (t != NULL)‏ 9 | { 10 | if (val[ t->v ] == 0)‏ 11 | visit(t->v, id, val, adjList); 12 | t = t -> next; 13 | } 14 | } 15 | 16 | void dfs( nodePtr adjList[ ], int n )‏ 17 | { 18 | int k, id; 19 | int val[1..MAX] = { 0 }; 20 | id = 0; 21 | for (k = 0; k < n; k++)‏ 22 | if (val(k) == 0)‏ 23 | visit(k, &id, val, adjList); 24 | 25 | -------------------------------------------------------------------------------- /Find_subset_array.cpp: -------------------------------------------------------------------------------- 1 | // Java code to find whether an array is subset of 2 | // another array 3 | import java.util.HashSet; 4 | class GFG 5 | { 6 | /* Return true if arr2[] is a subset of arr1[] */ 7 | static boolean isSubset(int arr1[], int arr2[], int m, 8 | int n) 9 | { 10 | HashSet hset= new HashSet<>(); 11 | 12 | // hset stores all the values of arr1 13 | for(int i = 0; i < m; i++) 14 | { 15 | if(!hset.contains(arr1[i])) 16 | hset.add(arr1[i]); 17 | } 18 | 19 | // loop to check if all elements of arr2 also 20 | // lies in arr1 21 | for(int i = 0; i < n; i++) 22 | { 23 | if(!hset.contains(arr2[i])) 24 | return false; 25 | } 26 | return true; 27 | } 28 | 29 | public static void main(String[] args) 30 | { 31 | int arr1[] = {11, 1, 13, 21, 3, 7}; 32 | int arr2[] = {11, 3, 7, 1}; 33 | 34 | int m = arr1.length; 35 | int n = arr2.length; 36 | 37 | if(isSubset(arr1, arr2, m, n)) 38 | System.out.println("arr2 is a subset of arr1"); 39 | else 40 | System.out.println("arr2 is not a subset of arr1"); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Find_variance_of_numbers.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | int *ARRAY = NULL, ARRAY_LENGTH, i, TEMPORARY_ELEMENT, isSorted = 0; 8 | float MEAN = 0, VARIANCE = 0, STAND; 9 | 10 | printf("Enter no. for Random Numbers :"); 11 | scanf("%d", &ARRAY_LENGTH); 12 | ARRAY = (int *)realloc( 13 | ARRAY, 14 | ARRAY_LENGTH * (sizeof(int))); // We allocate the dedicated memory 15 | for (i = 0; i < ARRAY_LENGTH; i++) // We generate the random numbers 16 | ARRAY[i] = rand() % 100; 17 | 18 | printf("Random Numbers Generated are :\n"); // We display them 19 | for (i = 0; i < ARRAY_LENGTH; i++) printf("%d ", ARRAY[i]); 20 | 21 | printf("\nSorted Data: "); // Then we sort it using Bubble Sort.. 22 | 23 | while (!isSorted) 24 | { // While our array's not sorted 25 | isSorted = 1; // we suppose that it's sorted 26 | for (i = 0; i < ARRAY_LENGTH - 1; i++) 27 | { // then for each element of the array 28 | if (ARRAY[i] > ARRAY[i + 1]) 29 | { // if the two elements aren't sorted 30 | isSorted = 0; // it means that the array is not sorted 31 | TEMPORARY_ELEMENT = ARRAY[i]; // and we switch these elements 32 | // using TEMPORARY_ELEMENT 33 | ARRAY[i] = ARRAY[i + 1]; 34 | ARRAY[i + 1] = TEMPORARY_ELEMENT; 35 | } 36 | } 37 | } 38 | for (i = 0; i < ARRAY_LENGTH; i++) 39 | { 40 | printf("%d ", ARRAY[i]); 41 | MEAN = MEAN + ARRAY[i]; 42 | } 43 | MEAN = MEAN / (float)ARRAY_LENGTH; 44 | 45 | for (i = 0; i < ARRAY_LENGTH; i++) 46 | VARIANCE = VARIANCE + (pow((ARRAY[i] - MEAN), 2)); 47 | 48 | VARIANCE = VARIANCE / (float)ARRAY_LENGTH; 49 | STAND = sqrt(VARIANCE); 50 | 51 | printf("\n\n- Mean is: %f\n", MEAN); 52 | printf("- Variance is: %f\n", VARIANCE); 53 | printf("- Standard Deviation is: %f\n", STAND); 54 | } 55 | -------------------------------------------------------------------------------- /Finding-the-median-of-n-numbers: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | int a[10], n, i, j, temp; 8 | float mean, median; 9 | 10 | printf("Enter no. for Random Numbers :"); 11 | scanf("%d", &n); 12 | for (i = 0; i < n; i++) 13 | { 14 | a[i] = rand() % 100; 15 | } 16 | printf("Random Numbers Generated are :\n"); 17 | for (i = 0; i < n; i++) 18 | { 19 | printf("\n%d", a[i]); 20 | } 21 | printf("\n"); 22 | printf("\nSorted Data:"); 23 | for (i = 0; i < n; i++) 24 | { 25 | for (j = 0; j < n; j++) 26 | { 27 | if (a[i] < a[j]) 28 | { 29 | temp = a[i]; 30 | a[i] = a[j]; 31 | a[j] = temp; 32 | } 33 | } 34 | } 35 | for (i = 0; i < n; i++) 36 | { 37 | printf("\n%d", a[i]); 38 | } 39 | 40 | if (n % 2 == 0) 41 | { 42 | median = (a[n / 2] + a[(n / 2) - 1]) / 2; 43 | } 44 | else 45 | { 46 | median = a[n / 2]; 47 | } 48 | printf("\nMedian is : %f", median); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Gaussian_elimination_method.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define ARRAY_SIZE 20 5 | 6 | void display(float a[ARRAY_SIZE][ARRAY_SIZE], int n) 7 | { 8 | int i, j; 9 | for (i = 0; i < n; i++) 10 | { 11 | for (j = 0; j <= n; j++) 12 | { 13 | printf("%.2f \t", a[i][j]); 14 | } 15 | printf("\n"); 16 | } 17 | } 18 | 19 | float interchange(float m[ARRAY_SIZE][ARRAY_SIZE], int i, int n) 20 | { 21 | float tmp[ARRAY_SIZE][ARRAY_SIZE]; 22 | float max = fabs(m[i][i]); 23 | int j, k = i; 24 | 25 | for (j = i; j < n; j++) 26 | { 27 | if (max < fabs(m[j][i])) 28 | { 29 | max = fabs(m[j][i]); 30 | k = j; 31 | } 32 | } 33 | for (j = 0; j <= n; j++) 34 | { 35 | tmp[i][j] = m[i][j]; 36 | m[i][j] = m[k][j]; 37 | m[k][j] = tmp[i][j]; 38 | } 39 | return m[ARRAY_SIZE - 1][ARRAY_SIZE - 1]; 40 | } 41 | float eliminate(float m[ARRAY_SIZE][ARRAY_SIZE], int i, int n) 42 | { 43 | float tmp; 44 | int k = 1, l, j; 45 | for (j = i; j < n - 1; j++) 46 | { 47 | tmp = -((m[i + k][i]) / (m[i][i])); 48 | for (l = 0; l <= n; l++) 49 | { 50 | m[i + k][l] = (m[i + k][l]) + (m[i][l] * tmp); 51 | } 52 | k++; 53 | } 54 | return m[ARRAY_SIZE - 1][ARRAY_SIZE - 1]; 55 | } 56 | int main(void) 57 | { 58 | int i, j, n, k = 0, l; 59 | float m[ARRAY_SIZE][ARRAY_SIZE], mul, tmp[ARRAY_SIZE][ARRAY_SIZE], val, 60 | ans[ARRAY_SIZE]; 61 | 62 | printf("Total No.of Equations : "); 63 | scanf("%d", &n); 64 | 65 | printf("\n"); 66 | for (i = 0; i < n; i++) 67 | { 68 | printf("Enter Co-efficient Of Equations %d & Total --->>>\n", i + 1); 69 | for (j = 0; j <= n; j++) 70 | { 71 | printf("r%d%d : ", i, j); 72 | scanf("%f", &m[i][j]); 73 | } 74 | printf("\n"); 75 | } 76 | printf(":::::::::::: Current Matrix ::::::::::::\n\n"); 77 | display(m, n); 78 | 79 | for (i = 0; i < n - 1; i++) 80 | { 81 | printf("\n------->>>>>>>>>>>>>>>>>>>>>>>>-------- %d\n", i + 1); 82 | m[ARRAY_SIZE - 1][ARRAY_SIZE - 1] = interchange(m, i, n); 83 | display(m, n); 84 | printf("\n_______________________________________\n"); 85 | m[ARRAY_SIZE - 1][ARRAY_SIZE - 1] = eliminate(m, i, n); 86 | display(m, n); 87 | } 88 | printf("\n\n Values are : \n"); 89 | for (i = n - 1; i >= 0; i--) 90 | { 91 | l = n - 1; 92 | mul = 0; 93 | for (j = 0; j < k; j++) 94 | { 95 | mul = mul + m[i][l] * ans[l]; 96 | l--; 97 | } 98 | k++; 99 | ans[i] = (m[i][n] - mul) / m[i][i]; 100 | printf("X%d = %.2f\n", i + 1, ans[i]); 101 | } 102 | 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /Integer_to_string.c: -------------------------------------------------------------------------------- 1 | /** 2 | * @file 3 | * @brief Convert a positive integer to string (non-standard function) 4 | * representation. 5 | */ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | char *int_to_string(uint16_t value, char *dest, int base) 14 | { 15 | const char hex_table[] = {'0', '1', '2', '3', '4', '5', '6', '7', 16 | '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 17 | 18 | int len = 0; 19 | do 20 | { 21 | dest[len++] = hex_table[value % base]; 22 | value /= base; 23 | } while (value != 0); 24 | 25 | /* reverse characters */ 26 | for (int i = 0, limit = len / 2; i < limit; ++i) 27 | { 28 | char t = dest[i]; 29 | dest[i] = dest[len - 1 - i]; 30 | dest[len - 1 - i] = t; 31 | } 32 | dest[len] = '\0'; 33 | return dest; 34 | } 35 | 36 | /** Test function 37 | * @returns `void` 38 | */ 39 | static void test() 40 | { 41 | const int MAX_SIZE = 100; 42 | char *str1 = (char *)calloc(sizeof(char), MAX_SIZE); 43 | char *str2 = (char *)calloc(sizeof(char), MAX_SIZE); 44 | 45 | for (int i = 1; i <= 100; ++i) /* test 100 random numbers */ 46 | { 47 | /* Generate value from 0 to 100 */ 48 | int value = rand() % 100; 49 | 50 | // assert(strcmp(itoa(value, str1, 2), int_to_string(value, str2, 2)) == 51 | // 0); 52 | snprintf(str1, MAX_SIZE, "%o", value); //* standard C - to octal */ 53 | assert(strcmp(str1, int_to_string(value, str2, 8)) == 0); 54 | snprintf(str1, MAX_SIZE, "%d", value); /* standard C - to decimal */ 55 | assert(strcmp(str1, int_to_string(value, str2, 10)) == 0); 56 | snprintf(str1, MAX_SIZE, "%x", value); /* standard C - to hexadecimal */ 57 | assert(strcmp(str1, int_to_string(value, str2, 16)) == 0); 58 | } 59 | 60 | free(str1); 61 | free(str2); 62 | } 63 | 64 | /** Driver Code */ 65 | int main() 66 | { 67 | /* Intializes random number generator */ 68 | srand(time(NULL)); 69 | test(); 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /Mean_finder.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define MAX_LEN INT_MAX 7 | 8 | int main(int argc, char **argv) 9 | { 10 | int *a, n = 10, i, j, temp, sum = 0; 11 | float mean; 12 | 13 | if (argc == 2) 14 | { 15 | n = atoi(argv[1]); 16 | if (n >= MAX_LEN) 17 | { 18 | fprintf(stderr, "Maximum %d!\n", MAX_LEN); 19 | return 1; 20 | } 21 | a = (int *)malloc(n * sizeof(int)); 22 | } 23 | 24 | printf("Random Numbers Generated are : "); 25 | for (i = 0; i < n; i++) 26 | { 27 | a[i] = rand() % 100; 28 | printf("%2d, ", a[i]); 29 | } 30 | putchar('\n'); 31 | 32 | for (i = 0; i < n; i++) sum = sum + a[i]; 33 | 34 | mean = sum / (float)n; 35 | printf("\nMean :"); 36 | printf("%f", mean); 37 | 38 | free(a); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Merge_sort_for_doubly_linked _list.c: -------------------------------------------------------------------------------- 1 | // C program for merge sort on doubly linked list 2 | #include 3 | #include 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next, *prev; 8 | }; 9 | 10 | struct Node *split(struct Node *head); 11 | 12 | // Function to merge two linked lists 13 | struct Node *merge(struct Node *first, struct Node *second) 14 | { 15 | // If first linked list is empty 16 | if (!first) 17 | return second; 18 | 19 | // If second linked list is empty 20 | if (!second) 21 | return first; 22 | 23 | // Pick the smaller value 24 | if (first->data < second->data) 25 | { 26 | first->next = merge(first->next,second); 27 | first->next->prev = first; 28 | first->prev = NULL; 29 | return first; 30 | } 31 | else 32 | { 33 | second->next = merge(first,second->next); 34 | second->next->prev = second; 35 | second->prev = NULL; 36 | return second; 37 | } 38 | } 39 | 40 | // Function to do merge sort 41 | struct Node *mergeSort(struct Node *head) 42 | { 43 | if (!head || !head->next) 44 | return head; 45 | struct Node *second = split(head); 46 | 47 | // Recur for left and right halves 48 | head = mergeSort(head); 49 | second = mergeSort(second); 50 | 51 | // Merge the two sorted halves 52 | return merge(head,second); 53 | } 54 | 55 | // A utility function to insert a new node at the 56 | // beginning of doubly linked list 57 | void insert(struct Node **head, int data) 58 | { 59 | struct Node *temp = 60 | (struct Node *)malloc(sizeof(struct Node)); 61 | temp->data = data; 62 | temp->next = temp->prev = NULL; 63 | if (!(*head)) 64 | (*head) = temp; 65 | else 66 | { 67 | temp->next = *head; 68 | (*head)->prev = temp; 69 | (*head) = temp; 70 | } 71 | } 72 | 73 | // A utility function to print a doubly linked list in 74 | // both forward and backward directions 75 | void print(struct Node *head) 76 | { 77 | struct Node *temp = head; 78 | printf("Forward Traversal using next poitner\n"); 79 | while (head) 80 | { 81 | printf("%d ",head->data); 82 | temp = head; 83 | head = head->next; 84 | } 85 | printf("\nBackward Traversal using prev pointer\n"); 86 | while (temp) 87 | { 88 | printf("%d ", temp->data); 89 | temp = temp->prev; 90 | } 91 | } 92 | 93 | // Utility function to swap two integers 94 | void swap(int *A, int *B) 95 | { 96 | int temp = *A; 97 | *A = *B; 98 | *B = temp; 99 | } 100 | 101 | // Split a doubly linked list (DLL) into 2 DLLs of 102 | // half sizes 103 | struct Node *split(struct Node *head) 104 | { 105 | struct Node *fast = head,*slow = head; 106 | while (fast->next && fast->next->next) 107 | { 108 | fast = fast->next->next; 109 | slow = slow->next; 110 | } 111 | struct Node *temp = slow->next; 112 | slow->next = NULL; 113 | return temp; 114 | } 115 | 116 | // Driver program 117 | int main(void) 118 | { 119 | struct Node *head = NULL; 120 | insert(&head,5); 121 | insert(&head,20); 122 | insert(&head,4); 123 | insert(&head,3); 124 | insert(&head,30); 125 | insert(&head,10); 126 | head = mergeSort(head); 127 | printf("\n\nLinked List after sorting\n"); 128 | print(head); 129 | return 0; 130 | } 131 | -------------------------------------------------------------------------------- /Merge_sorting_linked_list.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* Link list node */ 5 | struct Node { 6 | int data; 7 | struct Node* next; 8 | }; 9 | 10 | /* function prototypes */ 11 | struct Node* SortedMerge(struct Node* a, struct Node* b); 12 | void FrontBackSplit(struct Node* source, 13 | struct Node** frontRef, struct Node** backRef); 14 | 15 | /* sorts the linked list by changing next pointers (not data) */ 16 | void MergeSort(struct Node** headRef) 17 | { 18 | struct Node* head = *headRef; 19 | struct Node* a; 20 | struct Node* b; 21 | 22 | /* Base case -- length 0 or 1 */ 23 | if ((head == NULL) || (head->next == NULL)) { 24 | return; 25 | } 26 | 27 | /* Split head into 'a' and 'b' sublists */ 28 | FrontBackSplit(head, &a, &b); 29 | 30 | /* Recursively sort the sublists */ 31 | MergeSort(&a); 32 | MergeSort(&b); 33 | 34 | /* answer = merge the two sorted lists together */ 35 | *headRef = SortedMerge(a, b); 36 | } 37 | 38 | /* See https:// www.geeksforgeeks.org/?p=3622 for details of this 39 | function */ 40 | struct Node* SortedMerge(struct Node* a, struct Node* b) 41 | { 42 | struct Node* result = NULL; 43 | 44 | /* Base cases */ 45 | if (a == NULL) 46 | return (b); 47 | else if (b == NULL) 48 | return (a); 49 | 50 | /* Pick either a or b, and recur */ 51 | if (a->data <= b->data) { 52 | result = a; 53 | result->next = SortedMerge(a->next, b); 54 | } 55 | else { 56 | result = b; 57 | result->next = SortedMerge(a, b->next); 58 | } 59 | return (result); 60 | } 61 | 62 | /* UTILITY FUNCTIONS */ 63 | /* Split the nodes of the given list into front and back halves, 64 | and return the two lists using the reference parameters. 65 | If the length is odd, the extra node should go in the front list. 66 | Uses the fast/slow pointer strategy. */ 67 | void FrontBackSplit(struct Node* source, 68 | struct Node** frontRef, struct Node** backRef) 69 | { 70 | struct Node* fast; 71 | struct Node* slow; 72 | slow = source; 73 | fast = source->next; 74 | 75 | /* Advance 'fast' two nodes, and advance 'slow' one node */ 76 | while (fast != NULL) { 77 | fast = fast->next; 78 | if (fast != NULL) { 79 | slow = slow->next; 80 | fast = fast->next; 81 | } 82 | } 83 | 84 | /* 'slow' is before the midpoint in the list, so split it in two 85 | at that point. */ 86 | *frontRef = source; 87 | *backRef = slow->next; 88 | slow->next = NULL; 89 | } 90 | 91 | /* Function to print nodes in a given linked list */ 92 | void printList(struct Node* node) 93 | { 94 | while (node != NULL) { 95 | printf("%d ", node->data); 96 | node = node->next; 97 | } 98 | } 99 | 100 | /* Function to insert a node at the beginging of the linked list */ 101 | void push(struct Node** head_ref, int new_data) 102 | { 103 | /* allocate node */ 104 | struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); 105 | 106 | new_node->data = new_data; 107 | 108 | /* link the old list off the new node */ 109 | new_node->next = (*head_ref); 110 | 111 | /* move the head to point to the new node */ 112 | (*head_ref) = new_node; 113 | } 114 | 115 | /* Driver program to test above functions*/ 116 | int main() 117 | { 118 | /* Start with the empty list */ 119 | struct Node* res = NULL; 120 | struct Node* a = NULL; 121 | 122 | /* Let us create a unsorted linked lists to test the functions 123 | Created lists shall be a: 2->3->20->5->10->15 */ 124 | push(&a, 15); 125 | push(&a, 10); 126 | push(&a, 5); 127 | push(&a, 20); 128 | push(&a, 3); 129 | push(&a, 2); 130 | 131 | /* Sort the above created Linked List */ 132 | MergeSort(&a); 133 | 134 | printf("Sorted Linked List is: \n"); 135 | printList(a); 136 | 137 | getchar(); 138 | return 0; 139 | } 140 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Awesome-Algorithms-Data-tructures 2 | Breadth First Search : 3 | 4 | Breadth-first-search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key'[1]), and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. 5 | 6 | Depth-first-search (DFS) is an algorithm for traversing or searching tree or graph data structures. The algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a graph) and explores as far as possible along each branch before backtracking. 7 | 8 | The time and space analysis of DFS differs according to its application area. In theoretical computer science, DFS is typically used to traverse an entire graph, and takes time Θ(|V| + |E|),[4] linear in the size of the graph. In these applications it also uses space O(|V|) in the worst case to store the stack of vertices on the current search path as well as the set of already-visited vertices. Thus, in this setting, the time and space bounds are the same as for breadth-first search and the choice of which of these two algorithms to use depends less on their complexity and more on the different properties of the vertex orderings the two algorithms produce. 9 | 10 | For applications of DFS in relation to specific domains, such as searching for solutions in artificial intelligence or web-crawling, the graph to be traversed is often either too large to visit in its entirety or infinite (DFS may suffer from non-termination). In such cases, search is only performed to a limited depth; due to limited resources, such as memory or disk space, one typically does not use data structures to keep track of the set of all previously visited vertices. When search is performed to a limited depth, the time is still linear in terms of the number of expanded vertices and edges (although this number is not the same as the size of the entire graph because some vertices may be searched more than once and others not at all) but the space complexity of this variant of DFS is only proportional to the depth limit, and as a result, is much smaller than the space needed for searching to the same depth using breadth-first search. For such applications, DFS also lends itself much better to heuristic methods for choosing a likely-looking branch. When an appropriate depth limit is not known a priori, iterative deepening depth-first search applies DFS repeatedly with a sequence of increasing limits. In the artificial intelligence mode of analysis, with a branching factor greater than one, iterative deepening increases the running time by only a constant factor over the case in which the correct depth limit is known due to the geometric growth of the number of nodes per level. 11 | 12 | DFS may also be used to collect a sample of graph nodes. However, incomplete DFS, similarly to incomplete BFS, is biased towards nodes of high degree. 13 | 14 | 15 | A minimum spanning tree (MST) or minimum weight spanning tree is a subset of the edges of a connected, edge-weighted (un)directed graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. That is, it is a spanning tree whose sum of edge weights is as small as possible. More generally, any edge-weighted undirected graph (not necessarily connected) has a minimum spanning forest, which is a union of the minimum spanning trees for its connected components. 16 | 17 | There are quite a few use cases for minimum spanning trees. One example would be a telecommunications company trying to lay cable in a new neighborhood. If it is constrained to bury the cable only along certain paths (e.g. roads), then there would be a graph containing the points (e.g. houses) connected by those paths. Some of the paths might be more expensive, because they are longer, or require the cable to be buried deeper; these paths would be represented by edges with larger weights. Currency is an acceptable unit for edge weight – there is no requirement for edge lengths to obey normal rules of geometry such as the triangle inequality. A spanning tree for that graph would be a subset of those paths that has no cycles but still connects every house; there might be several spanning trees possible. A minimum spanning tree would be one with the lowest total cost, representing the least expensive path for laying the cable. 18 | 19 | 20 | Reference : https://en.wikipedia.org/wiki/Breadth-first_search 21 | https://en.wikipedia.org/wiki/Depth-first_search 22 | -------------------------------------------------------------------------------- /Recursive_Traversals.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void inOrderTraversal(struct node *node) 4 | { 5 | if (node == NULL) // if tree is empty 6 | return; 7 | 8 | inOrderTraversal(node->leftNode); 9 | printf("\t%d\t", node->data); 10 | inOrderTraversal(node->rightNode); 11 | } 12 | 13 | void preOrderTraversal(struct node *node) 14 | { 15 | if (node == NULL) // if tree is empty 16 | return; 17 | 18 | printf("\t%d\t", node->data); 19 | preOrderTraversal(node->leftNode); 20 | preOrderTraversal(node->rightNode); 21 | } 22 | 23 | void postOrderTraversal(struct node *node) 24 | { 25 | if (node == NULL) // if tree is empty 26 | return; 27 | 28 | postOrderTraversal(node->leftNode); 29 | postOrderTraversal(node->rightNode); 30 | printf("\t%d\t", node->data); 31 | } 32 | 33 | int main(void) 34 | { 35 | /* traversals can be done by simply invoking the 36 | function with a pointer to the root node. 37 | */ 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Red-BlackTree_implem.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct node 6 | { 7 | int val; 8 | struct node *par; 9 | struct node *left; 10 | struct node *right; 11 | int color; 12 | } Node; 13 | 14 | // Create a new node 15 | Node *newNode(int val, Node *par) 16 | { 17 | Node *create = (Node *)(malloc(sizeof(Node))); 18 | create->val = val; 19 | create->par = par; 20 | create->left = NULL; 21 | create->right = NULL; 22 | create->color = 1; 23 | } 24 | 25 | // Check if the node is the leaf 26 | int isLeaf(Node *n) 27 | { 28 | if (n->left == NULL && n->right == NULL) 29 | { 30 | return 1; 31 | } 32 | return 0; 33 | } 34 | 35 | // Left Rotate 36 | Node *leftRotate(Node *node) 37 | { 38 | Node *parent = node->par; 39 | Node *grandParent = parent->par; 40 | 41 | parent->right = node->left; 42 | if (node->left != NULL) 43 | { 44 | node->left->par = parent; 45 | } 46 | node->par = grandParent; 47 | parent->par = node; 48 | node->left = parent; 49 | if (grandParent != NULL) 50 | { 51 | if (grandParent->right == parent) 52 | { 53 | grandParent->right = node; 54 | } 55 | else 56 | { 57 | grandParent->left = node; 58 | } 59 | } 60 | return node; 61 | } 62 | 63 | // Right Rotate 64 | Node *rightRotate(Node *node) 65 | { 66 | Node *parent = node->par; 67 | Node *grandParent = parent->par; 68 | 69 | parent->left = node->right; 70 | if (node->right != NULL) 71 | { 72 | node->right->par = parent; 73 | } 74 | node->par = grandParent; 75 | parent->par = node; 76 | node->right = parent; 77 | if (grandParent != NULL) 78 | { 79 | if (grandParent->right == parent) 80 | { 81 | grandParent->right = node; 82 | } 83 | else 84 | { 85 | grandParent->left = node; 86 | } 87 | } 88 | return node; 89 | } 90 | 91 | // Check the node after the insertion step 92 | void checkNode(Node *node) 93 | { 94 | // If the node is the root 95 | if (node == NULL || node->par == NULL) 96 | { 97 | return; 98 | } 99 | Node *child = node; 100 | // If it is a black node or its parent is a black node 101 | if (node->color == 0 || (node->par)->color == 0) 102 | { 103 | // Dont Do Anything 104 | return; 105 | } 106 | 107 | // Both parent and child are red 108 | // Check For Uncle 109 | Node *parent = node->par; 110 | Node *grandParent = parent->par; 111 | 112 | // If grandParent is NULL, then parent is the root. 113 | // Just make the root black. 114 | if (grandParent == NULL) 115 | { 116 | parent->color = 0; 117 | return; 118 | } 119 | 120 | // If both the children of the grandParent are red 121 | if (grandParent->right != NULL && (grandParent->right)->color == 1 && 122 | grandParent->left != NULL && (grandParent->left)->color == 1) 123 | { 124 | // Make the grandParent red and both of its children black 125 | (grandParent->right)->color = 0; 126 | (grandParent->left)->color = 0; 127 | grandParent->color = 1; 128 | return; 129 | } 130 | else 131 | { 132 | // The only option left is rotation. 133 | Node *greatGrandParent = grandParent->par; 134 | // Right Case 135 | if (grandParent->right == parent) 136 | { 137 | // Right Right Case 138 | if (parent->right == node) 139 | { 140 | grandParent->right = parent->left; 141 | if (parent->left != NULL) 142 | { 143 | (parent->left)->par = grandParent; 144 | } 145 | parent->left = grandParent; 146 | grandParent->par = parent; 147 | 148 | // Attach to existing Tree; 149 | parent->par = greatGrandParent; 150 | if (greatGrandParent != NULL) 151 | { 152 | if (greatGrandParent->left != NULL && 153 | greatGrandParent->left == grandParent) 154 | { 155 | greatGrandParent->left = parent; 156 | } 157 | else 158 | { 159 | greatGrandParent->right = parent; 160 | } 161 | } 162 | 163 | // Change the colors 164 | parent->color = 0; 165 | grandParent->color = 1; 166 | } 167 | else 168 | { // Right Left Case 169 | // First step -> Parent Child Rotation 170 | parent->left = child->right; 171 | if (child->right != NULL) 172 | { 173 | (child->right)->par = parent; 174 | } 175 | child->right = parent; 176 | parent->par = child; 177 | 178 | // Second step -> Child and GrandParent Rotation 179 | grandParent->right = child->left; 180 | if (child->left != NULL) 181 | { 182 | (child->left)->par = grandParent; 183 | } 184 | child->left = grandParent; 185 | grandParent->par = child; 186 | 187 | // Attach to the existing tree 188 | child->par = greatGrandParent; 189 | if (greatGrandParent != NULL) 190 | { 191 | if (greatGrandParent->left != NULL && 192 | greatGrandParent->left == grandParent) 193 | { 194 | greatGrandParent->left = child; 195 | } 196 | else 197 | { 198 | greatGrandParent->right = child; 199 | } 200 | } 201 | 202 | // Change The Colors 203 | child->color = 0; 204 | grandParent->color = 1; 205 | } 206 | } 207 | else 208 | { // Left Case 209 | // Left Left Case 210 | if (parent->left == node) 211 | { 212 | grandParent->left = parent->right; 213 | if (parent->right != NULL) 214 | { 215 | (parent->right)->par = grandParent; 216 | } 217 | parent->right = grandParent; 218 | grandParent->par = parent; 219 | 220 | // Attach to existing Tree; 221 | parent->par = greatGrandParent; 222 | if (greatGrandParent != NULL) 223 | { 224 | if (greatGrandParent->left != NULL && 225 | greatGrandParent->left == grandParent) 226 | { 227 | greatGrandParent->left = parent; 228 | } 229 | else 230 | { 231 | greatGrandParent->right = parent; 232 | } 233 | } 234 | 235 | // Change the colors 236 | parent->color = 0; 237 | grandParent->color = 1; 238 | } 239 | else 240 | { // Left Right Case 241 | 242 | // First step -> Parent Child Rotation 243 | parent->right = child->left; 244 | if (child->left != NULL) 245 | { 246 | (child->left)->par = parent; 247 | } 248 | child->left = parent; 249 | parent->par = child; 250 | 251 | // Second step -> Child and GrandParent Rotation 252 | grandParent->left = child->right; 253 | if (child->right != NULL) 254 | { 255 | (child->right)->par = grandParent; 256 | } 257 | child->right = grandParent; 258 | grandParent->par = child; 259 | 260 | // Attach to the existing tree 261 | child->par = greatGrandParent; 262 | if (greatGrandParent != NULL) 263 | { 264 | if (greatGrandParent->left != NULL && 265 | greatGrandParent->left == grandParent) 266 | { 267 | greatGrandParent->left = child; 268 | } 269 | else 270 | { 271 | greatGrandParent->right = child; 272 | } 273 | } 274 | 275 | // Change The Colors 276 | child->color = 0; 277 | grandParent->color = 1; 278 | } 279 | } 280 | } 281 | } 282 | 283 | // To insert a node in the existing tree 284 | void insertNode(int val, Node **root) 285 | { 286 | Node *buffRoot = *root; 287 | while (buffRoot) 288 | { 289 | if (buffRoot->val > val) 290 | { 291 | // Go left 292 | if (buffRoot->left != NULL) 293 | { 294 | buffRoot = buffRoot->left; 295 | } 296 | else 297 | { 298 | // Insert The Node 299 | Node *toInsert = newNode(val, buffRoot); 300 | buffRoot->left = toInsert; 301 | buffRoot = toInsert; 302 | 303 | // Check For Double Red Problems 304 | break; 305 | } 306 | } 307 | else 308 | { 309 | // Go right 310 | if (buffRoot->right != NULL) 311 | { 312 | buffRoot = buffRoot->right; 313 | } 314 | else 315 | { 316 | // Insert The Node 317 | Node *toInsert = newNode(val, buffRoot); 318 | buffRoot->right = toInsert; 319 | buffRoot = toInsert; 320 | 321 | // Check For Double Red Problems 322 | break; 323 | } 324 | } 325 | } 326 | 327 | while (buffRoot != *root) 328 | { 329 | checkNode(buffRoot); 330 | if (buffRoot->par == NULL) 331 | { 332 | *root = buffRoot; 333 | break; 334 | } 335 | buffRoot = buffRoot->par; 336 | if (buffRoot == *root) 337 | { 338 | buffRoot->color = 0; 339 | } 340 | } 341 | } 342 | 343 | void checkForCase2(Node *toDelete, int delete, int fromDirection, Node **root) 344 | { 345 | if (toDelete == (*root)) 346 | { 347 | (*root)->color = 0; 348 | return; 349 | } 350 | 351 | if (!delete &&toDelete->color == 1) 352 | { 353 | if (!fromDirection) 354 | { 355 | if (toDelete->right != NULL) 356 | { 357 | toDelete->right->color = 1; 358 | } 359 | } 360 | else 361 | { 362 | if (toDelete->left != NULL) 363 | { 364 | toDelete->left->color = 1; 365 | } 366 | } 367 | toDelete->color = 0; 368 | return; 369 | } 370 | 371 | // Get the sibling for further inspection 372 | Node *sibling; 373 | Node *parent = toDelete->par; 374 | int locateChild = 0; // 0 if toDeleted is left of its parent else 1 375 | if (parent->right == toDelete) 376 | { 377 | sibling = parent->left; 378 | locateChild = 1; 379 | } 380 | else 381 | { 382 | sibling = parent->right; 383 | } 384 | 385 | // Case 2.1. i.e. if the any children of the sibling is red 386 | if ((sibling->right != NULL && sibling->right->color == 1) || 387 | (sibling->left != NULL && sibling->left->color == 1)) 388 | { 389 | if (sibling->right != NULL && sibling->right->color == 1) 390 | { 391 | // Sibling is left and child is right. i.e. LEFT RIGHT ROTATION 392 | if (locateChild == 1) 393 | { 394 | int parColor = parent->color; 395 | 396 | // Step 1: Left rotate sibling 397 | sibling = leftRotate(sibling->right); 398 | 399 | // Step 2: Right rotate updated sibling 400 | parent = rightRotate(sibling); 401 | 402 | // Check if the root is rotated 403 | if (parent->par == NULL) 404 | { 405 | *root = parent; 406 | } 407 | 408 | // Step 3: Update the colors 409 | parent->color = parColor; 410 | parent->left->color = 0; 411 | parent->right->color = 0; 412 | 413 | // Delete the node (present at parent->right->right) 414 | if (delete) 415 | { 416 | if (toDelete->left != NULL) 417 | { 418 | toDelete->left->par = parent->right; 419 | } 420 | parent->right->right = toDelete->left; 421 | free(toDelete); 422 | } 423 | } 424 | else 425 | { // Sibling is right and child is also right. i.e. LEFT LEFT 426 | // ROTATION 427 | 428 | int parColor = parent->color; 429 | 430 | // Left Rotate the sibling 431 | parent = leftRotate(sibling); 432 | 433 | // Check if the root is rotated 434 | if (parent->par == NULL) 435 | { 436 | *root = parent; 437 | } 438 | 439 | // Update Colors 440 | parent->color = parColor; 441 | parent->left->color = 0; 442 | parent->right->color = 0; 443 | 444 | // Delete the node (present at parent->left->left) 445 | if (delete) 446 | { 447 | if (toDelete->right != NULL) 448 | { 449 | toDelete->right->par = parent->left; 450 | } 451 | parent->left->left = toDelete->left; 452 | free(toDelete); 453 | } 454 | } 455 | } 456 | else 457 | { 458 | // Sibling is right and child is left. i.e. RIGHT LEFT ROTATION 459 | if (locateChild == 0) 460 | { 461 | int parColor = parent->color; 462 | 463 | // Step 1: Right rotate sibling 464 | sibling = rightRotate(sibling->left); 465 | 466 | // printf("%d - reached\n", sibling->val); 467 | // return; 468 | 469 | // Step 2: Left rotate updated sibling 470 | parent = leftRotate(sibling); 471 | 472 | // Check if the root is rotated 473 | if (parent->par == NULL) 474 | { 475 | *root = parent; 476 | } 477 | 478 | // Step 3: Update the colors 479 | parent->color = parColor; 480 | parent->left->color = 0; 481 | parent->right->color = 0; 482 | 483 | // Delete the node (present at parent->left->left) 484 | if (delete) 485 | { 486 | if (toDelete->right != NULL) 487 | { 488 | toDelete->right->par = parent->left; 489 | } 490 | parent->left->left = toDelete->right; 491 | free(toDelete); 492 | } 493 | } 494 | else 495 | { // Sibling is left and child is also left. i.e. RIGHT RIGHT 496 | // ROTATION 497 | 498 | int parColor = parent->color; 499 | 500 | // Right Rotate the sibling 501 | parent = rightRotate(sibling); 502 | 503 | // Check if the root is rotated 504 | if (parent->par == NULL) 505 | { 506 | *root = parent; 507 | } 508 | 509 | // Update Colors 510 | parent->color = parColor; 511 | parent->left->color = 0; 512 | parent->right->color = 0; 513 | 514 | // Delete the node (present at parent->right->right) 515 | if (delete) 516 | { 517 | if (toDelete->left != NULL) 518 | { 519 | toDelete->left->par = parent->right; 520 | } 521 | parent->right->right = toDelete->left; 522 | free(toDelete); 523 | } 524 | } 525 | } 526 | } 527 | else if (sibling->color == 0) 528 | { // Make the sibling red and recur for its parent 529 | 530 | // Recolor the sibling 531 | sibling->color = 1; 532 | 533 | // Delete if necessary 534 | if (delete) 535 | { 536 | if (locateChild) 537 | { 538 | toDelete->par->right = toDelete->left; 539 | if (toDelete->left != NULL) 540 | { 541 | toDelete->left->par = toDelete->par; 542 | } 543 | } 544 | else 545 | { 546 | toDelete->par->left = toDelete->right; 547 | if (toDelete->right != NULL) 548 | { 549 | toDelete->right->par = toDelete->par; 550 | } 551 | } 552 | } 553 | 554 | checkForCase2(parent, 0, locateChild, root); 555 | } 556 | else 557 | { // Bring the sibling on top and apply 2.1 or 2.2 accordingly 558 | if (locateChild) 559 | { // Right Rotate 560 | 561 | toDelete->par->right = toDelete->left; 562 | if (toDelete->left != NULL) 563 | { 564 | toDelete->left->par = toDelete->par; 565 | } 566 | 567 | parent = rightRotate(sibling); 568 | 569 | // Check if the root is rotated 570 | if (parent->par == NULL) 571 | { 572 | *root = parent; 573 | } 574 | 575 | parent->color = 0; 576 | parent->right->color = 1; 577 | checkForCase2(parent->right, 0, 1, root); 578 | } 579 | else 580 | { // Left Rotate 581 | 582 | toDelete->par->left = toDelete->right; 583 | if (toDelete->right != NULL) 584 | { 585 | toDelete->right->par = toDelete->par; 586 | } 587 | parent = leftRotate(sibling); 588 | 589 | // Check if the root is rotated 590 | if (parent->par == NULL) 591 | { 592 | *root = parent; 593 | } 594 | 595 | printf("\nroot - %d - %d\n", parent->val, parent->left->val); 596 | 597 | parent->color = 0; 598 | parent->left->color = 1; 599 | checkForCase2(parent->left, 0, 0, root); 600 | } 601 | } 602 | } 603 | 604 | // To delete a node from the tree 605 | void deleteNode(int val, Node **root) 606 | { 607 | Node *buffRoot = *root; 608 | 609 | // Search for the element in the tree 610 | while (1) 611 | { 612 | if (val == buffRoot->val) 613 | { 614 | // Node Found 615 | break; 616 | } 617 | 618 | if (val > buffRoot->val) 619 | { 620 | if (buffRoot->right != NULL) 621 | { 622 | buffRoot = buffRoot->right; 623 | } 624 | else 625 | { 626 | printf("Node Not Found!!!"); 627 | return; 628 | } 629 | } 630 | else 631 | { 632 | if (buffRoot->left != NULL) 633 | { 634 | buffRoot = buffRoot->left; 635 | } 636 | else 637 | { 638 | printf("Node Not Found!!!"); 639 | return; 640 | } 641 | } 642 | } 643 | 644 | Node *toDelete = buffRoot; 645 | 646 | // Look for the leftmost of right node or right most of left node 647 | if (toDelete->left != NULL) 648 | { 649 | toDelete = toDelete->left; 650 | while (toDelete->right != NULL) 651 | { 652 | toDelete = toDelete->right; 653 | } 654 | } 655 | else if (toDelete->right != NULL) 656 | { 657 | toDelete = toDelete->right; 658 | while (toDelete->left != NULL) 659 | { 660 | toDelete = toDelete->left; 661 | } 662 | } 663 | 664 | if (toDelete == *root) 665 | { 666 | *root = NULL; 667 | return; 668 | } 669 | 670 | // Swap the values 671 | buffRoot->val = toDelete->val; 672 | toDelete->val = val; 673 | 674 | // Checking for case 1 675 | if (toDelete->color == 1 || 676 | (toDelete->left != NULL && toDelete->left->color == 1) || 677 | (toDelete->right != NULL && toDelete->right->color == 1)) 678 | { 679 | // if it is a leaf 680 | if (toDelete->left == NULL && toDelete->right == NULL) 681 | { 682 | // Delete instantly 683 | if (toDelete->par->left == toDelete) 684 | { 685 | toDelete->par->left = NULL; 686 | } 687 | else 688 | { 689 | toDelete->par->right = NULL; 690 | } 691 | } 692 | else 693 | { // else its child should be red 694 | 695 | // Check for the exitstence of left node 696 | if (toDelete->left != NULL) 697 | { 698 | // The node should be right to its parent 699 | toDelete->par->right = toDelete->left; 700 | toDelete->left->par = toDelete->par; 701 | toDelete->left->color = 1; 702 | } 703 | else 704 | { // else the right node should be red 705 | toDelete->par->left = toDelete->right; 706 | toDelete->right->par = toDelete->par; 707 | toDelete->right->color = 1; 708 | } 709 | } 710 | 711 | // Remove the node from memory 712 | free(toDelete); 713 | } 714 | else 715 | { // Case 2 716 | checkForCase2(toDelete, 1, ((toDelete->par->right == toDelete)), root); 717 | } 718 | } 719 | 720 | void printInorder(Node *root) 721 | { 722 | if (root != NULL) 723 | { 724 | printInorder(root->left); 725 | printf("%d c-%d ", root->val, root->color); 726 | printInorder(root->right); 727 | } 728 | } 729 | 730 | void checkBlack(Node *temp, int c) 731 | { 732 | if (temp == NULL) 733 | { 734 | printf("%d ", c); 735 | return; 736 | } 737 | if (temp->color == 0) 738 | { 739 | c++; 740 | } 741 | checkBlack(temp->left, c); 742 | checkBlack(temp->right, c); 743 | } 744 | 745 | int main() 746 | { 747 | Node *root = NULL; 748 | int scanValue, choice = 1; 749 | printf( 750 | "1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - Quit\n\nPlease " 751 | "Enter the Choice - "); 752 | scanf("%d", &choice); 753 | while (choice) 754 | { 755 | switch (choice) 756 | { 757 | case 1: 758 | printf("\n\nPlease Enter A Value to insert - "); 759 | scanf("%d", &scanValue); 760 | if (root == NULL) 761 | { 762 | root = newNode(scanValue, NULL); 763 | root->color = 0; 764 | } 765 | else 766 | { 767 | insertNode(scanValue, &root); 768 | } 769 | printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue); 770 | break; 771 | case 2: 772 | printf("\n\nPlease Enter A Value to Delete - "); 773 | scanf("%d", &scanValue); 774 | deleteNode(scanValue, &root); 775 | printf("\nSuccessfully Inserted %d in the tree\n\n", scanValue); 776 | break; 777 | case 3: 778 | printf("\nInorder Traversel - "); 779 | printInorder(root); 780 | printf("\n\n"); 781 | // checkBlack(root,0); 782 | // printf("\n"); 783 | break; 784 | default: 785 | if (root != NULL) 786 | { 787 | printf("Root - %d\n", root->val); 788 | } 789 | } 790 | printf( 791 | "1 - Input\n2 - Delete\n3 - Inorder Traversel\n0 - " 792 | "Quit\n\nPlease Enter the Choice - "); 793 | scanf("%d", &choice); 794 | } 795 | } 796 | -------------------------------------------------------------------------------- /Searching-a-character.java: -------------------------------------------------------------------------------- 1 | // Java program to illustrate to find a character 2 | // in the string. 3 | import java.io.*; 4 | 5 | class GFG 6 | { 7 | public static void main (String[] args) 8 | { 9 | // This is a string in which a character 10 | // to be searched. 11 | String str = "GeeksforGeeks is a computer science portal"; 12 | 13 | // Returns index of first occurrence of character. 14 | int firstIndex = str.indexOf('s'); 15 | System.out.println("First occurrence of char 's'" + 16 | " is found at : " + firstIndex); 17 | 18 | // Returns index of last occurrence specified character. 19 | int lastIndex = str.lastIndexOf('s'); 20 | System.out.println("Last occurrence of char 's' is" + 21 | " found at : " + lastIndex); 22 | 23 | // Index of the first occurrence of specified char 24 | // after the specified index if found. 25 | int first_in = str.indexOf('s', 10); 26 | System.out.println("First occurrence of char 's'" + 27 | " after index 10 : " + first_in); 28 | 29 | int last_in = str.lastIndexOf('s', 20); 30 | System.out.println("Last occurrence of char 's'" + 31 | " after index 20 is : " + last_in); 32 | 33 | // gives ASCII value of character at location 20 34 | int char_at = str.charAt(20); 35 | System.out.println("Character at location 20: " + 36 | char_at); 37 | 38 | // throws StringIndexOutOfBoundsException 39 | // char_at = str.charAt(50); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Vertical_ord_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for printing vertical order of a given binary tree 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Structure for a binary tree node 8 | struct Node 9 | { 10 | int key; 11 | Node *left, *right; 12 | }; 13 | 14 | // A utility function to create a new node 15 | struct Node* newNode(int key) 16 | { 17 | struct Node* node = new Node; 18 | node->key = key; 19 | node->left = node->right = NULL; 20 | return node; 21 | } 22 | 23 | // Utility function to store vertical order in map 'm' 24 | // 'hd' is horigontal distance of current node from root. 25 | // 'hd' is initally passed as 0 26 | void getVerticalOrder(Node* root, int hd, map> &m) 27 | { 28 | // Base case 29 | if (root == NULL) 30 | return; 31 | 32 | // Store current node in map 'm' 33 | m[hd].push_back(root->key); 34 | 35 | // Store nodes in left subtree 36 | getVerticalOrder(root->left, hd-1, m); 37 | 38 | // Store nodes in right subtree 39 | getVerticalOrder(root->right, hd+1, m); 40 | } 41 | 42 | // The main function to print vertical oder of a binary tree 43 | // with given root 44 | void printVerticalOrder(Node* root) 45 | { 46 | // Create a map and store vertical oder in map using 47 | // function getVerticalOrder() 48 | map < int,vector > m; 49 | int hd = 0; 50 | getVerticalOrder(root, hd,m); 51 | 52 | // Traverse the map and print nodes at every horigontal 53 | // distance (hd) 54 | map< int,vector > :: iterator it; 55 | for (it=m.begin(); it!=m.end(); it++) 56 | { 57 | for (int i=0; isecond.size(); ++i) 58 | cout << it->second[i] << " "; 59 | cout << endl; 60 | } 61 | } 62 | 63 | // Driver program to test above functions 64 | int main() 65 | { 66 | Node *root = newNode(1); 67 | root->left = newNode(2); 68 | root->right = newNode(3); 69 | root->left->left = newNode(4); 70 | root->left->right = newNode(5); 71 | root->right->left = newNode(6); 72 | root->right->right = newNode(7); 73 | root->right->left->right = newNode(8); 74 | root->right->right->right = newNode(9); 75 | cout << "Vertical order traversal is n"; 76 | printVerticalOrder(root); 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /array-rotation-reversal-algorithm.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for re 2 | #include 3 | using namespace std; 4 | 5 | /*Function to reverse arr[] from index start to end*/ 6 | void rvereseArray(int arr[], int start, int end) 7 | { 8 | while (start < end) 9 | { 10 | int temp = arr[start]; 11 | arr[start] = arr[end]; 12 | arr[end] = temp; 13 | start++; 14 | end--; 15 | } 16 | } 17 | 18 | /* Function to left rotate arr[] of size n by d */ 19 | void leftRotate(int arr[], int d, int n) 20 | { 21 | rvereseArray(arr, 0, d-1); 22 | rvereseArray(arr, d, n-1); 23 | rvereseArray(arr, 0, n-1); 24 | } 25 | 26 | // Function to print an array 27 | void printArray(int arr[], int size) 28 | { 29 | for (int i = 0; i < size; i++) 30 | cout << arr[i] << " "; 31 | } 32 | 33 | /* Driver program to test above functions */ 34 | int main() 35 | { 36 | int arr[] = {1, 2, 3, 4, 5, 6, 7}; 37 | int n = sizeof(arr)/sizeof(arr[0]); 38 | int d = 2; 39 | 40 | // Function calling 41 | leftRotate(arr, d, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /array-rotation-through-juggling-algorithm.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to rotate an array by 2 | // d elements 3 | #include 4 | using namespace std; 5 | 6 | /*Fuction to get gcd of a and b*/ 7 | int gcd(int a, int b) 8 | { 9 | if (b == 0) 10 | return a; 11 | 12 | else 13 | return gcd(b, a % b); 14 | } 15 | 16 | /*Function to left rotate arr[] of siz n by d*/ 17 | void leftRotate(int arr[], int d, int n) 18 | { 19 | for (int i = 0; i < gcd(d, n); i++) { 20 | /* move i-th values of blocks */ 21 | int temp = arr[i]; 22 | int j = i; 23 | 24 | while (1) { 25 | int k = j + d; 26 | if (k >= n) 27 | k = k - n; 28 | 29 | if (k == i) 30 | break; 31 | 32 | arr[j] = arr[k]; 33 | j = k; 34 | } 35 | arr[j] = temp; 36 | } 37 | } 38 | 39 | // Function to print an array 40 | void printArray(int arr[], int size) 41 | { 42 | for (int i = 0; i < size; i++) 43 | cout << arr[i] << " "; 44 | } 45 | 46 | /* Driver program to test above functions */ 47 | int main() 48 | { 49 | int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; 50 | int n = sizeof(arr) / sizeof(arr[0]); 51 | 52 | // Function calling 53 | leftRotate(arr, 2, n); 54 | 55 | return 0; 56 | } 57 | 58 | -------------------------------------------------------------------------------- /check-sort-rotate.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of above approach 2 | #include 3 | using namespace std; 4 | 5 | // Function to check if it is possible 6 | bool isPossible(int a[], int n) 7 | { 8 | // step 1 9 | if (is_sorted(a, a + n)) { 10 | cout << "Possible" << endl; 11 | } 12 | 13 | else { 14 | 15 | // break where a[i] > a[i+1] 16 | bool flag = true; 17 | int i; 18 | for (i = 0; i < n - 1; i++) { 19 | if (a[i] > a[i + 1]) { 20 | break; 21 | } 22 | } 23 | // break point + 1 24 | i++; 25 | 26 | // check whether the sequence is 27 | // further increasing or not 28 | for (int k = i; k < n - 1; k++) { 29 | if (a[k] > a[k + 1]) { 30 | flag = false; 31 | break; 32 | } 33 | } 34 | 35 | // If not increasing after break point 36 | if (!flag) 37 | return false; 38 | 39 | else { 40 | 41 | // last element <= First element 42 | if (a[n - 1] <= a[0]) 43 | return true; 44 | 45 | else 46 | return false; 47 | } 48 | } 49 | } 50 | 51 | // Driver code 52 | int main() 53 | { 54 | 55 | int arr[] = { 3, 1, 2, 2, 3 }; 56 | int n = sizeof(arr) / sizeof(arr[0]); 57 | 58 | if (isPossible(arr, n)) 59 | cout << "Possible"; 60 | 61 | else 62 | cout << "Not Possible"; 63 | 64 | return 65 | 0; 66 | } 67 | 68 | -------------------------------------------------------------------------------- /checking-panagram.cpp: -------------------------------------------------------------------------------- 1 | // A C++ Program to check if the given 2 | // string is a pangram or not 3 | #include 4 | using namespace std; 5 | 6 | // Returns true if the string is pangram else false 7 | bool checkPangram (string &str) 8 | { 9 | // Create a hash table to mark the characters 10 | // present in the string 11 | vector mark(26, false); 12 | 13 | // For indexing in mark[] 14 | int index; 15 | 16 | // Traverse all characters 17 | for (int i=0; i 2 | using namespace std; 3 | #include 4 | 5 | int N[200],count,ans; 6 | void printCombination1(int [], int, int,int); 7 | void printCombination2(int [], int, int,int); 8 | void combinationUtil1(int [], int [], int, int, int, int,int); 9 | void combinationUtil2(int [], int [], int, int, int, int,int); 10 | int main() 11 | { 12 | int a[100],T,k; 13 | cin>>T; 14 | for(int i=0;i>N[i]; 17 | } 18 | for(int g=0;g= r-index; i++) 105 | { 106 | data[index] = arr[i]; 107 | combinationUtil1(arr, data, i+1, end, index+1, r,g); 108 | } 109 | } 110 | 111 | void combinationUtil2(int arr[], int data[], int start, int end, 112 | int index, int r,int g) 113 | { 114 | if (index == r) 115 | { 116 | if(N[g] == (data[0]*data[1]) + (data[0]*data[1])) 117 | ans=1; 118 | return; 119 | } 120 | 121 | for (int i=start; i<=end && end-i+1 >= r-index; i++) 122 | { 123 | data[index] = arr[i]; 124 | combinationUtil2(arr, data, i+1, end, index+1, r,g); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /count-all-pairs-with-given-sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ program to find number of pairs with 3 | // a given sum in a sorted and rotated array. 4 | #include 5 | using namespace std; 6 | 7 | // This function returns count of number of pairs 8 | // with sum equals to x. 9 | int pairsInSortedRotated(int arr[], int n, int x) 10 | { 11 | // Find the pivot element. Pivot element 12 | // is maximum element of array. 13 | int i; 14 | for (i = 0; i < n-1; i++) 15 | if (arr[i] > arr[i+1]) 16 | break; 17 | 18 | // l is index of minimum element. 19 | int l = (i + 1) % n; 20 | 21 | // r is index of maximum element. 22 | int r = i; 23 | 24 | // Variable to store count of number 25 | // of pairs. 26 | int cnt = 0; 27 | 28 | // Find sum of pair formed by arr[l] and 29 | // and arr[r] and update l, r and cnt 30 | // accordingly. 31 | while (l != r) 32 | { 33 | // If we find a pair with sum x, then 34 | // increment cnt, move l and r to 35 | // next element. 36 | if (arr[l] + arr[r] == x){ 37 | cnt++; 38 | 39 | // This condition is required to 40 | // be checked, otherwise l and r 41 | // will cross each other and loop 42 | // will never terminate. 43 | if(l == (r - 1 + n) % n){ 44 | return cnt; 45 | } 46 | 47 | l = (l + 1) % n; 48 | r = (r - 1 + n) % n; 49 | } 50 | 51 | // If current pair sum is less, move to 52 | // the higher sum side. 53 | else if (arr[l] + arr[r] < x) 54 | l = (l + 1) % n; 55 | 56 | // If current pair sum is greater, move 57 | // to the lower sum side. 58 | else 59 | r = (n + r - 1)%n; 60 | } 61 | 62 | return cnt; 63 | } 64 | 65 | /* Driver program to test above function */ 66 | int main() 67 | { 68 | int arr[] = {11, 15, 6, 7, 9, 10}; 69 | int sum = 16; 70 | int n = sizeof(arr)/sizeof(arr[0]); 71 | 72 | cout << pairsInSortedRotated(arr, n, sum); 73 | 74 | return 0; 75 | } 76 | 77 | 78 | Output: 79 | -------------------------------------------------------------------------------- /count-digits.c: -------------------------------------------------------------------------------- 1 | //function to count digits 2 | int countDigits(int num) 3 | { 4 | static int count=0; 5 | 6 | if(num>0) 7 | { 8 | count++; 9 | countDigits(num/10); 10 | } 11 | else 12 | { 13 | return count; 14 | } 15 | } 16 | int main() 17 | { 18 | int number; 19 | int count=0; 20 | 21 | printf("Enter a positive integer number: "); 22 | scanf("%d",&number); 23 | 24 | count=countDigits(number); 25 | 26 | printf("Total digits in number %d is: %d\n",number,count); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /count-divisible.cpp: -------------------------------------------------------------------------------- 1 | 2 | // CPP program to count divisible pairs. 3 | #include 4 | using namespace std; 5 | 6 | int countDivisibles(int arr[], int n) 7 | { 8 | int res = 0; 9 | 10 | // Iterate through all pairs 11 | for (int i=0; i 4 | #include 5 | 6 | using namespace std; 7 | 8 | // method to find maximum colinear point 9 | int maxPointOnSameLine(vector< pair > points) 10 | { 11 | int N = points.size(); 12 | if (N < 2) 13 | return N; 14 | 15 | int maxPoint = 0; 16 | int curMax, overlapPoints, verticalPoints; 17 | 18 | // here since we are using unordered_map 19 | // which is based on hash function 20 | //But by default we don't have hash function for pairs 21 | //so we'll use hash function defined in Boost library 22 | unordered_map, int,boost:: 23 | hash > > slopeMap; 24 | 25 | // looping for each point 26 | for (int i = 0; i < N; i++) 27 | { 28 | curMax = overlapPoints = verticalPoints = 0; 29 | 30 | // looping from i + 1 to ignore same pair again 31 | for (int j = i + 1; j < N; j++) 32 | { 33 | // If both point are equal then just 34 | // increase overlapPoint count 35 | if (points[i] == points[j]) 36 | overlapPoints++; 37 | 38 | // If x co-ordinate is same, then both 39 | // point are vertical to each other 40 | else if (points[i].first == points[j].first) 41 | verticalPoints++; 42 | 43 | else 44 | { 45 | int yDif = points[j].second - points[i].second; 46 | int xDif = points[j].first - points[i].first; 47 | int g = __gcd(xDif, yDif); 48 | 49 | // reducing the difference by their gcd 50 | yDif /= g; 51 | xDif /= g; 52 | 53 | // increasing the frequency of current slope 54 | // in map 55 | slopeMap[make_pair(yDif, xDif)]++; 56 | curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]); 57 | } 58 | 59 | curMax = max(curMax, verticalPoints); 60 | } 61 | 62 | // updating global maximum by current point's maximum 63 | maxPoint = max(maxPoint, curMax + overlapPoints + 1); 64 | 65 | // printf("maximum colinear point 66 | // which contains current point 67 | // are : %d\n", curMax + overlapPoints + 1); 68 | slopeMap.clear(); 69 | } 70 | 71 | return maxPoint; 72 | } 73 | 74 | // Driver code 75 | int main() 76 | { 77 | const int N = 6; 78 | int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2}, 79 | {3, 3}, {3, 4}}; 80 | 81 | vector< pair > points; 82 | for (int i = 0; i < N; i++) 83 | points.push_back(make_pair(arr[i][0], arr[i][1])); 84 | 85 | cout << maxPointOnSameLine(points) << endl; 86 | 87 | return 0; 88 | } 89 | -------------------------------------------------------------------------------- /cyclically-rotate-array.cpp: -------------------------------------------------------------------------------- 1 | // C++ code for program 2 | // to cyclically rotate 3 | // an array by one 4 | # include 5 | using namespace std; 6 | 7 | void rotate(int arr[], int n) 8 | { 9 | int x = arr[n - 1], i; 10 | for (i = n - 1; i > 0; i--) 11 | arr[i] = arr[i - 1]; 12 | arr[0] = x; 13 | } 14 | 15 | // Driver code 16 | int main() 17 | { 18 | int arr[] = {1, 2, 3, 4, 5}, i; 19 | int n = sizeof(arr) / 20 | sizeof(arr[0]); 21 | 22 | cout << "Given array is \n"; 23 | for (i = 0; i < n; i++) 24 | cout << arr[i]; 25 | 26 | rotate(arr, n); 27 | 28 | cout << "\nRotated array is\n"; 29 | for (i = 0; i < n; i++) 30 | cout << arr[i]; 31 | 32 | 33 | return 0; 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /delete-a-linked-list.cpp: -------------------------------------------------------------------------------- 1 | / A complete working C program to delete a node in a linked list 2 | // at a given position 3 | #include 4 | #include 5 | 6 | // A linked list node 7 | struct Node 8 | { 9 | int data; 10 | struct Node *next; 11 | }; 12 | 13 | /* Given a reference (pointer to pointer) to the head of a list 14 | and an int, inserts a new node on the front of the list. */ 15 | void push(struct Node** head_ref, int new_data) 16 | { 17 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 18 | new_node->data = new_data; 19 | new_node->next = (*head_ref); 20 | (*head_ref) = new_node; 21 | } 22 | 23 | /* Given a reference (pointer to pointer) to the head of a list 24 | and a position, deletes the node at the given position */ 25 | void deleteNode(struct Node **head_ref, int position) 26 | { 27 | // If linked list is empty 28 | if (*head_ref == NULL) 29 | return; 30 | 31 | // Store head node 32 | struct Node* temp = *head_ref; 33 | 34 | // If head needs to be removed 35 | if (position == 0) 36 | { 37 | *head_ref = temp->next; // Change head 38 | free(temp); // free old head 39 | return; 40 | } 41 | 42 | // Find previous node of the node to be deleted 43 | for (int i=0; temp!=NULL && inext; 45 | 46 | // If position is more than number of ndoes 47 | if (temp == NULL || temp->next == NULL) 48 | return; 49 | 50 | // Node temp->next is the node to be deleted 51 | // Store pointer to the next of node to be deleted 52 | struct Node *next = temp->next->next; 53 | 54 | // Unlink the node from linked list 55 | free(temp->next); // Free memory 56 | 57 | temp->next = next; // Unlink the deleted node from list 58 | } 59 | 60 | // This function prints contents of linked list starting from 61 | // the given node 62 | void printList(struct Node *node) 63 | { 64 | while (node != NULL) 65 | { 66 | printf(" %d ", node->data); 67 | node = node->next; 68 | } 69 | } 70 | 71 | /* Drier program to test above functions*/ 72 | int main() 73 | { 74 | /* Start with the empty list */ 75 | struct Node* head = NULL; 76 | 77 | push(&head, 7); 78 | push(&head, 1); 79 | push(&head, 3); 80 | push(&head, 2); 81 | push(&head, 8); 82 | 83 | puts("Created Linked List: "); 84 | printList(head); 85 | deleteNode(&head, 4); 86 | puts("\nLinked List after Deletion at position 4: "); 87 | printList(head); 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /element-at-index-rotated.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | // CPP code to rotate an array 4 | // and answer the index query 5 | #include 6 | using namespace std; 7 | 8 | // Function to compute the element at 9 | // given index 10 | int findElement(int arr[], int ranges[][2], 11 | int rotations, int index) 12 | { 13 | for (int i = rotations - 1; i >= 0; i--) { 14 | 15 | // Range[left...right] 16 | int left = ranges[i][0]; 17 | int right = ranges[i][1]; 18 | 19 | // Rotation will not have any effect 20 | if (left <= index && right >= index) { 21 | if (index == left) 22 | index = right; 23 | else 24 | index--; 25 | } 26 | } 27 | 28 | // Returning new element 29 | return arr[index]; 30 | } 31 | 32 | // Driver 33 | int main() 34 | { 35 | int arr[] = { 1, 2, 3, 4, 5 }; 36 | 37 | // No. of rotations 38 | int rotations = 2; 39 | 40 | // Ranges according to 0-based indexing 41 | int ranges[rotations][2] = { { 0, 2 }, { 0, 3 } }; 42 | 43 | int index = 1; 44 | 45 | cout << findElement(arr, ranges, rotations, index); 46 | 47 | return 0; 48 | 49 | } 50 | -------------------------------------------------------------------------------- /factorial-c.c: -------------------------------------------------------------------------------- 1 | /*C program to find factorial of a number using recursion.*/ 2 | 3 | #include 4 | 5 | //function for factorial 6 | long int factorial(int n) 7 | { 8 | if(n==1) return 1; 9 | return n*factorial(n-1); 10 | } 11 | int main() 12 | { 13 | int num; 14 | long int fact=0; 15 | 16 | printf("Enter an integer number: "); 17 | scanf("%d",&num); 18 | 19 | fact=factorial(num); 20 | printf("Factorial of %d is = %ld",num,fact); 21 | printf("\n"); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /fibonacci-rec.cpp: -------------------------------------------------------------------------------- 1 | /*C program to print fibonacii series till N terms.*/ 2 | 3 | #include 4 | 5 | //function to print fibonacii series 6 | void getFibonacii(int a,int b, int n) 7 | { 8 | int sum; 9 | if(n>0) 10 | { 11 | sum=a+b; 12 | printf("%d ",sum); 13 | a=b; 14 | b=sum; 15 | getFibonacii(a,b,n-1); 16 | } 17 | } 18 | int main() 19 | { 20 | int a,b,sum,n; 21 | int i; 22 | 23 | a=0; //first term 24 | b=1; //second term 25 | 26 | printf("Enter total number of terms: "); 27 | scanf("%d",&n); 28 | 29 | printf("Fibonacii series is : "); 30 | //print a and b as first and second terms of series 31 | printf("%d\t%d\t",a,b); 32 | //call function with (n-2) terms 33 | getFibonacii(a,b,n-2); 34 | printf("\n"); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /find-repetitive-element-1-n-1.cpp: -------------------------------------------------------------------------------- 1 | 2 | // CPP program to find the only repeating 3 | // element in an array where elements are 4 | // from 1 to n-1. 5 | #include 6 | using namespace std; 7 | 8 | int findRepeating(int arr[], int n) 9 | { 10 | unordered_set s; 11 | for (int i=0; i 3 | #include 4 | 5 | /* simple constructor */ 6 | Dictionary *create_dict(void) 7 | { 8 | Dictionary *p_dic = malloc(sizeof(Dictionary)); 9 | if (p_dic) 10 | { 11 | p_dic->number_of_elements = 0; 12 | 13 | /* initializes the elemens of the array with NULL-pointer */ 14 | for (int i = 0; i < MAXELEMENTS; i++) 15 | { 16 | p_dic->elements[i] = NULL; 17 | } 18 | 19 | return p_dic; 20 | } 21 | else 22 | { 23 | printf("unable to create a dictionary\n"); 24 | return NULL; 25 | } 26 | } 27 | 28 | /* 29 | utility function 30 | sdbm hash algorithm 31 | returns a hashcode for the given string 's' 32 | */ 33 | int get_hash(char s[]) 34 | { 35 | unsigned int hash_code = 0; 36 | 37 | /* iterates over string at each character */ 38 | for (int counter = 0; s[counter] != '\0'; counter++) 39 | { 40 | /* actual computing of the hash code */ 41 | hash_code = 42 | s[counter] + (hash_code << 6) + (hash_code << 16) - hash_code; 43 | } 44 | 45 | /* % modulo is for fitting the index in array. */ 46 | return hash_code % MAXELEMENTS; 47 | } 48 | 49 | int add_item_label(Dictionary *dic, char label[], void *item) 50 | { 51 | unsigned int index = get_hash(label); 52 | 53 | /* make sure index is fitting */ 54 | if (index < MAXELEMENTS) 55 | { 56 | dic->elements[index] = item; 57 | return 0; 58 | } 59 | 60 | /* error case */ 61 | return -1; 62 | } 63 | 64 | int add_item_index(Dictionary *dic, int index, void *item) 65 | { 66 | /* make sure whether this place is already given */ 67 | if (!dic->elements[index]) 68 | { 69 | dic->elements[index] = item; 70 | return 0; 71 | } 72 | 73 | /* error case */ 74 | return -1; 75 | } 76 | 77 | void *get_element_label(Dictionary *dict, char s[]) 78 | { 79 | int index = get_hash(s); 80 | if (dict->elements[index]) 81 | { 82 | return dict->elements[index]; 83 | } 84 | 85 | printf("None entry at given label\n"); 86 | return NULL; 87 | } 88 | 89 | void *get_element_index(Dictionary *dict, int index) 90 | { 91 | if (index >= 0 && index < MAXELEMENTS) 92 | { 93 | return dict->elements[index]; 94 | } 95 | 96 | printf("index out of bounds!\n"); 97 | return NULL; 98 | } 99 | 100 | void destroy(Dictionary *dict) { free(dict); } 101 | -------------------------------------------------------------------------------- /iterator.java: -------------------------------------------------------------------------------- 1 | 2 | // Java code to illustrate iterator() 3 | import java.util.*; 4 | 5 | public class ArrayDequeDemo { 6 | public static void main(String args[]) 7 | { 8 | // Creating an empty ArrayDeque 9 | Deque de_que = new ArrayDeque(); 10 | 11 | // Use add() method to add elements into the Queue 12 | de_que.add("Welcome"); 13 | de_que.add("To"); 14 | de_que.add("Geeks"); 15 | de_que.add("4"); 16 | de_que.add("Geeks"); 17 | 18 | // Displaying the ArrayDeque 19 | System.out.println("ArrayDeque: " + de_que); 20 | 21 | // Creating an iterator 22 | Iterator value = de_que.iterator(); 23 | 24 | // Displaying the values after iterating through the Deque 25 | System.out.println("The iterator values are: "); 26 | while (value.hasNext()) { 27 | System.out.println(value.next()); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /left-rotate-array.cpp: -------------------------------------------------------------------------------- 1 | 2 | // CPP implementation of left rotation of 3 | // an array K number of times 4 | #include 5 | using namespace std; 6 | 7 | // Function to leftRotate array multiple times 8 | void leftRotate(int arr[], int n, int k) 9 | { 10 | /* To get the starting point of rotated array */ 11 | int mod = k % n; 12 | 13 | // Prints the rotated array from start position 14 | for (int i = 0; i < n; i++) 15 | cout << (arr[(mod + i) % n]) << " "; 16 | 17 | cout << "\n"; 18 | } 19 | 20 | // Driver program 21 | int main() 22 | { 23 | int arr[] = { 1, 3, 5, 7, 9 }; 24 | int n = sizeof(arr) / sizeof(arr[0]); 25 | 26 | int k = 2; 27 | leftRotate(arr, n, k); 28 | 29 | k = 3; 30 | leftRotate(arr, n, k); 31 | 32 | k = 4; 33 | leftRotate(arr, n, k); 34 | 35 | return 0; 36 | } 37 | 38 | -------------------------------------------------------------------------------- /length-of-linked-list.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Iterative C++ program to find length 3 | // or count of nodes in a linked list 4 | #include 5 | using namespace std; 6 | 7 | /* Link list node */ 8 | class Node 9 | { 10 | public: 11 | int data; 12 | Node* next; 13 | }; 14 | 15 | /* Given a reference (pointer to pointer) to the head 16 | of a list and an int, push a new node on the front 17 | of the list. */ 18 | void push(Node** head_ref, int new_data) 19 | { 20 | /* allocate node */ 21 | Node* new_node =new Node(); 22 | 23 | /* put in the data */ 24 | new_node->data = new_data; 25 | 26 | /* link the old list off the new node */ 27 | new_node->next = (*head_ref); 28 | 29 | /* move the head to point to the new node */ 30 | (*head_ref) = new_node; 31 | } 32 | 33 | /* Counts no. of nodes in linked list */ 34 | int getCount(Node* head) 35 | { 36 | int count = 0; // Initialize count 37 | Node* current = head; // Initialize current 38 | while (current != NULL) 39 | { 40 | count++; 41 | current = current->next; 42 | } 43 | return count; 44 | } 45 | 46 | /* Driver program to test count function*/ 47 | int main() 48 | { 49 | /* Start with the empty list */ 50 | Node* head = NULL; 51 | 52 | /* Use push() to construct below list 53 | 1->2->1->3->1 */ 54 | push(&head, 1); 55 | push(&head, 3); 56 | push(&head, 1); 57 | push(&head, 2); 58 | push(&head, 1); 59 | 60 | /* Check the count function */ 61 | cout<<"count of nodes is "<< getCount(head); 62 | return 0; 63 | } 64 | 65 | -------------------------------------------------------------------------------- /max: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printCombination(int [], int, int); 5 | void combinationUtil(int [], int [], int, int, int,int); 6 | 7 | int ans; 8 | int main() 9 | { 10 | int T,N,K,A[1000],data[1000]; 11 | cin>>T; 12 | for(int i=0;i>N>>K; 16 | for(int j=0;j= r-index; i++) 55 | { 56 | data[index] = arr[i]; 57 | combinationUtil(arr, data, i+1, end, index+1, r); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /max-con-1-rotate-binary.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to calculate maximum contiguous 2 | // ones in string 3 | #include 4 | using namespace std; 5 | 6 | // function to calculate maximum contiguous ones 7 | int maxContiguousOnes(string s, int k) 8 | { 9 | 10 | int i, j, a, b, count; 11 | 12 | // multiset is used to store frequency of 13 | // 1's of each portion of contiguous 1 in 14 | // string in decreasing order 15 | multiset > m; 16 | 17 | // this loop calculate all the frequency 18 | // and stores them in multiset 19 | for (i = 0; i < s.length(); i++) { 20 | if (s[i] == '1') { 21 | count = 0; 22 | j = i; 23 | while (s[j] == '1' && j < s.length()) { 24 | count++; 25 | j++; 26 | } 27 | m.insert(count); 28 | i = j - 1; 29 | } 30 | } 31 | 32 | // if their is no 1 in string, then return 0 33 | if (m.size() == 0) 34 | return 0; 35 | 36 | // calculates maximum contiguous 1's on 37 | // doing rotations 38 | while (k > 0 && m.size() != 1) { 39 | 40 | // Delete largest two elements 41 | a = *(m.begin()); 42 | m.erase(m.begin()); 43 | b = *(m.begin()); 44 | m.erase(m.begin()); 45 | 46 | // insert their sum back into the multiset 47 | m.insert(a + b); 48 | k--; 49 | } 50 | 51 | // return maximum contiguous ones 52 | // possible after k rotations 53 | return *(m.begin()); 54 | } 55 | 56 | // Driver code 57 | int main() 58 | { 59 | string s = "10011110011"; 60 | int k = 1; 61 | cout << maxContiguousOnes(s, k); 62 | return 0; 63 | } 64 | 65 | -------------------------------------------------------------------------------- /max-hamming-distance.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ program to Find another array 3 | // such that the hamming distance 4 | // from the original array is maximum 5 | #include 6 | using namespace std; 7 | 8 | // Return the maximum hamming distance of a rotation 9 | int maxHamming(int arr[], int n) 10 | { 11 | // arr[] to brr[] two times so that 12 | // we can traverse through all rotations. 13 | int brr[2 *n + 1]; 14 | for (int i = 0; i < n; i++) 15 | brr[i] = arr[i]; 16 | for (int i = 0; i < n; i++) 17 | brr[n+i] = arr[i]; 18 | 19 | // We know hamming distance with 0 rotation 20 | // would be 0. 21 | int maxHam = 0; 22 | 23 | // We try other rotations one by one and compute 24 | // Hamming distance of every rotation 25 | for (int i = 1; i < n; i++) 26 | { 27 | int currHam = 0; 28 | for (int j = i, k=0; j < (i + n); j++,k++) 29 | if (brr[j] != arr[k]) 30 | currHam++; 31 | 32 | // We can never get more than n. 33 | if (currHam == n) 34 | return n; 35 | 36 | maxHam = max(maxHam, currHam); 37 | } 38 | 39 | return maxHam; 40 | } 41 | 42 | // driver program 43 | int main() 44 | { 45 | int arr[] = {2, 4, 6, 8}; 46 | int n = sizeof(arr)/sizeof(arr[0]); 47 | cout << maxHamming(arr, n); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /max-value-for-sum.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find max value of i*arr[i] 2 | #include 3 | using namespace std; 4 | 5 | // Returns max possible value of i*arr[i] 6 | int maxSum(int arr[], int n) 7 | { 8 | // Find array sum and i*arr[i] with no rotation 9 | int arrSum = 0; // Stores sum of arr[i] 10 | int currVal = 0; // Stores sum of i*arr[i] 11 | for (int i=0; i maxVal) 26 | maxVal = currVal; 27 | } 28 | 29 | // Return result 30 | return maxVal; 31 | } 32 | 33 | // Driver program 34 | int main(void) 35 | { 36 | int arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 37 | int n = sizeof(arr)/sizeof(arr[0]); 38 | cout << "\nMax sum is " << maxSum(arr, n); 39 | return 0; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /maximum-distance-two-occurrences-element-array.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find maximum distance between two 2 | // same occurrences of a number. 3 | #include 4 | using namespace std; 5 | 6 | // Function to find maximum distance between equal elements 7 | int maxDistance(int arr[], int n) 8 | { 9 | // Used to store element to first index mapping 10 | unordered_map mp; 11 | 12 | // Traverse elements and find maximum distance between 13 | // same occurrences with the help of map. 14 | int max_dist = 0; 15 | for (int i=0; i 3 | 4 | using namespace std; 5 | 6 | // Returns maximum value of i*arr[i] 7 | int maxSum(int arr[], int n) 8 | { 9 | // Initialize result 10 | int res = INT_MIN; 11 | 12 | // Consider rotation beginning with i 13 | // for all possible values of i. 14 | for (int i=0; i 4 | 5 | int findMin(int arr[], int low, int high) 6 | { 7 | // This condition is needed to handle the case when array is not 8 | // rotated at all 9 | if (high < low) return arr[0]; 10 | 11 | // If there is only one element left 12 | if (high == low) return arr[low]; 13 | 14 | // Find mid 15 | int mid = low + (high - low)/2; /*(low + high)/2;*/ 16 | 17 | // Check if element (mid+1) is minimum element. Consider 18 | // the cases like {3, 4, 5, 1, 2} 19 | if (mid < high && arr[mid+1] < arr[mid]) 20 | return arr[mid+1]; 21 | 22 | // Check if mid itself is minimum element 23 | if (mid > low && arr[mid] < arr[mid - 1]) 24 | return arr[mid]; 25 | 26 | // Decide whether we need to go to left half or right half 27 | if (arr[high] > arr[mid]) 28 | return findMin(arr, low, mid-1); 29 | return findMin(arr, mid+1, high); 30 | } 31 | 32 | // Driver program to test above functions 33 | int main() 34 | { 35 | int arr1[] = {5, 6, 1, 2, 3, 4}; 36 | int n1 = sizeof(arr1)/sizeof(arr1[0]); 37 | printf("The minimum element is %d\n", findMin(arr1, 0, n1-1)); 38 | 39 | int arr2[] = {1, 2, 3, 4}; 40 | int n2 = sizeof(arr2)/sizeof(arr2[0]); 41 | printf("The minimum element is %d\n", findMin(arr2, 0, n2-1)); 42 | 43 | int arr3[] = {1}; 44 | int n3 = sizeof(arr3)/sizeof(arr3[0]); 45 | printf("The minimum element is %d\n", findMin(arr3, 0, n3-1)); 46 | 47 | int arr4[] = {1, 2}; 48 | int n4 = sizeof(arr4)/sizeof(arr4[0]); 49 | printf("The minimum element is %d\n", findMin(arr4, 0, n4-1)); 50 | 51 | int arr5[] = {2, 1}; 52 | int n5 = sizeof(arr5)/sizeof(arr5[0]); 53 | printf("The minimum element is %d\n", findMin(arr5, 0, n5-1)); 54 | 55 | int arr6[] = {5, 6, 7, 1, 2, 3, 4}; 56 | int n6 = sizeof(arr6)/sizeof(arr6[0]); 57 | printf("The minimum element is %d\n", findMin(arr6, 0, n6-1)); 58 | 59 | int arr7[] = {1, 2, 3, 4, 5, 6, 7}; 60 | int n7 = sizeof(arr7)/sizeof(arr7[0]); 61 | printf("The minimum element is %d\n", findMin(arr7, 0, n7-1)); 62 | 63 | int arr8[] = {2, 3, 4, 5, 6, 7, 8, 1}; 64 | int n8 = sizeof(arr8)/sizeof(arr8[0]); 65 | printf("The minimum element is %d\n", findMin(arr8, 0, n8-1)); 66 | 67 | int arr9[] = {3, 4, 5, 1, 2}; 68 | int n9 = sizeof(arr9)/sizeof(arr9[0]); 69 | printf("The minimum element is %d\n", findMin(arr9, 0, n9-1)); 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /mirror-of-n-array-tree.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to mirror an n-ary tree 2 | #include 3 | using namespace std; 4 | 5 | // Represents a node of an n-ary tree 6 | struct Node 7 | { 8 | int key; 9 | vectorchild; 10 | }; 11 | 12 | // Function to convert a tree to its mirror 13 | void mirrorTree(Node * root) 14 | { 15 | // Base case: Nothing to do if root is NULL 16 | if (root==NULL) 17 | return; 18 | 19 | // Number of children of root 20 | int n = root->child.size(); 21 | 22 | // If number of child is less than 2 i.e. 23 | // 0 or 1 we do not need to do anything 24 | if (n < 2) 25 | return; 26 | 27 | // Calling mirror function for each child 28 | for (int i=0; ichild[i]); 30 | 31 | // Reverse vector (variable sized array) of child 32 | // pointers 33 | reverse(root->child.begin(), root->child.end()); 34 | } 35 | 36 | // Utility function to create a new tree node 37 | Node *newNode(int key) 38 | { 39 | Node *temp = new Node; 40 | temp->key = key; 41 | return temp; 42 | } 43 | 44 | // Prints the n-ary tree level wise 45 | void printNodeLevelWise(Node * root) 46 | { 47 | if (root==NULL) 48 | return; 49 | 50 | // Create a queue and enqueue root to it 51 | queueq; 52 | q.push(root); 53 | 54 | // Do level order traversal. Two loops are used 55 | // to make sure that different levels are printed 56 | // in different lines 57 | while (!q.empty()) 58 | { 59 | int n = q.size(); 60 | while (n>0) 61 | { 62 | // Dequeue an item from queue and print it 63 | Node * p = q.front(); 64 | q.pop(); 65 | cout << p->key << " "; 66 | 67 | // Enqueue all childrent of the dequeued item 68 | for (int i=0; ichild.size(); i++) 69 | q.push(p->child[i]); 70 | n--; 71 | } 72 | 73 | cout << endl; // Separator between levels 74 | } 75 | } 76 | 77 | // Driver program 78 | int main() 79 | { 80 | /* Let us create below tree 81 | * 10 82 | * / / \ \ 83 | * 2 34 56 100 84 | * | / | \ 85 | * 1 7 8 9 86 | */ 87 | Node *root = newNode(10); 88 | (root->child).push_back(newNode(2)); 89 | (root->child).push_back(newNode(34)); 90 | (root->child).push_back(newNode(56)); 91 | (root->child).push_back(newNode(100)); 92 | (root->child[2]->child).push_back(newNode(1)); 93 | (root->child[3]->child).push_back(newNode(7)); 94 | (root->child[3]->child).push_back(newNode(8)); 95 | (root->child[3]->child).push_back(newNode(9)); 96 | 97 | cout << "Level order traversal Before Mirroring\n"; 98 | printNodeLevelWise(root); 99 | 100 | mirrorTree(root); 101 | 102 | cout << "\nLevel order traversal After Mirroring\n"; 103 | printNodeLevelWise(root); 104 | 105 | return 0; 106 | } 107 | -------------------------------------------------------------------------------- /missing-elem-range.cpp: -------------------------------------------------------------------------------- 1 | // A hashing based C++ program to find missing 2 | // elements from an array 3 | #include 4 | using namespace std; 5 | 6 | // Print all elements of range [low, high] that 7 | // are not present in arr[0..n-1] 8 | void printMissing(int arr[], int n, int low, 9 | int high) 10 | { 11 | // Insert all elements of arr[] in set 12 | unordered_set s; 13 | for (int i=0; i 5 | using namespace std; 6 | 7 | // Fills temp[] with two copies of arr[] 8 | void preprocess(int arr[], int n, int temp[]) 9 | { 10 | // Store arr[] elements at i and i + n 11 | for (int i = 0; i 5 | using namespace std; 6 | 7 | int firstNonRepeating(int arr[], int n) 8 | { 9 | for (int i = 0; i < n; i++) { 10 | int j; 11 | for (j=0; j 6 | using namespace std; 7 | 8 | 9 | // Function to check if N is a 10 | // divisor of its right-rotation 11 | 12 | bool rightRotationDivisor(int N) 13 | { 14 | int lastDigit = N % 10; 15 | int rightRotation = (lastDigit * pow(10 ,int(log10(N)))) 16 | + floor(N / 10); 17 | return (rightRotation % N == 0); 18 | } 19 | 20 | // Function to generate m-digit 21 | // numbers which are divisor of 22 | // their right-rotation 23 | void generateNumbers(int m) 24 | { 25 | for (int i=pow(10,(m - 1));i 2 | using namespace std; 3 | #include 4 | 5 | int N[200],A[200],ans; 6 | void printCombination(int [], int, int); 7 | void combinationUtil(int [], int [], int, int, int, int); 8 | int main() 9 | { 10 | int T,B[200],arr[200]; 11 | cin>>T; 12 | for(int i=0;i>N[i]; 16 | for(int j=0;j>A[j]; 19 | arr[j]=j; 20 | } 21 | printCombination(arr,N[i]-1,N[i]-1); 22 | for(int k=0;k>B[k]; 25 | if(A[k]==B[k]) 26 | ans==1; 27 | else 28 | ans=0; 29 | } 30 | if(ans==1) 31 | cout<<"TAK"<<"\n"; 32 | else 33 | cout<<"NIE"<<"\n"; 34 | } 35 | return 0; 36 | } 37 | 38 | void printCombination(int arr[], int n, int r) 39 | { 40 | // A temporary array to store all combination one by one 41 | int data[r]; 42 | 43 | // all combination using temprary array 'data[]' 44 | combinationUtil(arr, data, 0, n-1, 0, r); 45 | } 46 | 47 | void combinationUtil(int arr[], int data[], int start, int end, 48 | int index, int r) 49 | { 50 | if (index == r) 51 | { 52 | for(int i=0;i= r-index; i++) 62 | { 63 | data[index] = arr[i]; 64 | combinationUtil(arr, data, i+1, end, index+1, r); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /pair with sum hashing.c: -------------------------------------------------------------------------------- 1 | 2 | // C++ program to check if given array 3 | // has 2 elements whose sum is equal 4 | // to the given value 5 | 6 | // Works only if range elements is limited 7 | #include 8 | #define MAX 100000 9 | 10 | void printPairs(int arr[], int arr_size, int sum) 11 | { 12 | int i, temp; 13 | bool s[MAX] = {0}; /*initialize hash set as 0*/ 14 | 15 | for (i = 0; i < arr_size; i++) 16 | { 17 | temp = sum - arr[i]; 18 | if (temp >= 0 && s[temp] == 1) 19 | printf("Pair with given sum %d is (%d, %d) n", 20 | sum, arr[i], temp); 21 | s[arr[i]] = 1; 22 | } 23 | } 24 | 25 | /* Driver program to test above function */ 26 | int main() 27 | { 28 | int A[] = {1, 4, 45, 6, 10, 8}; 29 | int n = 16; 30 | int arr_size = sizeof(A)/sizeof(A[0]); 31 | 32 | printPairs(A, arr_size, n); 33 | 34 | getchar(); 35 | return 0; 36 | } 37 | Copy Code 38 | -------------------------------------------------------------------------------- /pair-sum.c: -------------------------------------------------------------------------------- 1 | // C program to check if given array 2 | // has 2 elements whose sum is equal 3 | // to the given value 4 | 5 | # include 6 | # define bool int 7 | 8 | void quickSort(int *, int, int); 9 | 10 | bool hasArrayTwoCandidates(int A[], int arr_size, int sum) 11 | { 12 | int l, r; 13 | 14 | /* Sort the elements */ 15 | quickSort(A, 0, arr_size-1); 16 | 17 | /* Now look for the two candidates in the sorted 18 | array*/ 19 | l = 0; 20 | r = arr_size-1; 21 | while (l < r) 22 | { 23 | if(A[l] + A[r] == sum) 24 | return 1; 25 | else if(A[l] + A[r] < sum) 26 | l++; 27 | else // A[i] + A[j] > sum 28 | r--; 29 | } 30 | return 0; 31 | } 32 | 33 | /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING 34 | PURPOSE */ 35 | void exchange(int *a, int *b) 36 | { 37 | int temp; 38 | temp = *a; 39 | *a = *b; 40 | *b = temp; 41 | } 42 | 43 | int partition(int A[], int si, int ei) 44 | { 45 | int x = A[ei]; 46 | int i = (si - 1); 47 | int j; 48 | 49 | for (j = si; j <= ei - 1; j++) 50 | { 51 | if(A[j] <= x) 52 | { 53 | i++; 54 | exchange(&A[i], &A[j]); 55 | } 56 | } 57 | exchange (&A[i + 1], &A[ei]); 58 | return (i + 1); 59 | } 60 | 61 | /* Implementation of Quick Sort 62 | A[] --> Array to be sorted 63 | si --> Starting index 64 | ei --> Ending index 65 | */ 66 | void quickSort(int A[], int si, int ei) 67 | { 68 | int pi; /* Partitioning index */ 69 | if(si < ei) 70 | { 71 | pi = partition(A, si, ei); 72 | quickSort(A, si, pi - 1); 73 | quickSort(A, pi + 1, ei); 74 | } 75 | } 76 | 77 | /* Driver program to test above function */ 78 | int main() 79 | { 80 | int A[] = {1, 4, 45, 6, 10, -8}; 81 | int n = 16; 82 | int arr_size = 6; 83 | 84 | if( hasArrayTwoCandidates(A, arr_size, n)) 85 | printf("Array has two elements with given sum"); 86 | else 87 | printf("Array doesn't have two elements with given sum"); 88 | 89 | getchar(); 90 | return 0; 91 | } 92 | -------------------------------------------------------------------------------- /pair-sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ implementation of simple method to find count of 3 | // pairs with given sum. 4 | #include 5 | using namespace std; 6 | 7 | // Returns number of pairs in arr[0..n-1] with sum equal 8 | // to 'sum' 9 | int getPairsCount(int arr[], int n, int sum) 10 | { 11 | int count = 0; // Initialize result 12 | 13 | // Consider all possible pairs and check their sums 14 | for (int i=0; i 5 | using namespace std; 6 | 7 | // Function to find greatest number that us 8 | int findGreatest( int arr[] , int n) 9 | { 10 | int result = -1; 11 | for (int i = 0; i < n ; i++) 12 | for (int j = 0; j < n-1; j++) 13 | for (int k = j+1 ; k < n ; k++) 14 | if (arr[j] * arr[k] == arr[i]) 15 | result = max(result, arr[i]); 16 | return result; 17 | } 18 | 19 | // Driver code 20 | int main() 21 | { 22 | // Your C++ Code 23 | int arr[] = {30, 10, 9, 3, 35}; 24 | int n = sizeof(arr)/sizeof(arr[0]); 25 | 26 | cout << findGreatest(arr, n); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | char a[100], b[100]; 7 | 8 | printf("Enter a string to check if it is a palindrome\n"); 9 | gets(a); 10 | 11 | strcpy(b, a); // Copying input string 12 | strrev(b); // Reversing the string 13 | 14 | if (strcmp(a, b) == 0) // Comparing input string with the reverse string 15 | printf("The string is a palindrome.\n"); 16 | else 17 | printf("The string isn't a palindrome.\n"); 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /palindromes.cpp: -------------------------------------------------------------------------------- 1 | 2 | // A C++ program to generate palindromic numbers 3 | // less than n. 4 | #include 5 | using namespace std; 6 | 7 | // A utility for creating palindrome 8 | int createPalindrome(int input, int b, bool isOdd) 9 | { 10 | int n = input; 11 | int palin = input; 12 | 13 | // checks if number of digits is odd or even 14 | // if odd then neglect the last digit of input in 15 | // finding reverse as in case of odd number of 16 | // digits middle element occur once 17 | if (isOdd) 18 | n /= b; 19 | 20 | // Creates palindrome by just appending reverse 21 | // of number to itself 22 | while (n > 0) 23 | { 24 | palin = palin * b + (n % b); 25 | n /= b; 26 | } 27 | return palin; 28 | } 29 | 30 | // Function to print decimal palindromic number 31 | void generatePalindromes(int n) 32 | { 33 | int number; 34 | 35 | // Run two times for odd and even length palindromes 36 | for (int j = 0; j < 2; j++) 37 | { 38 | // Creates palindrome numbers with first half as i. 39 | // Value of j decided whether we need an odd length 40 | // of even length palindrome. 41 | int i = 1; 42 | while ((number = createPalindrome(i, 10, j % 2)) < n) 43 | { 44 | cout << number << " "; 45 | i++; 46 | } 47 | } 48 | } 49 | 50 | // Driver Program to test above function 51 | int main() 52 | { 53 | int n = 104; 54 | generatePalindromes(n); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /power-recursion.c: -------------------------------------------------------------------------------- 1 | /*C program to calculate power of any number using recursion*/ 2 | 3 | #include 4 | 5 | //function for calculating power 6 | long int getPower(int b,int p) 7 | { 8 | long int result=1; 9 | if(p==0) return result; 10 | result=b*(getPower(b,p-1)); //call function again 11 | } 12 | int main() 13 | { 14 | int base,power; 15 | long int result; 16 | 17 | printf("Enter value of base: "); 18 | scanf("%d",&base); 19 | 20 | printf("Enter value of power: "); 21 | scanf("%d",&power); 22 | 23 | result=getPower(base,power); 24 | 25 | printf("%d to the power of %d is: %ld\n",base,power,result); 26 | 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /queries-on-array.cpp: -------------------------------------------------------------------------------- 1 | // CPP Program to solve queries on Left and Right 2 | // Circular shift on array 3 | #include 4 | using namespace std; 5 | 6 | // Function to solve query of type 1 x. 7 | void querytype1(int* toRotate, int times, int n) 8 | { 9 | // Decreasing the absolute rotation 10 | (*toRotate) = ((*toRotate) - times) % n; 11 | } 12 | 13 | // Function to solve query of type 2 y. 14 | void querytype2(int* toRotate, int times, int n) 15 | { 16 | // Increasing the absolute rotation. 17 | (*toRotate) = ((*toRotate) + times) % n; 18 | } 19 | 20 | // Function to solve queries of type 3 l r. 21 | void querytype3(int toRotate, int l, int r, 22 | int preSum[], int n) 23 | { 24 | // Finding absolute l and r. 25 | l = (l + toRotate + n) % n; 26 | r = (r + toRotate + n) % n; 27 | 28 | // if l is before r. 29 | if (l <= r) 30 | cout << (preSum[r + 1] - preSum[l]) << endl; 31 | 32 | // If r is before l. 33 | else 34 | cout << (preSum[n] + preSum[r + 1] - preSum[l]) 35 | << endl; 36 | } 37 | 38 | // Wrapper Function solve all queries. 39 | void wrapper(int a[], int n) 40 | { 41 | int preSum[n + 1]; 42 | preSum[0] = 0; 43 | 44 | // Finding Prefix sum 45 | for (int i = 1; i <= n; i++) 46 | preSum[i] = preSum[i - 1] + a[i - 1]; 47 | 48 | int toRotate = 0; 49 | 50 | // Solving each query 51 | querytype1(&toRotate, 3, n); 52 | querytype3(toRotate, 0, 2, preSum, n); 53 | querytype2(&toRotate, 1, n); 54 | querytype3(toRotate, 1, 4, preSum, n); 55 | } 56 | 57 | // Driver Program 58 | int main() 59 | { 60 | int a[] = { 1, 2, 3, 4, 5 }; 61 | int n = sizeof(a) / sizeof(a[0]); 62 | wrapper(a, n); 63 | return 0; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /queue: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int T,N,M,K,L,a[1000],time=0,ans[1000],p=0,k; 7 | cin>>T; 8 | for(int i=0;i>N>>M>>K>>L; 11 | } 12 | for(int i=0;i>a[i]; 15 | } 16 | for(int j=0;j 5 | 6 | /*Function to reverse arr[] 7 | from index start to end*/ 8 | void reverseArray(int arr[], int start, 9 | int end) 10 | { 11 | while (start < end) 12 | { 13 | std::swap(arr[start], arr[end]); 14 | start++; 15 | end--; 16 | } 17 | } 18 | 19 | /* Function to right rotate arr[] 20 | of size n by d */ 21 | void rightRotate(int arr[], int d, int n) 22 | { 23 | reverseArray(arr, 0, n-1); 24 | reverseArray(arr, 0, d-1); 25 | reverseArray(arr, d, n-1); 26 | } 27 | 28 | /* function to print an array */ 29 | void printArray(int arr[], int size) 30 | { 31 | for (int i = 0; i < size; i++) 32 | std::cout << arr[i] << " "; 33 | } 34 | 35 | // driver code 36 | int main() 37 | { 38 | int arr[] = {1, 2, 3, 4, 5, 39 | 6, 7, 8, 9, 10}; 40 | 41 | int n = sizeof(arr)/sizeof(arr[0]); 42 | int k = 3; 43 | 44 | rightRotate(arr, k, n); 45 | printArray(arr, n); 46 | 47 | return 0; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /rotated-array-pair-sum.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ program to find a pair with a given sum in a sorted and 3 | // rotated array 4 | #include 5 | using namespace std; 6 | 7 | // This function returns true if arr[0..n-1] has a pair 8 | // with sum equals to x. 9 | bool pairInSortedRotated(int arr[], int n, int x) 10 | { 11 | // Find the pivot element 12 | int i; 13 | for (i=0; i arr[i+1]) 15 | break; 16 | int l = (i+1)%n; // l is now index of minimum element 17 | int r = i; // r is now index of maximum element 18 | 19 | // Keep moving either l or r till they meet 20 | while (l != r) 21 | { 22 | // If we find a pair with sum x, we return true 23 | if (arr[l] + arr[r] == x) 24 | return true; 25 | 26 | // If current pair sum is less, move to the higher sum 27 | if (arr[l] + arr[r] < x) 28 | l = (l + 1)%n; 29 | else // Move to the lower sum side 30 | r = (n + r - 1)%n; 31 | } 32 | return false; 33 | } 34 | 35 | /* Driver program to test above function */ 36 | int main() 37 | { 38 | int arr[] = {11, 15, 6, 8, 9, 10}; 39 | int sum = 16; 40 | int n = sizeof(arr)/sizeof(arr[0]); 41 | 42 | if (pairInSortedRotated(arr, n, sum)) 43 | cout << "Array has two elements with sum 16"; 44 | else 45 | cout << "Array doesn't have two elements with sum 16 "; 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /rotation-count-Linear-search.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | // C++ program to find number of rotations 4 | // in a sorted and rotated array. 5 | #include 6 | using namespace std; 7 | 8 | // Returns count of rotations for an array which 9 | // is first sorted in ascending order, then rotated 10 | int countRotations(int arr[], int n) 11 | { 12 | // We basically find index of minimum 13 | // element 14 | int min = arr[0], min_index; 15 | for (int i=0; i arr[i]) 18 | { 19 | min = arr[i]; 20 | min_index = i; 21 | } 22 | } 23 | return min_index; 24 | } 25 | 26 | // Driver code 27 | int main() 28 | { 29 | int arr[] = {15, 18, 2, 3, 6, 12}; 30 | int n = sizeof(arr)/sizeof(arr[0]); 31 | cout << countRotations(arr, n); 32 | return 0; 33 | } 34 | 35 | -------------------------------------------------------------------------------- /search-element-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* C++ Program to search an element 3 | in a sorted and pivoted array*/ 4 | #include 5 | using namespace std; 6 | 7 | /* Standard Binary Search function*/ 8 | int binarySearch(int arr[], int low, 9 | int high, int key) 10 | { 11 | if (high < low) 12 | return -1; 13 | 14 | int mid = (low + high)/2; /*low + (high - low)/2;*/ 15 | if (key == arr[mid]) 16 | return mid; 17 | 18 | if (key > arr[mid]) 19 | return binarySearch(arr, (mid + 1), high, key); 20 | 21 | // else 22 | return binarySearch(arr, low, (mid -1), key); 23 | } 24 | 25 | /* Function to get pivot. For array 3, 4, 5, 6, 1, 2 26 | it returns 3 (index of 6) */ 27 | int findPivot(int arr[], int low, int high) 28 | { 29 | // base cases 30 | if (high < low) return -1; 31 | if (high == low) return low; 32 | 33 | int mid = (low + high)/2; /*low + (high - low)/2;*/ 34 | if (mid < high && arr[mid] > arr[mid + 1]) 35 | return mid; 36 | 37 | if (mid > low && arr[mid] < arr[mid - 1]) 38 | return (mid-1); 39 | 40 | if (arr[low] >= arr[mid]) 41 | return findPivot(arr, low, mid-1); 42 | 43 | return findPivot(arr, mid + 1, high); 44 | } 45 | 46 | /* Searches an element key in a pivoted 47 | sorted array arr[] of size n */ 48 | int pivotedBinarySearch(int arr[], int n, int key) 49 | { 50 | int pivot = findPivot(arr, 0, n-1); 51 | 52 | // If we didn't find a pivot, 53 | // then array is not rotated at all 54 | if (pivot == -1) 55 | return binarySearch(arr, 0, n-1, key); 56 | 57 | // If we found a pivot, then first compare with pivot 58 | // and then search in two subarrays around pivot 59 | if (arr[pivot] == key) 60 | return pivot; 61 | 62 | if (arr[0] <= key) 63 | return binarySearch(arr, 0, pivot-1, key); 64 | 65 | return binarySearch(arr, pivot+1, n-1, key); 66 | } 67 | 68 | /* Driver program to check above functions */ 69 | int main() 70 | { 71 | // Let us search 3 in below array 72 | int arr1[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}; 73 | int n = sizeof(arr1)/sizeof(arr1[0]); 74 | int key = 3; 75 | 76 | // Function calling 77 | cout << "Index of the element is : " << 78 | pivotedBinarySearch(arr1, n, key); 79 | 80 | return 0; 81 | } 82 | 83 | -------------------------------------------------------------------------------- /simpsons_method.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | float f(float x) 5 | { 6 | return 1.0 + 7 | x * x * x; // This is the expresion of the function to integrate? 8 | } 9 | 10 | int main() 11 | { 12 | int i, n; 13 | float a, b, h, x, s2, s3, sum, integral; 14 | 15 | printf("enter the lower limit of the integration:"); 16 | scanf("%f", &a); 17 | printf("enter the upper limit of the integration:"); 18 | scanf("%f", &b); 19 | printf("enter the number of intervals:"); 20 | scanf("%d", &n); 21 | 22 | h = (b - a) / n; 23 | sum = f(a) + f(b); 24 | s2 = s3 = 0.0; 25 | 26 | for (i = 1; i < n; i += 3) 27 | { 28 | x = a + i * h; 29 | s3 = s3 + f(x) + f(x + h); 30 | } 31 | 32 | for (i = 3; i < n; i += 3) 33 | { 34 | x = a + i * h; 35 | s2 = s2 + f(x); 36 | } 37 | 38 | integral = (h / 3.0) * (sum + 2 * s2 + 4 * s3); 39 | printf("\nValue of the integral = %9.4f\n", integral); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /snack: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include 4 | 5 | int main() 6 | { 7 | int T,N[10],flag,test[10]; 8 | int snack[]={2010,2015,2016,2017,2019}; 9 | cin>>T; 10 | if(T>=1 && T<=10){ 11 | for(int i=0;i>N[i]; 14 | flag=0; 15 | if(N[i]>=2010 && N[i]<=2019){ 16 | for(int j=0;j<5;j++) 17 | { 18 | if(N[i]==snack[j]) 19 | flag=1; 20 | } 21 | test[i]=flag; 22 | } 23 | else 24 | exit(0); 25 | } 26 | } 27 | else 28 | exit(0); 29 | for(int i=0;i 5 | using namespace std; 6 | 7 | // Map m2 keeps track of indexes of elements in array 8 | unordered_map m2; 9 | 10 | // Used for sorting by frequency. And if frequency is same, 11 | // then by appearance 12 | bool sortByVal(const pair& a, const pair& b) 13 | { 14 | // If frequency is same then sort by index 15 | if (a.second == b.second) 16 | return m2[a.first] < m2[b.first]; 17 | 18 | return a.second > b.second; 19 | } 20 | 21 | // function to sort elements by frequency 22 | void sortByFreq(int a[], int n) 23 | { 24 | unordered_map m; 25 | vector > v; 26 | 27 | for (int i = 0; i < n; ++i) { 28 | 29 | // Map m is used to keep track of count 30 | // of elements in array 31 | m[a[i]]++; 32 | 33 | // Update the value of map m2 only once 34 | if (m2[a[i]] == 0) 35 | m2[a[i]] = i + 1; 36 | } 37 | 38 | // Copy map to vector 39 | copy(m.begin(), m.end(), back_inserter(v)); 40 | 41 | // Sort the element of array by frequency 42 | sort(v.begin(), v.end(), sortByVal); 43 | 44 | for (int i = 0; i < v.size(); ++i) 45 | for (int j = 0; j < v[i].second; ++j) 46 | cout << v[i].first << " "; 47 | } 48 | 49 | // Driver program 50 | int main() 51 | { 52 | int a[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; 53 | int n = sizeof(a) / sizeof(a[0]); 54 | 55 | sortByFreq(a, n); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /split-and-add.cpp: -------------------------------------------------------------------------------- 1 | 2 | // CPP program to split array and move first 3 | // part to end. 4 | #include 5 | using namespace std; 6 | 7 | void splitArr(int arr[], int n, int k) 8 | { 9 | for (int i = 0; i < k; i++) { 10 | 11 | // Rotate array by 1. 12 | int x = arr[0]; 13 | for (int j = 0; j < n - 1; ++j) 14 | arr[j] = arr[j + 1]; 15 | arr[n - 1] = x; 16 | } 17 | } 18 | 19 | // Driver code 20 | int main() 21 | { 22 | int arr[] = { 12, 10, 5, 6, 52, 36 }; 23 | int n = sizeof(arr) / sizeof(arr[0]); 24 | int position = 2; 25 | 26 | splitArr(arr, 6, position); 27 | 28 | for (int i = 0; i < n; ++i) 29 | printf("%d ", arr[i]); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /sum-digits.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //function to calculate sum of all digits 4 | int sumDigits(int num) 5 | { 6 | static int sum=0; 7 | if(num>0) 8 | { 9 | sum+=(num%10); //add digit into sum 10 | sumDigits(num/10); 11 | } 12 | else 13 | { 14 | return sum; 15 | } 16 | } 17 | int main() 18 | { 19 | int number,sum; 20 | 21 | printf("Enter a positive integer number: "); 22 | scanf("%d",&number); 23 | 24 | sum=sumDigits(number); 25 | 26 | printf("Sum of all digits are: %d\n",sum); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /symmetric-pair-in-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A C++ program to find all symmetric pairs in a given array of pairs 5 | // Print all pairs that have a symmetric counterpart 6 | void findSymPairs(int arr[][2], int row) 7 | { 8 | // Creates an empty hashMap hM 9 | unordered_map hM; 10 | 11 | // Traverse through the given array 12 | for (int i = 0; i < row; i++) 13 | { 14 | // First and second elements of current pair 15 | int first = arr[i][0]; 16 | int sec = arr[i][1]; 17 | 18 | // If found and value in hash matches with first 19 | // element of this pair, we found symmetry 20 | if (hM.find(sec) != hM.end() && hM[sec] == first) 21 | cout << "(" << sec << ", " << first << ")" < 4 | using namespace std; 5 | 6 | /* Function to print top three repeated numbers */ 7 | void top3Repeated(int arr[], int n) 8 | { 9 | // There should be atleast two elements 10 | if (n < 3) { 11 | cout << "Invalid Input"; 12 | return; 13 | } 14 | 15 | // Count Frequency of each element 16 | unordered_map fre; 17 | for (int i = 0; i < n; i++) 18 | fre[arr[i]]++; 19 | 20 | // Initialize first value of each variable 21 | // of Pair type is INT_MIN 22 | pair x, y, z; 23 | x.first = y.first = z.first = INT_MIN; 24 | 25 | for (auto curr : fre) { 26 | 27 | // If frequency of current element 28 | // is not zero and greater than 29 | // frequency of first largest element 30 | if (curr.second > x.first) { 31 | 32 | // Update second and third largest 33 | z = y; 34 | y = x; 35 | 36 | // Modify values of x Number 37 | x.first = curr.second; 38 | x.second = curr.first; 39 | } 40 | 41 | // If frequency of current element is 42 | // not zero and frequency of current 43 | // element is less than frequency of 44 | // first largest element, but greater 45 | // than y element 46 | else if (curr.second > y.first) { 47 | 48 | // Modify values of third largest 49 | z = y; 50 | 51 | // Modify values of second largest 52 | y.first = curr.second; 53 | y.second = curr.first; 54 | } 55 | 56 | // If frequency of current element 57 | // is not zero and frequency of 58 | // current element is less than 59 | // frequency of first element and 60 | // second largest, but greater than 61 | // third largest. 62 | else if (curr.second > z.first) { 63 | 64 | // Modify values of z Number 65 | z.first = curr.second; 66 | z.second = curr.first; 67 | } 68 | } 69 | 70 | cout << "Three largest elements are " 71 | << x.second << " " << y.second 72 | << " " << z.second; 73 | } 74 | 75 | // Driver's Code 76 | int main() 77 | { 78 | int arr[] = { 3, 4, 2, 3, 16, 3, 15, 79 | 16, 15, 15, 16, 2, 3 }; 80 | int n = sizeof(arr) / sizeof(arr[0]); 81 | top3Repeated(arr, n); 82 | return 0; 83 | } 84 | -------------------------------------------------------------------------------- /trie-delete.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) 7 | 8 | // Alphabet size (# of symbols) 9 | 10 | #define ALPHABET_SIZE (26) 11 | #define INDEX(c) ((int)c - (int)'a') 12 | 13 | #define FREE(p) \ 14 | free(p); \ 15 | p = NULL; 16 | 17 | // forward declration 18 | typedef struct trie_node trie_node_t; 19 | 20 | // trie node 21 | struct trie_node 22 | { 23 | int value; // non zero if leaf 24 | trie_node_t *children[ALPHABET_SIZE]; 25 | }; 26 | 27 | // trie ADT 28 | typedef struct trie trie_t; 29 | 30 | struct trie 31 | { 32 | trie_node_t *root; 33 | int count; 34 | }; 35 | 36 | trie_node_t *getNode(void) 37 | { 38 | trie_node_t *pNode = NULL; 39 | 40 | pNode = (trie_node_t *)malloc(sizeof(trie_node_t)); 41 | 42 | if( pNode ) 43 | { 44 | int i; 45 | 46 | pNode->value = 0; 47 | 48 | for(i = 0; i < ALPHABET_SIZE; i++) 49 | { 50 | pNode->children[i] = NULL; 51 | } 52 | } 53 | 54 | return pNode; 55 | } 56 | 57 | void initialize(trie_t *pTrie) 58 | { 59 | pTrie->root = getNode(); 60 | pTrie->count = 0; 61 | } 62 | 63 | void insert(trie_t *pTrie, char key[]) 64 | { 65 | int level; 66 | int length = strlen(key); 67 | int index; 68 | trie_node_t *pCrawl; 69 | 70 | pTrie->count++; 71 | pCrawl = pTrie->root; 72 | 73 | for( level = 0; level < length; level++ ) 74 | { 75 | index = INDEX(key[level]); 76 | 77 | if( pCrawl->children[index] ) 78 | { 79 | // Skip current node 80 | pCrawl = pCrawl->children[index]; 81 | } 82 | else 83 | { 84 | // Add new node 85 | pCrawl->children[index] = getNode(); 86 | pCrawl = pCrawl->children[index]; 87 | } 88 | } 89 | 90 | // mark last node as leaf (non zero) 91 | pCrawl->value = pTrie->count; 92 | } 93 | 94 | int search(trie_t *pTrie, char key[]) 95 | { 96 | int level; 97 | int length = strlen(key); 98 | int index; 99 | trie_node_t *pCrawl; 100 | 101 | pCrawl = pTrie->root; 102 | 103 | for( level = 0; level < length; level++ ) 104 | { 105 | index = INDEX(key[level]); 106 | 107 | if( !pCrawl->children[index] ) 108 | { 109 | return 0; 110 | } 111 | 112 | pCrawl = pCrawl->children[index]; 113 | } 114 | 115 | return (0 != pCrawl && pCrawl->value); 116 | } 117 | 118 | int leafNode(trie_node_t *pNode) 119 | { 120 | return (pNode->value != 0); 121 | } 122 | 123 | int isItFreeNode(trie_node_t *pNode) 124 | { 125 | int i; 126 | for(i = 0; i < ALPHABET_SIZE; i++) 127 | { 128 | if( pNode->children[i] ) 129 | return 0; 130 | } 131 | 132 | return 1; 133 | } 134 | 135 | bool deleteHelper(trie_node_t *pNode, char key[], int level, int len) 136 | { 137 | if( pNode ) 138 | { 139 | // Base case 140 | if( level == len ) 141 | { 142 | if( pNode->value ) 143 | { 144 | // Unmark leaf node 145 | pNode->value = 0; 146 | 147 | // If empty, node to be deleted 148 | if( isItFreeNode(pNode) ) 149 | { 150 | return true; 151 | } 152 | 153 | return false; 154 | } 155 | } 156 | else // Recursive case 157 | { 158 | int index = INDEX(key[level]); 159 | 160 | if( deleteHelper(pNode->children[index], key, level+1, len) ) 161 | { 162 | // last node marked, delete it 163 | FREE(pNode->children[index]); 164 | 165 | // recursively climb up, and delete eligible nodes 166 | return ( !leafNode(pNode) && isItFreeNode(pNode) ); 167 | } 168 | } 169 | } 170 | 171 | return false; 172 | } 173 | 174 | void deleteKey(trie_t *pTrie, char key[]) 175 | { 176 | int len = strlen(key); 177 | 178 | if( len > 0 ) 179 | { 180 | deleteHelper(pTrie->root, key, 0, len); 181 | } 182 | } 183 | 184 | int main() 185 | { 186 | char keys[][8] = {"she", "sells", "sea", "shore", "the", "by", "sheer"}; 187 | trie_t trie; 188 | 189 | initialize(&trie); 190 | 191 | for(int i = 0; i < ARRAY_SIZE(keys); i++) 192 | { 193 | insert(&trie, keys[i]); 194 | } 195 | 196 | deleteKey(&trie, keys[0]); 197 | 198 | printf("%s %s\n", "she", search(&trie, "she") ? "Present in trie" : "Not present in trie"); 199 | 200 | return 0; 201 | } 202 | -------------------------------------------------------------------------------- /trie-search: -------------------------------------------------------------------------------- 1 | // C implementation of search and insert operations 2 | // on Trie 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0]) 9 | 10 | // Alphabet size (# of symbols) 11 | #define ALPHABET_SIZE (26) 12 | 13 | // Converts key current character into index 14 | // use only 'a' through 'z' and lower case 15 | #define CHAR_TO_INDEX(c) ((int)c - (int)'a') 16 | 17 | // trie node 18 | struct TrieNode 19 | { 20 | struct TrieNode *children[ALPHABET_SIZE]; 21 | 22 | // isEndOfWord is true if the node represents 23 | // end of a word 24 | bool isEndOfWord; 25 | }; 26 | 27 | // Returns new trie node (initialized to NULLs) 28 | struct TrieNode *getNode(void) 29 | { 30 | struct TrieNode *pNode = NULL; 31 | 32 | pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode)); 33 | 34 | if (pNode) 35 | { 36 | int i; 37 | 38 | pNode->isEndOfWord = false; 39 | 40 | for (i = 0; i < ALPHABET_SIZE; i++) 41 | pNode->children[i] = NULL; 42 | } 43 | 44 | return pNode; 45 | } 46 | 47 | // If not present, inserts key into trie 48 | // If the key is prefix of trie node, just marks leaf node 49 | void insert(struct TrieNode *root, const char *key) 50 | { 51 | int level; 52 | int length = strlen(key); 53 | int index; 54 | 55 | struct TrieNode *pCrawl = root; 56 | 57 | for (level = 0; level < length; level++) 58 | { 59 | index = CHAR_TO_INDEX(key[level]); 60 | if (!pCrawl->children[index]) 61 | pCrawl->children[index] = getNode(); 62 | 63 | pCrawl = pCrawl->children[index]; 64 | } 65 | 66 | // mark last node as leaf 67 | pCrawl->isEndOfWord = true; 68 | } 69 | 70 | // Returns true if key presents in trie, else false 71 | bool search(struct TrieNode *root, const char *key) 72 | { 73 | int level; 74 | int length = strlen(key); 75 | int index; 76 | struct TrieNode *pCrawl = root; 77 | 78 | for (level = 0; level < length; level++) 79 | { 80 | index = CHAR_TO_INDEX(key[level]); 81 | 82 | if (!pCrawl->children[index]) 83 | return false; 84 | 85 | pCrawl = pCrawl->children[index]; 86 | } 87 | 88 | return (pCrawl != NULL && pCrawl->isEndOfWord); 89 | } 90 | 91 | // Driver 92 | int main() 93 | { 94 | // Input keys (use only 'a' through 'z' and lower case) 95 | char keys[][8] = {"the", "a", "there", "answer", "any", 96 | "by", "bye", "their"}; 97 | 98 | char output[][32] = {"Not present in trie", "Present in trie"}; 99 | 100 | 101 | struct TrieNode *root = getNode(); 102 | 103 | // Construct trie 104 | int i; 105 | for (i = 0; i < ARRAY_SIZE(keys); i++) 106 | insert(root, keys[i]); 107 | 108 | // Search for different keys 109 | printf("%s --- %s\n", "the", output[search(root, "the")] ); 110 | printf("%s --- %s\n", "these", output[search(root, "these")] ); 111 | printf("%s --- %s\n", "their", output[search(root, "their")] ); 112 | printf("%s --- %s\n", "thaw", output[search(root, "thaw")] ); 113 | 114 | return 0; 115 | } 116 | --------------------------------------------------------------------------------