├── .gitignore ├── .gitattributes ├── Introduction ├── a.out └── Analysis.c ├── LinkedList ├── a.out ├── Poly.c ├── DCLL.c ├── CLL.c └── DLL.c ├── Algo ├── CA │ └── IsPrime.c ├── Greedy │ ├── OptimalMergePattern.c │ ├── Knapsack.c │ ├── FractionalKnapsack.c │ ├── HuffmanTree.c │ ├── ActivitySelection.c │ ├── MultipleStageGraph.c │ ├── ChotaBhim.c │ ├── JoinRopes.c │ ├── JobSequencing.c │ └── HuffmanTree.h ├── DP │ ├── MinStairCost.c │ ├── LargestIncreasingSubseq.c │ ├── DiceThrow.c │ ├── StairUniqueWays.c │ ├── LargestPalindromicSubsequence.c │ ├── Vacation.c │ ├── HouseRobber.c │ ├── LargestPalindromicSubstr.c │ ├── Fibo.c │ ├── LargestBitonicSubseq.c │ ├── GridMinCost.c │ ├── GridUniqueWays.c │ ├── LongestCommonSubseq.c │ ├── FloydWarshall.c │ ├── WildCharMatch.c │ ├── EditDist.c │ ├── StockBuySell.c │ ├── MinCostBinaryTree.c │ ├── ALS.c │ ├── OptimalBST.c │ ├── JobScheduling.c │ ├── MatrixCM.c │ ├── Knapsack.c │ └── CoinChange.c ├── BT │ ├── NQueen.c │ ├── TOH.c │ ├── SubsetSum.c │ ├── TSP.c │ ├── Permutations.c │ └── GraphColouring.c └── DAC │ ├── NutsAndBolts.c │ └── ClosestPair.c ├── .vscode ├── c_cpp_properties.json ├── settings.json └── launch.json ├── .project ├── Tree ├── Tree2.c ├── BinaryIndexTree.c ├── Tree.h ├── SegmentTree.c ├── rangeMaxST.c ├── rmqST.c ├── AVLTree.c └── SPLAYTree.c ├── Queue ├── QueueUsingStack.c ├── Stack.c ├── Queue.c └── QueueLL.c ├── README.md ├── Stack ├── TwoStack.c ├── StackLL.c └── Stack.c ├── Heap ├── BinomialHeap.py ├── SkipList.py ├── Strassens.py ├── fibonacci.py └── Heap.c ├── .settings └── language.settings.xml ├── Searching └── BitManipulation.c ├── HashTable ├── HashSC.c ├── Set.c ├── HashLP.c ├── HashTableExercise.c └── Counter.c ├── String ├── Trie.c ├── TST.c ├── StringTree.c └── StrStr.c └── Graph ├── GraphAM.h └── Graph.h /.gitignore: -------------------------------------------------------------------------------- 1 | *err 2 | *.exe 3 | *.exe 4 | */err 5 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /Introduction/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hemant-Jain-Author/Problem-Solving-in-Data-Structures-and-Algorithms-using-C/HEAD/Introduction/a.out -------------------------------------------------------------------------------- /LinkedList/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Hemant-Jain-Author/Problem-Solving-in-Data-Structures-and-Algorithms-using-C/HEAD/LinkedList/a.out -------------------------------------------------------------------------------- /Algo/CA/IsPrime.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | int isPrime(int n) { 6 | int answer = (n > 1) ? 1 : 0; 7 | for (int i = 2; i * i <= n; ++i) { 8 | if (n % i == 0) { 9 | answer = 0; 10 | break; 11 | } 12 | } 13 | return answer; 14 | } 15 | 16 | int main() { 17 | printf("7 is prime: %d", isPrime(7)); 18 | return 0; 19 | } 20 | 21 | /* 22 | 7 is prime: 1 23 | */ -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Linux", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "defines": [], 9 | "cStandard": "c11", 10 | "cppStandard": "c++14", 11 | "intelliSenseMode": "linux-clang-x64" 12 | } 13 | ], 14 | "version": 4 15 | } -------------------------------------------------------------------------------- /Algo/Greedy/OptimalMergePattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../../Heap/Heap.c" 4 | 5 | int merge(int lists[], int size) { 6 | Heap* hp = createHeap(greater); 7 | 8 | for (int i = 0; i < size; i++) { 9 | heapAdd(hp, lists[i]); 10 | } 11 | 12 | int total = 0; 13 | int value = 0; 14 | while (heapSize(hp) > 1) { 15 | value = heapRemove(hp); 16 | value += heapRemove(hp); 17 | heapAdd(hp, value); 18 | total += value; 19 | } 20 | printf("Total : %d\n" , total ); 21 | return total; 22 | } 23 | 24 | int main() { 25 | int lists[] = {4, 3, 2, 6}; 26 | merge(lists, 4); 27 | } 28 | 29 | /* 30 | Total : 29 31 | */ -------------------------------------------------------------------------------- /Algo/DP/MinStairCost.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int min(int a, int b) { 5 | return (a < b)? a : b; 6 | } 7 | 8 | int minStairCost(int cost[], int n) { 9 | // base case 10 | if (n == 1) 11 | return cost[0]; 12 | 13 | int dp[n]; 14 | dp[0] = cost[0]; 15 | dp[1] = cost[1]; 16 | 17 | for (int i = 2; i < n; i++) 18 | dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]; 19 | 20 | return min(dp[n - 2], dp[n - 1]); 21 | } 22 | 23 | int main() { 24 | int a[] = {1, 5, 6, 3, 4, 7, 9, 1, 2, 11}; 25 | int n = sizeof(a)/sizeof(int); 26 | printf("minStairCost : %d\n", minStairCost(a, n)); 27 | return 0; 28 | } 29 | 30 | /* 31 | minStairCost : 18 32 | */ -------------------------------------------------------------------------------- /Algo/DP/LargestIncreasingSubseq.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | int lis(int arr[], int n) { 6 | int lis[n]; 7 | int max = 0; 8 | 9 | // Populating LIS values in bottom up manner. 10 | for (int i = 0; i < n; i++) { 11 | lis[i] = 1; // Initialize LIS values for all indexes as 1. 12 | for (int j = 0; j < i; j++) { 13 | if (arr[j] < arr[i] && lis[i] < lis[j] + 1) 14 | lis[i] = lis[j] + 1; 15 | } 16 | 17 | if (max < lis[i]) // Max LIS values. 18 | max = lis[i]; 19 | } 20 | return max; 21 | } 22 | 23 | int main() { 24 | int arr[] = {10, 12, 9, 23, 25, 55, 49, 70}; 25 | printf("Length of lis is %d." , lis(arr, 8) ); 26 | return 0; 27 | } 28 | 29 | /* 30 | Length of lis is 6 31 | */ 32 | 33 | -------------------------------------------------------------------------------- /Algo/DP/DiceThrow.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int findWaysBU(int n, int m, int V) { 5 | int dp[n + 1][V + 1]; 6 | for (int i = 0; i <= n; i++) 7 | for (int j = 0; j <= V; j++) 8 | dp[i][j] = 0; 9 | 10 | // Table entries for only one dice. 11 | for (int j = 1; j <= m && j <= V; j++) 12 | dp[1][j] = 1; 13 | 14 | for (int i = 2; i <= n; i++) { // i is number of dice 15 | for (int j = 1; j <= V; j++) { // j is target value 16 | for (int k = 1; k <= j && k <= m; k++) { // k value of m face dice. 17 | dp[i][j] += dp[i - 1][j - k]; 18 | } 19 | } 20 | } 21 | return dp[n][V]; 22 | } 23 | 24 | int main() { 25 | for (int i = 1;i <= 6;i++) { 26 | printf("%d\n", findWaysBU(i, 6, 6) ); 27 | } 28 | } 29 | 30 | /* 31 | 1 32 | 5 33 | 10 34 | 10 35 | 5 36 | 1 37 | */ -------------------------------------------------------------------------------- /Algo/BT/NQueen.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void print(int Q[], int n) { 5 | for (int i = 0; i < n; i++) 6 | printf("%d ", Q[i]); 7 | 8 | printf("\n"); 9 | } 10 | 11 | int feasible(int Q[], int k) { 12 | for (int i = 0; i < k; i++) { 13 | if (Q[k] == Q[i] || abs(Q[i] - Q[k]) == abs(i - k)) 14 | return 0; 15 | } 16 | return 1; 17 | } 18 | 19 | void nQueens(int Q[], int k, int n) { 20 | if (k == n) { 21 | print(Q, n); 22 | return; 23 | } 24 | for (int i = 0; i < n; i++) { 25 | Q[k] = i; 26 | if (feasible(Q, k)) { 27 | nQueens(Q, k + 1, n); 28 | } 29 | } 30 | } 31 | 32 | int main() { 33 | int Q[8]; 34 | nQueens(Q, 0, 8); 35 | return 0; 36 | } 37 | 38 | /* 39 | 0 4 7 5 2 6 1 3 40 | 0 5 7 2 6 3 1 4 41 | .... 42 | 7 2 0 5 1 4 6 3 43 | 7 3 0 2 5 1 6 4 44 | */ -------------------------------------------------------------------------------- /Algo/DP/StairUniqueWays.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int stairUniqueWaysBU(int n) { 5 | if (n <= 2) 6 | return n; 7 | 8 | int first = 1, second = 2, temp = 0; 9 | 10 | for (int i = 3; i <= n; i++) { 11 | temp = first + second; 12 | first = second; 13 | second = temp; 14 | } 15 | return temp; 16 | } 17 | 18 | int stairUniqueWaysBU2(int n) { 19 | if (n < 2) 20 | return n; 21 | 22 | int ways[n]; 23 | ways[0] = 1; 24 | ways[1] = 2; 25 | 26 | for (int i = 2; i < n; i++) 27 | ways[i] = ways[i - 1] + ways[i - 2]; 28 | 29 | return ways[n - 1]; 30 | } 31 | 32 | int main() { 33 | printf("Unique way to reach top:: %d\n" , stairUniqueWaysBU(4)); 34 | printf("Unique way to reach top:: %d\n" , stairUniqueWaysBU2(4)); 35 | } 36 | 37 | /* 38 | Unique way to reach top:: 5 39 | Unique way to reach top:: 5 40 | */ -------------------------------------------------------------------------------- /Algo/BT/TOH.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void tohUtil(int num, char from, char to, char temp) { 5 | if (num < 1) 6 | return; 7 | 8 | tohUtil(num - 1, from, temp, to); 9 | printf("Move disk %d from peg %c to peg %c.\n", num, from, to ); 10 | tohUtil(num - 1, temp, to, from); 11 | } 12 | 13 | void toh(int num) { 14 | printf("The sequence of moves involved in the Tower of Hanoi are :\n" ); 15 | tohUtil(num, 'A', 'C', 'B'); 16 | } 17 | 18 | int main() { 19 | toh(3); 20 | return 0; 21 | } 22 | 23 | /* 24 | The sequence of moves involved in the Tower of Hanoi are : 25 | Move disk 1 from peg A to peg C 26 | Move disk 2 from peg A to peg B 27 | Move disk 1 from peg C to peg B 28 | Move disk 3 from peg A to peg C 29 | Move disk 1 from peg B to peg A 30 | Move disk 2 from peg B to peg C 31 | Move disk 1 from peg A to peg C 32 | */ -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | 2Chapter1 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.cdt.managedbuilder.core.genmakebuilder 10 | clean,full,incremental, 11 | 12 | 13 | 14 | 15 | org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder 16 | full,incremental, 17 | 18 | 19 | 20 | 21 | 22 | org.eclipse.cdt.core.cnature 23 | org.eclipse.cdt.managedbuilder.core.managedBuildNature 24 | org.eclipse.cdt.managedbuilder.core.ScannerConfigNature 25 | 26 | 27 | -------------------------------------------------------------------------------- /Algo/DP/LargestPalindromicSubsequence.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | int max(int a, int b) { 6 | return (a > b)? a : b; 7 | } 8 | 9 | int palindromicSubsequence(char* str) { 10 | int n = strlen(str); 11 | int dp[n][n]; 12 | memset(dp, 0, sizeof(dp)); 13 | 14 | for (int i = 0; i < n; i++) // each char is itself palindromic with length 1 15 | dp[i][i] = 1; 16 | 17 | for (int l = 1; l < n; l++) { 18 | for (int i = 0, j = l; j < n; i++, j++) { 19 | if (str[i] == str[j]) 20 | dp[i][j] = dp[i + 1][j - 1] + 2; 21 | else 22 | dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); 23 | } 24 | } 25 | return dp[0][n - 1]; 26 | } 27 | 28 | int main() { 29 | char *str = "ABCAUCBCxxCBA"; 30 | printf("Max Palindromic Subsequence length: %d", palindromicSubsequence(str)); 31 | return 0; 32 | } 33 | 34 | /* 35 | Max Palindromic Subsequence length: 9 36 | */ -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "deque": "c", 4 | "initializer_list": "c", 5 | "list": "c", 6 | "queue": "c", 7 | "stack": "c", 8 | "type_traits": "c", 9 | "vector": "c", 10 | "xstring": "c", 11 | "xutility": "c", 12 | "xlocale": "c", 13 | "system_error": "c", 14 | "xfunctional": "c", 15 | "xstddef": "c", 16 | "xtr1common": "c", 17 | "cmath": "c", 18 | "ostream": "cpp" 19 | }, 20 | "cSpell.words": [ 21 | "APLE", 22 | "Bhim", 23 | "bitonic", 24 | "chota", 25 | "DCLL", 26 | "expn", 27 | "heapify", 28 | "htree", 29 | "kruskal", 30 | "swapch" 31 | ], 32 | "C_Cpp.errorSquiggles": "Disabled", 33 | "cSpell.ignoreWords": [ 34 | "bbaaaabb" 35 | ] 36 | } -------------------------------------------------------------------------------- /Algo/DP/Vacation.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | int min(int a, int b) { 6 | return (a < b)? a : b; 7 | } 8 | 9 | int max(int a, int b) { 10 | return (a > b)? a : b; 11 | } 12 | 13 | int minCost(int days[], int n, int costs[]) { 14 | int maxVal = days[n - 1]; 15 | int dp[maxVal + 1]; 16 | memset(dp, 0, sizeof(dp)); 17 | 18 | int j = 0; 19 | for (int i = 1; i <= maxVal; i++) { 20 | if (days[j] == i) { // That days is definitely travelled. 21 | j++; 22 | dp[i] = dp[i - 1] + costs[0]; 23 | dp[i] = min(dp[i], dp[max(0, i - 7)] + costs[1]); 24 | dp[i] = min(dp[i], dp[max(0, i - 30)] + costs[2]); 25 | } else { 26 | dp[i] = dp[i - 1]; // day may be ignored. 27 | } 28 | } 29 | return dp[maxVal]; 30 | } 31 | 32 | int main() { 33 | int days[] = {1, 3, 5, 7, 12, 20, 30}; 34 | int n = 7; 35 | int costs[] = {2, 7, 20}; 36 | printf("Min cost is: %d", minCost(days, n, costs)); 37 | return 0; 38 | } 39 | 40 | /* 41 | Min cost is:13 42 | */ -------------------------------------------------------------------------------- /Tree/Tree2.c: -------------------------------------------------------------------------------- 1 | #include "../Stack/Stack.c" 2 | 3 | int isBSTArray(int preorder[], int size) { 4 | Stack* stk = createStack(); 5 | int value; 6 | int root = -999999; 7 | for (int i = 0; i < size; i++) { 8 | value = preorder[i]; 9 | 10 | // If value of the right child is less than roo 11 | if (value < root) 12 | return 0; 13 | // First left child `alues will be popped 14 | // Last popped value will be the roo 15 | while (stackIsEmpty(stk) == 0 && stackTop(stk) < value) { 16 | root = stackPop(stk); 17 | } 18 | // add current value to the stack. 19 | stackPush(stk, value); 20 | } 21 | return 1; 22 | } 23 | 24 | int main() { 25 | int arr1[] = {5, 2, 4, 6, 9, 10}; 26 | printf("%d\n", isBSTArray(arr1, 6)); 27 | 28 | int arr2[] = {5, 2, 6, 4, 7, 9, 10}; 29 | printf("%d\n", isBSTArray(arr2, 6)); 30 | return 0; 31 | } 32 | 33 | /* 34 | 1 35 | 0 36 | */ 37 | -------------------------------------------------------------------------------- /Algo/DP/HouseRobber.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int max(int a, int b) { 5 | return (a > b)? a : b; 6 | } 7 | 8 | int maxRobbery(int house[], int n) { 9 | int dp[n]; 10 | dp[0] = house[0]; 11 | dp[1] = house[1]; 12 | dp[2] = house[0] + house[2]; 13 | for (int i = 3; i < n; i++) { 14 | dp[i] = max(dp[i - 2], dp[i - 3]) + house[i]; 15 | } 16 | return max(dp[n - 1], dp[n - 2]); 17 | } 18 | 19 | int maxRobbery2(int house[], int n) { 20 | int dp[n][2]; 21 | dp[0][1] = house[0]; 22 | dp[0][0] = 0; 23 | 24 | for (int i = 1; i < n; ++i) { 25 | dp[i][1] = max(dp[i - 1][0] + house[i], dp[i - 1][1]); 26 | dp[i][0] = dp[i - 1][1]; 27 | } 28 | return max(dp[n - 1][1], dp[n - 1][0]); 29 | } 30 | 31 | int main() { 32 | int arr[] = {10, 12, 9, 23, 25, 55, 49, 70}; 33 | printf("Total cash: %d \n" , maxRobbery(arr, 8)); 34 | printf("Total cash: %d \n" , maxRobbery2(arr, 8)); 35 | return 0; 36 | } 37 | 38 | /* 39 | Total cash: 160 40 | Total cash: 160 41 | */ -------------------------------------------------------------------------------- /Algo/DP/LargestPalindromicSubstr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int palindromicSubstring(char* str) { 6 | int n = strlen(str); 7 | int dp[n][n]; 8 | memset(dp, 0, sizeof(dp)); 9 | 10 | for (int i = 0;i < n;i++) 11 | dp[i][i] = 1; 12 | 13 | int max = 1; 14 | int start = 0; 15 | 16 | for (int l = 1; l < n; l++) { 17 | for (int i = 0, j = i + l; j < n; i++, j++) { 18 | if (str[i] == str[j] && dp[i + 1][j - 1] == j - i - 1) { 19 | dp[i][j] = dp[i + 1][j - 1] + 2; 20 | if (dp[i][j] > max) { 21 | max = dp[i][j]; // Keeping track of max length and 22 | start = i; // starting position of sub-string. 23 | } 24 | } else { 25 | dp[i][j] = 0; 26 | } 27 | } 28 | } 29 | return max; 30 | } 31 | 32 | int main() { 33 | char* str = "ABCAUCBCxxCBA"; 34 | int length = palindromicSubstring(str); 35 | printf("Max Palindromic Substrings len: %d." , length ); 36 | return 0; 37 | } 38 | 39 | /* 40 | Max Palindromic Substrings len: 6 41 | */ -------------------------------------------------------------------------------- /Algo/BT/SubsetSum.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void printSubset(int flags[], int arr[], int size) { 5 | for (int i = 0; i < size; i++) { 6 | if (flags[i]) { 7 | printf("%d ",arr[i]); 8 | } 9 | } 10 | printf("\n"); 11 | } 12 | 13 | void subsetSumUtil(int arr[], int n, int flags[], int sum, int curr, int target) { 14 | if (target == sum) { // Solution found. 15 | printSubset(flags, arr, n); 16 | return; 17 | } 18 | 19 | // Constraint check and Backtracking. 20 | if (curr >= n || sum > target) { 21 | return; 22 | } 23 | 24 | flags[curr] = 1; // Current element included. 25 | subsetSumUtil(arr, n, flags, sum + arr[curr], curr + 1, target); 26 | 27 | flags[curr] = 0; // Current element excluded. 28 | subsetSumUtil(arr, n, flags, sum, curr + 1, target); 29 | } 30 | 31 | void subsetSum(int arr[], int n, int target) { 32 | int flags[n]; 33 | subsetSumUtil(arr, n, flags, 0, 0, target); 34 | } 35 | 36 | int main() { 37 | int arr[] = {15, 22, 14, 26, 32, 9, 16, 8}; 38 | int target = 53; 39 | int n = sizeof(arr)/sizeof(int); 40 | subsetSum(arr, n, target); 41 | return 0; 42 | } 43 | 44 | /* 45 | 15 22 16 46 | 15 14 16 8 47 | 22 14 9 8 48 | */ -------------------------------------------------------------------------------- /Algo/DP/Fibo.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int fibonacci(int n) { 5 | if (n < 2) 6 | return n; 7 | return fibonacci(n - 1) + fibonacci(n - 2); 8 | } 9 | 10 | void fibonacciSeries(int n) { 11 | for (int i = 0;i < n;i++) 12 | printf("%d ", fibonacci(i)); 13 | } 14 | 15 | int fibonacciBU(int n) { 16 | if (n < 2) 17 | return n; 18 | 19 | int dp[n+1]; 20 | dp[0] = 0; 21 | dp[1] = 1; 22 | 23 | for (int i = 2; i <= n; i++) { 24 | dp[i] = dp[i-1] + dp[i-2]; 25 | } 26 | 27 | return dp[n]; 28 | } 29 | 30 | int fibonacciTDUtil(int n, int dp[]) { 31 | if (n < 2) { 32 | dp[n] = n; 33 | return n; 34 | } 35 | 36 | if (dp[n] == 0) 37 | dp[n] = fibonacciTDUtil(n-1, dp) + fibonacciTDUtil(n-2, dp); 38 | 39 | return dp[n]; 40 | } 41 | 42 | int fibonacciTD(int n) { 43 | int dp[n+1]; 44 | for (int i = 0; i <= n; i++) 45 | dp[i] = 0; 46 | return fibonacciTDUtil(n, dp); 47 | } 48 | 49 | int main() { 50 | printf("%d \n", fibonacci(10)); 51 | printf("%d \n", fibonacciBU(10)); 52 | printf("%d \n", fibonacciTD(10)); 53 | return 0; 54 | } 55 | 56 | /* 57 | 55 58 | 55 59 | 55 60 | */ -------------------------------------------------------------------------------- /Algo/DP/LargestBitonicSubseq.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int max(int a, int b) { 6 | return (a > b)? a : b; 7 | } 8 | 9 | int lbs(int arr[], int n) { 10 | int lis[n]; // Initialize LIS values for all indexes as 1. 11 | int lds[n]; // Initialize LDS values for all indexes as 1. 12 | 13 | for (int i = 0; i < n; i++) { 14 | lis[i] = 1; 15 | lds[i] = 1; 16 | } 17 | 18 | int maxVal = 0; 19 | 20 | // Populating LIS values in bottom up manner. 21 | for (int i = 0; i < n; i++) { 22 | for (int j = 0; j < i; j++) { 23 | if (arr[j] < arr[i] && lis[i] < lis[j] + 1) 24 | lis[i] = lis[j] + 1; 25 | } 26 | } 27 | 28 | // Populating LDS values in bottom up manner. 29 | for (int i = n - 1; i > 0; i--) { 30 | for (int j = n - 1; j > i; j--) { 31 | if (arr[j] < arr[i] && lds[i] < lds[j] + 1) 32 | lds[i] = lds[j] + 1; 33 | } 34 | } 35 | 36 | for (int i = 0; i < n; i++) 37 | maxVal = max(maxVal, lis[i] + lds[i] - 1); 38 | return maxVal; 39 | } 40 | 41 | int main() { 42 | int arr[] = {1, 6, 3, 11, 1, 9, 5, 12, 3, 14, 6, 17, 3, 19, 2, 19}; 43 | int n = 16; 44 | printf("Length of lbs is %d." , lbs(arr, n) ); 45 | } 46 | 47 | /* 48 | Length of lbs is 8 49 | */ -------------------------------------------------------------------------------- /Queue/QueueUsingStack.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include 4 | #include "string.h" 5 | #include 6 | #include "../Stack/Stack.c" 7 | 8 | int min(int a, int b) { 9 | return a > b ? b : a; 10 | } 11 | 12 | int max(int a, int b) { 13 | return a < b ? b : a; 14 | } 15 | 16 | typedef struct Queue { 17 | Stack* stk1; 18 | Stack* stk2; 19 | }Queue; 20 | 21 | Queue* createQueue() { 22 | Queue* que = (Queue*)malloc(sizeof(Queue)); 23 | que->stk1 = createStack(); 24 | que->stk2 = createStack(); 25 | return que; 26 | } 27 | 28 | void queueAdd(Queue* que, int value) { 29 | stackPush(que->stk1, value); 30 | } 31 | 32 | int queueRemove(Queue* que) { 33 | int value; 34 | if (stackIsEmpty(que->stk2)) { 35 | while (!stackIsEmpty(que->stk1)) { 36 | value = stackPop(que->stk1); 37 | stackPush(que->stk2, value); 38 | } 39 | } 40 | return stackPop(que->stk2); 41 | } 42 | 43 | int queueSize(Queue* que) { 44 | return stackSize(que->stk1) + stackSize(que->stk2); 45 | } 46 | 47 | int main() { 48 | Queue* que = createQueue(); 49 | queueAdd(que, 1); 50 | queueAdd(que, 2); 51 | queueAdd(que, 3); 52 | queueAdd(que, 4); 53 | while(queueSize(que) > 0) 54 | printf("%d ", queueRemove(que)); 55 | } -------------------------------------------------------------------------------- /Algo/DP/GridMinCost.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int min(int x, int y, int z) { 5 | x = (x < y)? x : y; 6 | x = (x < z)? x : z; 7 | return x; 8 | } 9 | 10 | int minGridCost(int N, int cost[][N], int m, int n ) { 11 | if (m == 0 || n == 0) 12 | return 99999; 13 | 14 | if (m == 1 && n == 1) 15 | return cost[0][0]; 16 | 17 | return cost[m-1][n-1] + min(minGridCost(N, cost,m-1, n-1), 18 | minGridCost(N, cost,m-1, n), 19 | minGridCost(N, cost,m, n-1)); 20 | } 21 | 22 | int minGridCostBU(int m, int n, int cost[m][n]) { 23 | int tc[m][n]; 24 | tc[0][0] = cost[0][0]; 25 | 26 | // Initialize first column. 27 | for (int i = 1; i < m; i++) 28 | tc[i][0] = tc[i-1][0] + cost[i][0]; 29 | 30 | // Initialize first row. 31 | for (int j = 1; j < n; j++) 32 | tc[0][j] = tc[0][j-1] + cost[0][j]; 33 | 34 | for (int i = 1; i < m; i++) { 35 | for (int j = 1; j < n; j++) { 36 | tc[i][j] = cost[i][j] + min(tc[i-1][j-1], 37 | tc[i-1][j], tc[i][j-1]); 38 | } 39 | } 40 | return tc[m-1][n-1]; 41 | } 42 | 43 | int main() { 44 | int cost[3][3] = {{1, 3, 4}, {4, 7, 5}, {1, 5, 3}}; 45 | printf("%d\n", minGridCost(3,cost, 3, 3)); 46 | printf("%d\n", minGridCostBU(3, 3, cost)); 47 | } 48 | 49 | /* 50 | 11 51 | 11 52 | */ -------------------------------------------------------------------------------- /Algo/DP/GridUniqueWays.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int gridUniqueWays(int m, int n) { 6 | int dp[m][n]; 7 | memset(dp, 0, m*n*sizeof(int)); 8 | dp[0][0] = 1; 9 | 10 | // Initialize first column - Streight path. 11 | for (int i = 1; i < m; i++) 12 | dp[i][0] = 1; 13 | 14 | // Initialize first row - Streight path. 15 | for (int j = 1; j < n; j++) 16 | dp[0][j] = 1; 17 | 18 | for (int i = 1; i < m; i++) 19 | for (int j = 1; j < n; j++) 20 | dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 21 | 22 | return dp[m - 1][n - 1]; 23 | } 24 | 25 | int gridUnique3Ways(int m, int n) { 26 | int dp[m][n]; 27 | memset(dp, 0, m*n*sizeof(int)); 28 | dp[0][0] = 1; 29 | 30 | // Initialize first column - Streight path. 31 | for (int i = 1; i < m; i++) 32 | dp[i][0] = 1; 33 | 34 | // Initialize first row - Streight path. 35 | for (int j = 1; j < n; j++) 36 | dp[0][j] = 1; 37 | 38 | for (int i = 1; i < m; i++) 39 | for (int j = 1; j < n; j++) 40 | dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] + dp[i][j - 1]; 41 | 42 | return dp[m - 1][n - 1]; 43 | } 44 | 45 | int main() { 46 | printf("%d \n", gridUniqueWays(3, 3)); 47 | printf("%d \n", gridUnique3Ways(3, 3)); 48 | return 0; 49 | } 50 | /* 51 | 6 52 | 13 53 | */ -------------------------------------------------------------------------------- /Algo/DP/LongestCommonSubseq.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void PrintLCS(int n, int p[][n], char X[], int i, int j) { 6 | if (i == 0 || j == 0) 7 | return; 8 | 9 | if (p[i][j] == 0) { 10 | PrintLCS(n, p, X, i - 1, j - 1); 11 | printf("%c", X[i - 1]); 12 | } else if (p[i][j] == 1) { 13 | PrintLCS(n, p, X, i - 1, j); 14 | } else { 15 | PrintLCS(n, p, X, i, j - 1); 16 | } 17 | } 18 | 19 | int LCSubStr(char* X, char* Y) { 20 | int m = strlen(X); 21 | int n = strlen(Y); 22 | int dp[m + 1][n + 1]; // Dynamic programming array. 23 | int p[m + 1][n + 1]; // For printing the subchar*. 24 | memset(dp, 0, sizeof(dp)); 25 | memset(dp, 0, sizeof(p)); 26 | 27 | // Fill dp array in bottom up fashion. 28 | for (int i = 1; i <= m; i++) { 29 | for (int j = 1; j <= n; j++) { 30 | if (X[i - 1] == Y[j - 1]) { 31 | dp[i][j] = dp[i - 1][j - 1] + 1; 32 | p[i][j] = 0; 33 | } else { 34 | dp[i][j] = (dp[i - 1][j] > dp[i][j - 1])? dp[i - 1][j]: dp[i][j - 1]; 35 | p[i][j] = (dp[i - 1][j] > dp[i][j - 1])? 1 : 2; 36 | } 37 | } 38 | } 39 | PrintLCS(n+1, p, X, m, n); 40 | printf("\n"); 41 | return dp[m][n]; 42 | } 43 | 44 | int main() { 45 | char* X = "carpenter"; 46 | char* Y = "sharpener"; 47 | printf("%d", LCSubStr(X, Y) ); 48 | return 0; 49 | } 50 | 51 | /* 52 | arpener 53 | 7 54 | */ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Problem-Solving-in-Data-Structures-and-Algorithms-using-C 2 | 3 | **This is the code repository of book "Problem Solving in Data Structures & Algorithms Using C".** 4 | 5 | ![alt text](https://m.media-amazon.com/images/P/B0BKTN5FY6.jpg) 6 | 7 | 8 | **About The Book** 9 | - This textbook provides in depth coverage of various Data Structures and Algorithms. 10 | - Concepts are discussed in easy to understand manner. 11 | - Large number of diagrams are provided to grasp concepts easily. 12 | - Time and Space complexities of various algorithms are discussed. 13 | - Helpful for interviews preparation and competitive coding. 14 | - Large number of interview questions are solved. 15 | - C solutions are provided with input and output. 16 | - Guide you through how to solve new problems in programming interview of various software companies. 17 | 18 | 19 | **Table of Contents** 20 | - Chapter 0: How to use this book. 21 | - Chapter 1: Algorithms Analysis 22 | - Chapter 2: Approach to solve algorithm design problems 23 | - Chapter 3: Abstract Data Type 24 | - Chapter 4: Searching 25 | - Chapter 5: Sorting 26 | - Chapter 6: Linked List 27 | - Chapter 7: Stack 28 | - Chapter 8: Queue 29 | - Chapter 9: Tree 30 | - Chapter 10: Priority Queue 31 | - Chapter 11: Hash-Table 32 | - Chapter 12: Graphs 33 | - Chapter 13: String Algorithms 34 | - Chapter 14: Algorithm Design Techniques 35 | - Chapter 15: Brute Force Algorithm 36 | - Chapter 16: Greedy Algorithm 37 | - Chapter 17: Divide & Conquer 38 | - Chapter 18: Dynamic Programming 39 | - Chapter 19: Backtracking 40 | - Chapter 20: Complexity Theory 41 | 42 | 43 | -------------------------------------------------------------------------------- /Algo/Greedy/Knapsack.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | typedef struct Item { 6 | int wt; 7 | int cost; 8 | double density; 9 | } Item; 10 | 11 | Item* createItem(int w, int v) { 12 | Item* item = (Item*)malloc(sizeof(Item)); 13 | item->wt = w; 14 | item->cost = v; 15 | item->density = (double)v / w; 16 | return item; 17 | } 18 | 19 | int less(Item *a, Item *b) { 20 | return a->density < b->density; 21 | } 22 | 23 | void sort(Item * arr[], int size, int (*comp)(Item * p1, Item * p2)) { 24 | for (int i = 0; i < (size - 1); i++) { 25 | for (int j = 0; j < size - i - 1; j++) { 26 | if (comp(arr[j], arr[j + 1])) { 27 | /* Swapping */ 28 | Item* temp = arr[j]; 29 | arr[j] = arr[j + 1]; 30 | arr[j + 1] = temp; 31 | } 32 | } 33 | } 34 | } 35 | 36 | int getMaxCostGreedy(int wt[], int cost[], int n, int capacity) { 37 | int totalCost = 0; 38 | Item* itemList[n]; 39 | for (int i = 0; i < n; i++) 40 | itemList[i] = createItem(wt[i], cost[i]); 41 | 42 | sort(itemList, n, less); 43 | 44 | for (int i = 0; i < n && capacity > 0; i++) { 45 | if (capacity - itemList[i]->wt >= 0) { 46 | capacity -= itemList[i]->wt; 47 | totalCost += itemList[i]->cost; 48 | } 49 | } 50 | return totalCost; 51 | } 52 | 53 | int main() { 54 | int wt[] = {10, 40, 20, 30}; 55 | int cost[] = {60, 40, 90, 120}; 56 | int n = 4; 57 | int capacity = 50; 58 | int maxCost = getMaxCostGreedy(wt, cost, n, capacity); 59 | printf("Maximum cost obtained = %d\n", maxCost ); 60 | } 61 | 62 | /* 63 | Maximum cost obtained = 150 64 | */ -------------------------------------------------------------------------------- /Queue/Stack.c: -------------------------------------------------------------------------------- 1 | #include "Queue.c" 2 | 3 | typedef struct Stack { 4 | Queue* que1; 5 | Queue* que2; 6 | int size; 7 | }Stack; 8 | 9 | Stack* createStack() { 10 | Stack* stk = (Stack*)malloc(sizeof(Stack)); 11 | stk->que1 = createQueue(); 12 | stk->que2 = createQueue(); 13 | return stk; 14 | } 15 | 16 | void StackPush(Stack* stk, int value) { 17 | QueueAdd(stk->que1, value); 18 | stk->size += 1; 19 | } 20 | 21 | int StackPop(Stack* stk) { 22 | int value=0, s = stk->size; 23 | while(s > 0){ 24 | value = QueueRemove(stk->que1); 25 | if(s > 1) 26 | QueueAdd(stk->que2, value); 27 | s--; 28 | } 29 | Queue* temp = stk->que1; 30 | stk->que1 = stk->que2; 31 | stk->que2 = temp; 32 | stk->size -= 1; 33 | return value; 34 | } 35 | 36 | void StackPush2(Stack* stk, int value) { 37 | QueueAdd(stk->que1, value); 38 | stk->size += 1; 39 | } 40 | 41 | int StackPop2(Stack* stk) { 42 | int value=0, s = stk->size; 43 | while(s > 0){ 44 | value = QueueRemove(stk->que1); 45 | if(s > 1) 46 | QueueAdd(stk->que1, value); 47 | s--; 48 | } 49 | stk->size -= 1; 50 | return value; 51 | } 52 | 53 | int main() { 54 | Stack* stk = createStack(); 55 | StackPush(stk, 1); 56 | StackPush(stk, 2); 57 | StackPush(stk, 3); 58 | printf("%d ", StackPop(stk)); 59 | printf("%d ", StackPop(stk)); 60 | printf("%d ", StackPop(stk)); 61 | 62 | StackPush2(stk, 1); 63 | StackPush2(stk, 2); 64 | StackPush2(stk, 3); 65 | printf("%d ", StackPop2(stk)); 66 | printf("%d ", StackPop2(stk)); 67 | printf("%d ", StackPop2(stk)); 68 | } -------------------------------------------------------------------------------- /Algo/DAC/NutsAndBolts.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void printArray(int arr[], int n) { 5 | printf("[ "); 6 | for (int i = 0; i < n; i++) { 7 | printf("%d ", arr[i] ); 8 | } 9 | printf("] "); 10 | } 11 | 12 | void swap(int arr[], int first, int second) { 13 | int temp = arr[first]; 14 | arr[first] = arr[second]; 15 | arr[second] = temp; 16 | } 17 | 18 | int partition(int arr[], int low, int high, int pivot) { 19 | int i = low; 20 | for (int j = low; j < high; j++) { 21 | if (arr[j] < pivot) { 22 | swap(arr, i, j); 23 | i++; 24 | } else if (arr[j] == pivot) { 25 | swap(arr, high, j); 26 | j--; 27 | } 28 | } 29 | swap(arr, i, high); 30 | return i; 31 | } 32 | 33 | void makePairsUtil(int nuts[], int bolts[], int low, int high) { 34 | if (low < high) { 35 | // Choose first element of bolts array as pivot to partition nuts. 36 | int pivot = partition(nuts, low, high, bolts[low]); 37 | // Using nuts[pivot] as pivot to partition bolts. 38 | partition(bolts, low, high, nuts[pivot]); 39 | // Recursively lower and upper half of nuts and bolts are matched. 40 | makePairsUtil(nuts, bolts, low, pivot - 1); 41 | makePairsUtil(nuts, bolts, pivot + 1, high); 42 | } 43 | } 44 | 45 | void makePairs(int nuts[], int bolts[], int size) { 46 | makePairsUtil(nuts, bolts, 0, size-1); 47 | printf("Matched nuts and bolts are : "); 48 | printArray(nuts, size); 49 | printArray(bolts, size); 50 | } 51 | 52 | int main() { 53 | int nuts[] = {1, 2, 6, 5, 4, 3}; 54 | int bolts[] = {6, 4, 5, 1, 3, 2}; 55 | makePairs(nuts, bolts, 6); 56 | return 0; 57 | } 58 | 59 | /* 60 | Matched nuts and bolts are : [ 1 2 3 4 5 6 ] [ 1 2 3 4 5 6 ] 61 | */ -------------------------------------------------------------------------------- /Algo/DP/FloydWarshall.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const int INFINITE = 99999; 5 | 6 | void printSolution(int V, int dist[V][V]) { 7 | for (int i = 0; i < V; i++) { 8 | for (int j = 0; j < V; j++) { 9 | if (dist[i][j] == INFINITE) 10 | printf("INFINITE "); 11 | else 12 | printf("%d ", dist[i][j]); 13 | } 14 | printf("\n"); 15 | } 16 | } 17 | 18 | void floydWarshall(int V, int graph[V][V]) { // Bottom up. 19 | int dist[V][V]; 20 | for (int i = 0; i < V; i++) 21 | for (int j = 0; j < V; j++) 22 | dist[i][j] = graph[i][j]; // Direct path. 23 | 24 | for (int k = 0; k < V; k++) { // Pick intermediate vertices. 25 | for (int i = 0; i < V; i++) { // Pick source vertices one by one. 26 | for (int j = 0; j < V; j++) { // Pick destination vertices. 27 | // If we have shorter path from i to j via k, then update dist[i][j] 28 | if (dist[i][k] != INFINITE && dist[k][j] != INFINITE && dist[i][k] + dist[k][j] < dist[i][j]) 29 | dist[i][j] = dist[i][k] + dist[k][j]; 30 | } 31 | } 32 | } 33 | // Print the shortest distance matrix 34 | printSolution(V, dist); 35 | } 36 | 37 | int main() { 38 | int graph[7][7] = 39 | { 40 | {0, 2, 4, INFINITE, INFINITE, INFINITE, INFINITE}, 41 | {2, 0, 4, 1, INFINITE, INFINITE, INFINITE}, 42 | {4, 4, 0, 2, 8, 4, INFINITE}, 43 | {INFINITE, 1, 2, 0, 3, INFINITE, 6}, 44 | {INFINITE, INFINITE, 6, 4, 0, 3, 1}, 45 | {INFINITE, INFINITE, 4, INFINITE, 4, 0, 2}, 46 | {INFINITE, INFINITE, INFINITE, 4, 2, 3, 0} 47 | }; 48 | floydWarshall(7, graph); 49 | } 50 | 51 | /* 52 | 0 2 4 3 6 8 7 53 | 2 0 3 1 4 7 5 54 | 4 3 0 2 5 4 6 55 | 3 1 2 0 3 6 4 56 | 7 5 6 4 0 3 1 57 | 8 7 4 6 4 0 2 58 | 7 5 6 4 2 3 0 59 | */ -------------------------------------------------------------------------------- /Stack/TwoStack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX_SIZE 50 5 | #define ERROR_VALUE 999999 6 | 7 | typedef struct stack { 8 | int top1; 9 | int top2; 10 | int data[MAX_SIZE]; 11 | } Stack; 12 | 13 | Stack* createStack() { 14 | Stack *stk = (Stack*)malloc(sizeof(Stack)); 15 | stk->top1 = -1; 16 | stk->top2 = MAX_SIZE; 17 | return stk; 18 | } 19 | 20 | void stackPush1(Stack *stk, int data) { 21 | if (stk->top1 < stk->top2 - 1) { 22 | stk->data[++stk->top1] = data; 23 | } else { 24 | printf("Stack is Full!\n"); 25 | } 26 | } 27 | 28 | void stackPush2(Stack *stk, int data) { 29 | if (stk->top1 < stk->top2 - 1) { 30 | stk->data[--stk->top2] = data; 31 | } else { 32 | printf("Stack is Full!\n"); 33 | } 34 | } 35 | 36 | int stackPop1(Stack *stk) { 37 | if (stk->top1 >= 0) { 38 | int value = stk->data[stk->top1--]; 39 | return value; 40 | } else { 41 | printf("Stack Empty!\n"); 42 | } 43 | return ERROR_VALUE; 44 | } 45 | 46 | int stackPop2(Stack *stk) { 47 | if (stk->top2 < MAX_SIZE) { 48 | int value = stk->data[stk->top2++]; 49 | return value; 50 | } else { 51 | printf("Stack Empty!\n"); 52 | } 53 | return ERROR_VALUE; 54 | } 55 | 56 | int main() { 57 | Stack* stk = createStack(); 58 | stackPush1(stk, 1); 59 | stackPush1(stk, 2); 60 | stackPush2(stk, 3); 61 | stackPush2(stk, 4); 62 | printf("%d \n",stackPop1(stk)); 63 | printf("%d \n",stackPop1(stk)); 64 | printf("%d \n",stackPop2(stk)); 65 | printf("%d \n",stackPop2(stk)); 66 | } 67 | 68 | /* 69 | 2 70 | 1 71 | 4 72 | 3 73 | */ 74 | -------------------------------------------------------------------------------- /Algo/Greedy/FractionalKnapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct Item { 5 | int wt; 6 | int cost; 7 | double density; 8 | } Item ; 9 | 10 | Item* createItem(int w, int v) { 11 | Item* item = (Item*)malloc(sizeof(Item)); 12 | item->wt = w; 13 | item->cost = v; 14 | item->density = (double)v / w; 15 | return item; 16 | } 17 | 18 | int less(Item *a, Item *b) { 19 | return a->density < b->density; 20 | } 21 | 22 | void sort(Item * arr[], int size, int (*comp)(Item * p1, Item * p2)) { 23 | int i, j; 24 | for (i = 0; i < (size - 1); i++) { 25 | for (j = 0; j < size - i - 1; j++) { 26 | if (comp(arr[j], arr[j + 1])) { 27 | /* Swapping */ 28 | Item* temp = arr[j]; 29 | arr[j] = arr[j + 1]; 30 | arr[j + 1] = temp; 31 | } 32 | } 33 | } 34 | } 35 | 36 | double getMaxCostFractional(int wt[], int cost[], int n, int capacity) { 37 | double totalCost = 0; 38 | Item* itemList[n]; 39 | for (int i = 0; i < n; i++) { 40 | itemList[i] = createItem(wt[i], cost[i]); 41 | } 42 | 43 | sort(itemList, n, less); 44 | for (int i = 0; i < n; i++) { 45 | if (capacity - itemList[i]->wt >= 0) { 46 | capacity -= itemList[i]->wt; 47 | totalCost += itemList[i]->cost; 48 | } else { 49 | totalCost += (itemList[i]->density * capacity); 50 | break; 51 | } 52 | } 53 | return totalCost; 54 | } 55 | 56 | int main() { 57 | int wt[] = {10, 40, 20, 30}; 58 | int cost[] = {60, 40, 90, 120}; 59 | int capacity = 50; 60 | double maxCost = getMaxCostFractional(wt, cost, 4, capacity); 61 | printf("Maximum cost obtained = %f\n" , maxCost ); 62 | } 63 | 64 | /* 65 | Maximum cost obtained = 230 66 | */ -------------------------------------------------------------------------------- /Algo/Greedy/HuffmanTree.c: -------------------------------------------------------------------------------- 1 | #include "HuffmanTree.h" 2 | 3 | Node* createNode(char ch, int fr, Node *l, Node *r) { 4 | Node *nd = (Node*)malloc(sizeof(Node)); 5 | nd->c = ch; 6 | nd->freq = fr; 7 | nd->left = l; 8 | nd->right = r; 9 | return nd; 10 | } 11 | 12 | int greater(Node *n1, Node *n2) { 13 | return n1->freq > n2->freq; 14 | } 15 | 16 | HuffmanTree* createHuffmanTree(char arr[], int freq[], int n) { 17 | HuffmanTree* tree = (HuffmanTree*)malloc(sizeof(HuffmanTree)); 18 | Heap* hp = createHeap(greater); 19 | for (int i = 0; i < n; i++) { 20 | Node *node = createNode(arr[i], freq[i], NULL, NULL); 21 | heapAdd(hp, node); 22 | } 23 | 24 | while (heapSize(hp) > 1) { 25 | Node *lt = heapRemove(hp); 26 | Node *rt = heapRemove(hp); 27 | Node *nd = createNode('+', lt->freq + rt->freq, lt, rt); 28 | heapAdd(hp, nd); 29 | } 30 | tree->root = heapRemove(hp); 31 | return tree; 32 | } 33 | 34 | void printHuffmanTreeUtil(Node* root, char* s) { 35 | if (root->left == NULL && root->right == NULL && root->c != '+') { 36 | printf("%c = %s\n", root->c, s); 37 | return; 38 | } 39 | strcat(s, "0"); 40 | printHuffmanTreeUtil(root->left, s); 41 | s[strlen(s)-1]='\0'; 42 | strcat(s, "1"); 43 | printHuffmanTreeUtil(root->right, s); 44 | s[strlen(s)-1]='\0'; 45 | } 46 | 47 | void printHuffmanTree(HuffmanTree* tree) { 48 | printf("Char = Huffman code\n" ); 49 | char str[100]=""; 50 | printHuffmanTreeUtil(tree->root, str); 51 | } 52 | 53 | int main() { 54 | char ar[] = {'A', 'B', 'C', 'D', 'E'}; 55 | int fr[] = {30, 25, 21, 14, 10}; 56 | HuffmanTree* tree = createHuffmanTree(ar, fr, 5); 57 | printHuffmanTree(tree); 58 | } 59 | 60 | /* 61 | Char = Huffman code 62 | C = 00 63 | E = 010 64 | D = 011 65 | B = 10 66 | A = 11 67 | */ -------------------------------------------------------------------------------- /Stack/StackLL.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define ERROR_VALUE -9999999 4 | 5 | typedef struct StackNode { 6 | int value; 7 | struct StackNode *next; 8 | } StackNode; 9 | 10 | 11 | typedef struct Stack { 12 | StackNode *head; 13 | } Stack; 14 | 15 | Stack* createStack() { 16 | Stack *stk = (Stack*)malloc(sizeof(Stack)); 17 | stk->head = NULL; 18 | return stk; 19 | } 20 | 21 | int stackIsEmpty(Stack *stk) { 22 | return stk->head == NULL; 23 | } 24 | 25 | void stackPush(Stack *stk, int value) { 26 | StackNode *temp = (StackNode *)malloc(sizeof(StackNode)); 27 | if (!temp) { 28 | printf("Memory allocation error.\n"); 29 | return; 30 | } 31 | temp->value = value; 32 | temp->next = stk->head; 33 | stk->head = temp; 34 | } 35 | 36 | int stackPop(Stack *stk) { 37 | StackNode *deleteMe; 38 | if(stk->head == NULL) { 39 | printf("Stack is empty.\n"); 40 | return ERROR_VALUE; 41 | } 42 | deleteMe = stk->head; 43 | stk->head = stk->head->next; 44 | int value = deleteMe->value; 45 | free(deleteMe); 46 | return value; 47 | } 48 | 49 | void stackPrint(Stack *stk) { 50 | if (!stk->head) 51 | return; 52 | 53 | StackNode *head = stk->head; 54 | printf("Stack : "); 55 | while (head != NULL) { 56 | printf("%d ", head->value); 57 | head = head->next; 58 | } 59 | printf("\n"); 60 | } 61 | 62 | 63 | int main() { 64 | Stack* stk= createStack(); 65 | stackPush(stk, 1); 66 | stackPush(stk, 2); 67 | stackPush(stk, 3); 68 | stackPrint(stk); 69 | printf("%d ", stackPop(stk)); 70 | printf("%d ", stackPop(stk)); 71 | return 0; 72 | } 73 | /* 74 | Stack : 3 2 1 75 | 3 2 76 | */ -------------------------------------------------------------------------------- /Algo/BT/TSP.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int tspUtil(int n, int graph[n][n], int path[], int pSize, int pCost, int visited[], int ans, int ansPath[]) { 6 | if(pCost >= ans) // Ignore useless paths. 7 | return ans; 8 | 9 | int curr = path[pSize - 1]; 10 | if (pSize == n) { 11 | int first = path[0]; 12 | if(graph[curr][first] > 0 && ans > pCost + graph[curr][first]) { 13 | for (int i = 0; i <= n; i++) { 14 | ansPath[i] = path[i%n]; 15 | } 16 | ans = pCost + graph[curr][first]; 17 | } 18 | return ans; 19 | } 20 | 21 | for (int i = 0; i < n ; i++) { 22 | if (visited[i] == 0 && graph[curr][i] > 0) { 23 | visited[i] = 1; 24 | path[pSize] = i; 25 | ans = tspUtil(n, graph, path, pSize+1, pCost + graph[curr][i],visited, ans, ansPath); 26 | visited[i] = 0; 27 | } 28 | } 29 | return ans; 30 | } 31 | 32 | int tsp(int n, int graph[n][n]) { 33 | int visited[n]; 34 | int path[n]; 35 | int ansPath[n+1]; 36 | 37 | for(int i = 0; i < n; i++) { 38 | visited[i] = 0; 39 | path[i] = 0; 40 | } 41 | 42 | int source = 0; 43 | path[0] = source; 44 | visited[source] = 1; 45 | 46 | int ans = 99999; 47 | ans = tspUtil(n, graph, path, 1 /*path length*/, 0 /*path cost*/, 48 | visited, ans, ansPath); 49 | printf("Shortest Path weight: %d\n", ans); 50 | printf("Shortest Path is: "); 51 | for (int i = 0; i <= n; i++) 52 | printf("%d ", ansPath[i]); 53 | return ans; 54 | } 55 | 56 | int main() { 57 | int n = 4; 58 | int graph[4][4] = {{0, 1, 5, 10}, 59 | {1, 0, 25, 15}, 60 | {5, 25, 0, 20}, 61 | {10, 15, 20, 0}}; 62 | 63 | tsp(n, graph); 64 | return 0; 65 | } 66 | 67 | /* 68 | Shortest Path weight: 41 69 | Shortest Path is: 0 1 3 2 0 70 | */ -------------------------------------------------------------------------------- /Algo/Greedy/ActivitySelection.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct Activity { 5 | int start; 6 | int stop; 7 | } Activity ; 8 | 9 | Activity* createActivity(int s, int f) { 10 | Activity* act = (Activity*)malloc(sizeof(Activity)); 11 | act->start = s; 12 | act->stop = f; 13 | } 14 | 15 | int compare(Activity *s1, Activity *s2) { 16 | return (s1->stop > s2->stop); 17 | } 18 | 19 | void sort(Activity* arr[], int size, int (*comp)(Activity* p1, Activity* p2)) { 20 | int i, j; 21 | Activity* temp; 22 | for (i = 0; i < (size - 1); i++) { 23 | for (j = 0; j < size - i - 1; j++) { 24 | if (comp(arr[j], arr[j + 1])) { 25 | /* Swapping */ 26 | temp = arr[j]; 27 | arr[j] = arr[j + 1]; 28 | arr[j + 1] = temp; 29 | } 30 | } 31 | } 32 | } 33 | 34 | void maxActivities(int s[], int f[], int n) { 35 | Activity* act[n]; 36 | for (int i = 0; i < n; i++) { 37 | act[i] = createActivity(s[i], f[i]); 38 | } 39 | 40 | sort(act, n, compare); // sort according to finish time. 41 | int i = 0; // The first activity at index 0 is always gets selected. 42 | printf("Activities are : (%d, %d)", act[i]->start ,act[i]->stop); 43 | 44 | for (int j = 1; j < n; j++) { 45 | // Find next activity whose start time is greater than or equal 46 | // to the finish time of previous activity. 47 | if (act[j]->start >= act[i]->stop) { 48 | printf(" (%d, %d)", act[j]->start ,act[j]->stop); 49 | i = j; 50 | } 51 | } 52 | } 53 | 54 | int main() { 55 | int s[] = {1, 5, 0, 3, 5, 6, 8}; 56 | int f[] = {2, 6, 5, 4, 9, 7, 9}; 57 | maxActivities(s, f, sizeof(s)/sizeof(int)); 58 | return 0; 59 | } 60 | 61 | /* 62 | Activities are : (1, 2) (3, 4) (5, 6) (6, 7) (8, 9) 63 | */ 64 | -------------------------------------------------------------------------------- /Algo/Greedy/MultipleStageGraph.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int INFINITE = 99999; 5 | 6 | int shortestDist(int n, int graph[][n]) { 7 | // dist[i] is going to store shortest distance from node i to node n-1. 8 | int dist[n]; 9 | int path[n]; 10 | for (int i = 0; i < n; i++) 11 | dist[i] = INFINITE; 12 | 13 | int value; 14 | dist[0] = 0; 15 | path[0] = -1; 16 | 17 | // Calculating shortest path for the nodes 18 | for (int i = 0; i < n; i++) { 19 | // Check all nodes of next 20 | for (int j = i; j < n; j++) { 21 | // Reject if no edge exists 22 | if (graph[i][j] == INFINITE) 23 | { 24 | continue; 25 | } 26 | value = graph[i][j] + dist[i]; 27 | if (dist[j] > value) 28 | { 29 | dist[j] = value; 30 | path[j] = i; 31 | } 32 | } 33 | } 34 | value = n - 1; 35 | while (value != -1) { 36 | printf("%d ", value); 37 | value = path[value]; 38 | } 39 | printf("\n"); 40 | return dist[n - 1]; 41 | } 42 | 43 | int main() { 44 | // Graph stored in the form of an adjacency Matrix 45 | int n = 8; 46 | int graph[][8] = 47 | { 48 | {INFINITE, 1, 2, 5, INFINITE, INFINITE, INFINITE, INFINITE}, 49 | {INFINITE, INFINITE, INFINITE, INFINITE, 4, 11, INFINITE, INFINITE}, 50 | {INFINITE, INFINITE, INFINITE, INFINITE, 9, 5, 16, INFINITE}, 51 | {INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, 2, INFINITE}, 52 | {INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, 18}, 53 | {INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, 13}, 54 | {INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, 2}, 55 | {INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE, INFINITE} 56 | }; 57 | 58 | printf("%d\n", shortestDist(n, graph)); 59 | } 60 | /* 61 | 7 6 3 0 62 | 9 63 | */ -------------------------------------------------------------------------------- /Algo/Greedy/ChotaBhim.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "../../Heap/Heap.c" 5 | 6 | void bubbleSort(int arr[], int size, int (*comp)(int p1, int p2)) { 7 | int i, j; 8 | int temp; 9 | for (i = 0; i < (size - 1); i++) { 10 | for (j = 0; j < size - i - 1; j++) { 11 | if (comp(arr[j], arr[j + 1])) { 12 | /* Swapping */ 13 | temp = arr[j]; 14 | arr[j] = arr[j + 1]; 15 | arr[j + 1] = temp; 16 | } 17 | } 18 | } 19 | } 20 | 21 | int chotaBhim(int cups[], int size) { 22 | int time = 60; 23 | bubbleSort(cups, size, less); // decreasing order. 24 | int total = 0; 25 | int index, temp; 26 | while (time > 0) { 27 | total += cups[0]; 28 | cups[0] = ceil(cups[0] / 2.0); 29 | index = 0; 30 | temp = cups[0]; 31 | while (index < size - 1 && temp < cups[index + 1]) { 32 | cups[index] = cups[index + 1]; 33 | index += 1; 34 | } 35 | cups[index] = temp; 36 | time -= 1; 37 | } 38 | printf("Total : %d\n" , total ); 39 | return total; 40 | } 41 | 42 | int chotaBhim2(int cups[], int size) { 43 | int time = 60; 44 | Heap* hp = createHeap2(cups, size, less); // max heap 45 | int total = 0; 46 | int value; 47 | while (time > 0) { 48 | value = heapRemove(hp); 49 | total += value; 50 | value = ceil(value / 2.0); 51 | heapAdd(hp, value); 52 | time -= 1; 53 | } 54 | printf("Total : %d\n", total); 55 | return total; 56 | } 57 | 58 | int main() { 59 | int cups[] = {2, 1, 7, 4, 2}; 60 | chotaBhim(cups, sizeof(cups) / sizeof(int)); 61 | int cups2[] = {2, 1, 7, 4, 2}; 62 | chotaBhim2(cups2, sizeof(cups) / sizeof(int)); 63 | return 0; 64 | } 65 | 66 | /* 67 | Total : 76 68 | Total : 76 69 | */ -------------------------------------------------------------------------------- /Algo/Greedy/JoinRopes.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../../Heap/Heap.c" 4 | 5 | void sort(int arr[], int size, int (*comp)(int p1, int p2)) { 6 | int i, j; 7 | int temp; 8 | for (i = 0; i < (size - 1); i++) { 9 | for (j = 0; j < size - i - 1; j++) { 10 | if (comp(arr[j], arr[j + 1])) { 11 | /* Swapping */ 12 | temp = arr[j]; 13 | arr[j] = arr[j + 1]; 14 | arr[j + 1] = temp; 15 | } 16 | } 17 | } 18 | } 19 | 20 | int JoinRopes(int ropes[], int size) { 21 | sort(ropes, size, less); // decreasing 22 | int total = 0; 23 | int value = 0; 24 | int temp, index; 25 | int length = size; 26 | 27 | while (length >= 2) { 28 | value = ropes[length - 1] + ropes[length - 2]; 29 | total += value; 30 | index = length - 2; 31 | 32 | while (index > 0 && ropes[index - 1] < value) { 33 | ropes[index] = ropes[index - 1]; 34 | index -= 1; 35 | } 36 | ropes[index] = value; 37 | length--; 38 | } 39 | printf("Total : %d \n", total); 40 | return total; 41 | } 42 | 43 | int JoinRopes2(int ropes[], int size) { 44 | Heap* hp = createHeap2(ropes, size, greater); 45 | int total = 0; 46 | int value = 0; 47 | while (heapSize(hp) > 1) { 48 | value = heapRemove(hp); 49 | value += heapRemove(hp); 50 | heapAdd(hp, value); 51 | total += value; 52 | } 53 | printf("Total : %d \n", total); 54 | return total; 55 | } 56 | 57 | int main() { 58 | int ropes[] = {4, 3, 2, 6}; 59 | JoinRopes(ropes, sizeof(ropes) / sizeof(int)); 60 | int rope2[] = {4, 3, 2, 6}; 61 | JoinRopes2(rope2, sizeof(rope2) / sizeof(int)); 62 | return 0; 63 | } 64 | 65 | /* 66 | Total : 29 67 | Total : 29 68 | */ -------------------------------------------------------------------------------- /Queue/Queue.c: -------------------------------------------------------------------------------- 1 | //#include "stdafx.h" 2 | #include "stdio.h" 3 | #include "stdlib.h" 4 | 5 | #define QUEUE_CAPACITY 2000 6 | 7 | #ifndef ERROR_VALUE 8 | #define ERROR_VALUE -99999 9 | #endif 10 | 11 | typedef struct Queue { 12 | int front; 13 | int back; 14 | int size; 15 | int data[QUEUE_CAPACITY]; 16 | } Queue; 17 | 18 | Queue* createQueue() { 19 | Queue* que = (Queue*)malloc(sizeof(Queue)); 20 | que->back = 0; 21 | que->front = 0; 22 | que->size = 0; 23 | return que; 24 | } 25 | 26 | void queueAdd(Queue *que, int value) { 27 | if (que->size == QUEUE_CAPACITY) { 28 | printf("Queue is full.\n"); 29 | return; 30 | } 31 | que->size++; 32 | que->data[que->back] = value; 33 | que->back = (que->back + 1) % QUEUE_CAPACITY; 34 | } 35 | 36 | int queueRemove(Queue *que) { 37 | int value; 38 | if (que->size == 0) { 39 | printf("Queue is empty.\n"); 40 | return ERROR_VALUE; 41 | } 42 | que->size--; 43 | value = que->data[que->front]; 44 | que->front = (que->front + 1) % QUEUE_CAPACITY; 45 | return value; 46 | } 47 | 48 | int queueFront(Queue *que) { 49 | return que->data[que->front]; 50 | } 51 | 52 | int queueBack(Queue *que) { 53 | return que->data[que->back-1]; 54 | } 55 | 56 | int queueRemoveBack(Queue *que) { 57 | int value; 58 | if (que->size == 0) { 59 | printf("Queue is empty.\n"); 60 | return ERROR_VALUE; 61 | } 62 | que->size--; 63 | value = que->data[que->back - 1]; 64 | que->back = (que->back - 1) % QUEUE_CAPACITY; 65 | return value; 66 | } 67 | 68 | int queueIsEmpty(Queue *que) { 69 | return que->size == 0; 70 | } 71 | 72 | int queueSize(Queue *que) { 73 | return que->size; 74 | } 75 | 76 | void queuePrint(Queue *que) { 77 | int size = que->size; 78 | printf("[ "); 79 | int index = que->front; 80 | for (int i=0;idata[index]); 82 | index = (index + 1) % QUEUE_CAPACITY; 83 | } 84 | printf("]\n"); 85 | } -------------------------------------------------------------------------------- /Heap/BinomialHeap.py: -------------------------------------------------------------------------------- 1 | function BinomailHeapUnion(H1, H2): 2 | H = CreateBinomialHeap() 3 | H.head = BinomailHeapMerge(H1, H2) 4 | if H.head == null: 5 | then return H 6 | prev = null 7 | curr = H.head 8 | sibling = curr.sibling 9 | 10 | while sibling != null: 11 | if curr.degree != sibling.degree or 12 | ( sibling.next != null and sibling.next.degree == curr.degree ): 13 | prev = curr 14 | curr = sibling 15 | else : 16 | if curr.key <= sibling.key: # sibling become child of curr. 17 | curr.sibling = sibling.sibling 18 | left = curr.leftchild 19 | curr.leftchild = sibling 20 | sibling.sibling = left 21 | sibling.parent = curr 22 | 23 | else: # curr become child of sibling. 24 | if prev == null: 25 | H.head = sibling 26 | else: 27 | prev.sibling = sibling 28 | 29 | left = sibling.leftchild 30 | sibling.leftchild = curr 31 | curr.parent = sibling 32 | curr.sibling = left 33 | 34 | # Sibling became new root. 35 | curr = sibling 36 | 37 | 38 | sibling = curr.sibling 39 | 40 | return H 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | function BinomialHeapMinimum(H) 50 | y = null 51 | x = H.head 52 | min = ∞ 53 | while x != null 54 | do if x.key < min 55 | then min = x.key 56 | y = x 57 | x = x.sibling 58 | return y 59 | 60 | 61 | function BinomialHeapInsert(H, x) 62 | H2 = CreateBinomialHeap() 63 | x.parent = null 64 | x.leftchild = null 65 | x.sibling = null 66 | x.degree = 0 67 | H2.head = x 68 | H = BinomailHeapUnion(H,H2) -------------------------------------------------------------------------------- /Heap/SkipList.py: -------------------------------------------------------------------------------- 1 | function Search(list, key) 2 | p = top-left node in list 3 | while (p.below != null) //Scan down 4 | p = p.below 5 | while (key >= p.next) //Scan forward 6 | p = p.next 7 | return p 8 | 9 | 10 | function Insert(list, key, value) 11 | // Create update array 12 | local update[0...MaxLevel+1] 13 | x = list.header 14 | 15 | // Populate update array to find 16 | // the possition of new node at each level. 17 | for i = (list.level - 1) downto 0 18 | while x.forward[i] != Null and x.forward[i].key < key 19 | x = x.forward[i] 20 | update[i] = x 21 | 22 | // Key already present so just update value. 23 | if x.forward[0] != Null and x.forward[0].key = key 24 | x.forward[0].value = value 25 | return; 26 | 27 | 28 | // Level of the new node is created. 29 | // if level is increased then header will be 30 | // the start of new level list. 31 | lvl = randomLevel() 32 | if lvl > list.level 33 | for i = list.level to (lvl - 1) 34 | update[i] = list.header 35 | list.level = lvl 36 | 37 | // New node is created and linked at each level. 38 | x = makeNode(key, value, lvl) 39 | for i = 0 to lvl 40 | x.forward[i] = update[i].forward[i] 41 | update[i].forward[i] = x 42 | 43 | 44 | function Delete(list, key) 45 | local update[0..MaxLevel+1] 46 | x = list.header 47 | for i = (list.level - 1) downto 0 do 48 | while x.forward[i] != Null and x.forward[i].key < key 49 | x = x.forward[i] 50 | update[i] = x 51 | 52 | x = x.forward[0] 53 | if x.key = key 54 | for i = 0 to list.level-1 55 | if update[i].forward[i] ≠ x 56 | then break 57 | update[i].forward[i] = x.forward[i] 58 | free(x) 59 | while list.level > 0 and list.header.forward[list.level] = Null 60 | list.level = list.level - 1 61 | -------------------------------------------------------------------------------- /Algo/BT/Permutations.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void printArray(int arr[], int n) { 5 | for (int i = 0;i < n;i++) 6 | printf("%d ", arr[i]); 7 | printf("\n"); 8 | } 9 | 10 | void swap(int arr[], int i, int j) { 11 | int temp = arr[i]; 12 | arr[i] = arr[j]; 13 | arr[j] = temp; 14 | } 15 | 16 | void permutation(int arr[], int i, int length) { 17 | if (length == i) { 18 | printArray(arr, length); 19 | return; 20 | } 21 | 22 | for (int j = i; j < length; j++) { 23 | swap(arr, i, j); 24 | permutation(arr, i + 1, length); 25 | swap(arr, i, j); 26 | } 27 | return; 28 | } 29 | 30 | int isValid(int arr[], int n) { 31 | for (int j = 1;j < n;j++) { 32 | if (abs(arr[j] - arr[j - 1]) < 2) { 33 | return 0; 34 | } 35 | } 36 | return 1; 37 | } 38 | 39 | void permutation2(int arr[], int i, int length) { 40 | if (length == i) { 41 | if (isValid(arr, length)) { 42 | printArray(arr, length); 43 | } 44 | return; 45 | } 46 | 47 | for (int j = i; j < length; j++) { 48 | swap(arr, i, j); 49 | permutation2(arr, i + 1, length); 50 | swap(arr, i, j); 51 | } 52 | return; 53 | } 54 | 55 | int isValid2(int arr[], int i) { 56 | if (i < 1 || abs(arr[i] - arr[i - 1]) >= 2) { 57 | return 1; 58 | } 59 | return 0; 60 | } 61 | 62 | void permutation3(int arr[], int i, int length) { 63 | if (length == i) { 64 | printArray(arr, length); 65 | return; 66 | } 67 | 68 | for (int j = i; j < length; j++) { 69 | swap(arr, i, j); 70 | if (isValid2(arr, i)) { 71 | permutation3(arr, i + 1, length); 72 | } 73 | swap(arr, i, j); 74 | } 75 | return; 76 | } 77 | 78 | int main() { 79 | int arr[4] = {1,2,3,4}; 80 | permutation(arr, 0, 4); 81 | printf("\n"); 82 | permutation2(arr, 0, 4); 83 | printf("\n"); 84 | permutation3(arr, 0, 4); 85 | return 0; 86 | } 87 | 88 | /* 89 | 1 2 3 4 90 | 1 2 4 3 91 | .... 92 | 4 1 3 2 93 | 4 1 2 3 94 | 95 | 2 4 1 3 96 | 3 1 4 2 97 | 98 | 2 4 1 3 99 | 3 1 4 2 100 | */ -------------------------------------------------------------------------------- /Heap/Strassens.py: -------------------------------------------------------------------------------- 1 | # Splits a given matrix into quarters of n/2 x n/2. 2 | def Split(matrix): 3 | row, col = matrix.shape 4 | row2, col2 = row//2, col//2 5 | return matrix[:row2, :col2], matrix[:row2, col2:], matrix[row2:, :col2], matrix[row2:, col2:] 6 | 7 | 8 | def multiply(a, b): 9 | for i=0 to N-1 10 | for j=0 to N-1 11 | c[i, j] = 0 12 | for k=0 to N 13 | c[i][j] += a[i, k]*b[k, j] 14 | return c 15 | 16 | 17 | function multiply(x, y) 18 | // Base case when size of matrices is 1x1 19 | if Size(x) = 1 20 | return x * y 21 | 22 | // Splitting the matrices into 4 quadrants. 23 | // This will be done recursively until the base case is reached. 24 | a, b, c, d = Split(x) 25 | e, f, g, h = Split(y) 26 | 27 | A = multiply(a) 28 | B = multiply(b) 29 | C = multiply(c) 30 | D = multiply(d) 31 | E = multiply(e) 32 | F = multiply(f) 33 | G = multiply(g) 34 | H = multiply(h) 35 | 36 | // Computing the values of the 4 quadrants of the output matrix c 37 | c11 = A*E + B*G 38 | c12 = A*F + B*H 39 | c21 = C*E + D*G 40 | c22 = C*F + D*H 41 | 42 | // Combining the 4 quadrants into a single output matrix. 43 | c = Combine(c11, c12, c21, c22) 44 | return c 45 | 46 | def Strassen(x, y): 47 | 48 | # Base case when size of matrices is 1x1 49 | if Size(x) = 1: 50 | return x * y 51 | 52 | # Splitting the matrices into quadrants. This will be done recursively 53 | # until the base case is reached. 54 | a, b, c, d = Split(x) 55 | e, f, g, h = Split(y) 56 | 57 | # Computing the 7 products, recursively (p1, p2...p7) 58 | m1 = Strassen(a, f - h) 59 | m2 = Strassen(a + b, h) 60 | m3 = Strassen(c + d, e) 61 | m4 = Strassen(d, g - e) 62 | m5 = Strassen(a + d, e + h) 63 | m6 = Strassen(b - d, g + h) 64 | m7 = Strassen(a - c, e + f) 65 | 66 | # Computing the values of the 4 quadrants of the final matrix c 67 | c11 = m5 + m4 - m2 + m6 68 | c12 = m1 + m2 69 | c21 = m3 + m4 70 | c22 = m1 + m5 - m3 - m7 71 | 72 | # Combining the 4 quadrants into a single matrix by stacking horizontally and vertically. 73 | c = Combine(c11, c12, c21, c22) 74 | 75 | return c 76 | -------------------------------------------------------------------------------- /Queue/QueueLL.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define ERROR_VALUE 999999; 4 | 5 | typedef struct QueueNode { 6 | int value; 7 | struct QueueNode *next; 8 | } QueueNode; 9 | 10 | typedef struct Queue { 11 | QueueNode *tail; 12 | } Queue; 13 | 14 | Queue* createQueue() { 15 | Queue *queue = (Queue*) malloc(sizeof(Queue)); 16 | queue->tail = NULL; 17 | return queue; 18 | } 19 | 20 | int queueIsEmpty(Queue *queue) { 21 | return queue->tail == NULL; 22 | } 23 | 24 | int queueAdd(Queue *queue, int value) { 25 | QueueNode *temp = (QueueNode *)malloc(sizeof(QueueNode)); 26 | if (!temp) { 27 | printf("Memory Allocation Error"); 28 | return 0; 29 | } 30 | temp->value = value; 31 | 32 | if (!queue->tail) { 33 | temp->next = temp; 34 | queue->tail = temp; 35 | } else { 36 | temp->next = queue->tail->next; 37 | queue->tail->next = temp; 38 | queue->tail = temp; 39 | } 40 | return 1; 41 | } 42 | int queueRemove(Queue *queue) { 43 | int value; 44 | QueueNode *deleteMe; 45 | 46 | if (!queue->tail) 47 | return ERROR_VALUE; 48 | 49 | if (queue->tail->next == queue->tail) { 50 | value = queue->tail->value; 51 | free(queue->tail); 52 | queue->tail = NULL; 53 | return value; 54 | } 55 | 56 | deleteMe = queue->tail->next; 57 | value = deleteMe->value; 58 | queue->tail->next = deleteMe->next; 59 | free(deleteMe); 60 | return value; 61 | } 62 | 63 | void queuePrint(Queue *queue) { 64 | if (!queue->tail) 65 | return; 66 | 67 | QueueNode *head = queue->tail->next; 68 | printf("Queue %d ", head->value); 69 | QueueNode *currNode = head->next; 70 | while (currNode != head) { 71 | printf("%d ", currNode->value); 72 | currNode = currNode->next; 73 | } 74 | printf("\n"); 75 | } 76 | 77 | int main() { 78 | Queue* queue = createQueue(); 79 | queueAdd(queue, 1); 80 | queueAdd(queue, 2); 81 | queueAdd(queue, 3); 82 | printf("%d ", queueRemove(queue)); 83 | printf("%d ", queueRemove(queue)); 84 | printf("%d ", queueRemove(queue)); 85 | return 0; 86 | } -------------------------------------------------------------------------------- /.settings/language.settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Algo/DP/WildCharMatch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int matchExpUtil(char* exp, char* str, int m, int n) { 6 | if (m == strlen(exp) && (n == strlen(str) || exp[m - 1] == '*')) 7 | return 1; 8 | 9 | if ((m == strlen(exp) && n != strlen(str)) || (m != strlen(exp) && n == strlen(str))) 10 | return 0; 11 | 12 | if (exp[m] == '?' || exp[m] == str[n]) 13 | return matchExpUtil(exp, str, m + 1, n + 1); 14 | 15 | if (exp[m] == '*') 16 | return matchExpUtil(exp, str, m + 1, n) || matchExpUtil(exp, str, m, n + 1); 17 | 18 | return 0; 19 | } 20 | 21 | int matchExp(char* exp, char* str) { 22 | return matchExpUtil(exp, str, 0, 0); 23 | } 24 | 25 | int matchExpDPUtil(char* exp, char* str, int m, int n) { 26 | int lookup[m + 1][n + 1]; 27 | lookup[0][0] = 1; // empty exp and empty str match. 28 | 29 | // 0 row will remain all 0. empty exp can't match any str. 30 | // '*' can match with empty string, column 0 update. 31 | for (int i = 1; i <= m; i++) { 32 | if (exp[i - 1] == '*') 33 | lookup[i][0] = lookup[i - 1][0]; 34 | else 35 | break; 36 | } 37 | 38 | // Fill the table in bottom-up fashion 39 | for (int i = 1; i <= m; i++) { 40 | for (int j = 1; j <= n; j++) { 41 | // If we see a '*' in pattern: 42 | // 1) We ignore '*' character and consider next character in the pattern. 43 | // 2) We ignore one character in the input str and consider next character. 44 | if (exp[i - 1] == '*') 45 | lookup[i][j] = lookup[i - 1][j] || lookup[i][j - 1]; 46 | // Condition when both the pattern and input string have same character. 47 | // Also '?' match with all the characters. 48 | else if (exp[i - 1] == '?' || str[j - 1] == exp[i - 1]) 49 | lookup[i][j] = lookup[i - 1][j - 1]; 50 | // If characters don't match 51 | else 52 | lookup[i][j] = 0; 53 | } 54 | } 55 | return lookup[m][n]; 56 | } 57 | 58 | int matchExpDP(char* exp, char* str) { 59 | return matchExpDPUtil(exp, str, strlen(exp), strlen(str)); 60 | } 61 | 62 | int main() { 63 | printf("matchExp :: %d\n",matchExp("*llo,?World?", "Hello, World!")); 64 | printf("matchExp :: %d\n",matchExpDP("*llo,?World?", "Hello, World!")); 65 | } 66 | 67 | /* 68 | matchExp :: 1 69 | matchExp :: 1 70 | */ -------------------------------------------------------------------------------- /Algo/Greedy/JobSequencing.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct Job { 5 | char id; 6 | int deadline; 7 | int profit; 8 | } Job; 9 | 10 | Job* createJob(char id, int deadline, int profit) { 11 | Job* job = (Job*)malloc(sizeof(Job)); 12 | job->id = id; 13 | job->deadline = deadline; 14 | job->profit = profit; 15 | return job; 16 | } 17 | 18 | int max(int a, int b) { 19 | return (a > b)? a : b; 20 | } 21 | 22 | int less(Job *a, Job *b) { 23 | return a->profit < b->profit; 24 | } 25 | 26 | void sort(Job * arr[], int size, int (*comp)(Job * p1, Job * p2)) { 27 | for (int i = 0; i < (size - 1); i++) { 28 | for (int j = 0; j < size - i - 1; j++) { 29 | if (comp(arr[j], arr[j + 1])) { 30 | /* Swapping */ 31 | Job* temp = arr[j]; 32 | arr[j] = arr[j + 1]; 33 | arr[j + 1] = temp; 34 | } 35 | } 36 | } 37 | } 38 | 39 | int JobSequencing(char ids[], int deadlines[], int profits[], int n) { 40 | Job* jobs[n]; 41 | int maxDL = deadlines[0]; 42 | for (int i = 1; i < n; i++) 43 | maxDL = max(maxDL, deadlines[i]); 44 | 45 | for (int i = 0;i < n;i++) 46 | jobs[i] = createJob(ids[i], deadlines[i], profits[i]); 47 | 48 | sort(jobs, n, less); // decreasing order. 49 | 50 | int result[maxDL]; 51 | for (int i = 0; i < maxDL; i++) 52 | result[i] = 0; 53 | 54 | char answer[maxDL]; 55 | for (int i = 0; i < maxDL; i++) 56 | answer[i] = '0'; 57 | 58 | int profit = 0; 59 | 60 | // Iterate through all given jobs 61 | for (int i = 0; i < n; i++) { 62 | for (int j = jobs[i]->deadline - 1; j >= 0; j--) { 63 | if (result[j] == 0) 64 | { 65 | result[j] = 1; 66 | answer[j] = jobs[i]->id; 67 | profit += jobs[i]->profit; 68 | break; 69 | } 70 | } 71 | } 72 | printf("Profit is :: %d\n" , profit ); 73 | printf("Jobs selected are::"); 74 | for (int i = 0;i < maxDL;i++) { 75 | if (answer[i] != '0') { 76 | printf("%c " , answer[i]); 77 | } 78 | } 79 | return profit; 80 | } 81 | 82 | int main() { 83 | char id[] = {'a', 'b', 'c', 'd', 'e'}; 84 | int deadline[] = {3, 1, 2, 4, 4}; 85 | int profit[] = {50, 40, 27, 31, 30}; 86 | JobSequencing(id, deadline, profit, 5); 87 | } 88 | 89 | /* 90 | Profit is :: 151 91 | Jobs selected are::b e a d 92 | */ -------------------------------------------------------------------------------- /Algo/DP/EditDist.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int min(int x, int y, int z) { 6 | x = (x < y)? x : y; 7 | return x = (x < z)? x : z; 8 | } 9 | 10 | int editDistUtil(char* str1, char* str2, int m, int n) { 11 | // If any one string is empty, then empty the other string. 12 | if (m == 0 || n == 0) 13 | return m + n; 14 | 15 | // If last characters of both strings are same then ignore last characters. 16 | if (str1[m - 1] == str2[n - 1]) { 17 | return editDistUtil(str1, str2, m - 1, n - 1); 18 | } 19 | 20 | // If last characters are different then consider all three cases: 21 | // 1) Insert last char of second into first. 22 | // 2) Remove last char of first. 23 | // 3) Replace last char of first with second. 24 | return 1 + min(editDistUtil(str1, str2, m, n - 1), 25 | editDistUtil(str1, str2, m - 1, n), 26 | editDistUtil(str1, str2, m - 1, n - 1)); // Replace 27 | } 28 | 29 | int editDist(char* str1, char* str2) { 30 | int m = strlen(str1); 31 | int n = strlen(str2); 32 | return editDistUtil(str1, str2, m, n); 33 | } 34 | 35 | int editDistDP(char* str1, char* str2) { // bottom up approach 36 | int m = strlen(str1); 37 | int n = strlen(str2); 38 | int dp[m + 1][n + 1]; 39 | 40 | // Fill dp[][] in bottom up manner. 41 | for (int i = 0; i <= m; i++) { 42 | for (int j = 0; j <= n; j++) { 43 | // If any one string is empty then empty the other string. 44 | if (i == 0 || j == 0) { 45 | dp[i][j] = (i + j); 46 | } 47 | // If last characters of both strings are same then ignore last characters. 48 | else if (str1[i - 1] == str2[j - 1]) { 49 | dp[i][j] = dp[i - 1][j - 1]; 50 | } 51 | // If last characters are different then consider all three operations: 52 | // 1) Insert last char of second into first. 53 | // 2) Remove last char of first. 54 | // 3) Replace last char of first with second. 55 | else { 56 | dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]); // Replace 57 | } 58 | } 59 | } 60 | return dp[m][n]; 61 | } 62 | 63 | int main() { 64 | char* str1 = "sunday"; 65 | char* str2 = "saturday"; 66 | printf("EditDist is %d\n", editDist(str1, str2)); 67 | printf("EditDist is %d\n", editDistDP(str1, str2)); 68 | return 0; 69 | } 70 | 71 | /* 72 | EditDist is 3 73 | EditDist is 3 74 | */ -------------------------------------------------------------------------------- /Algo/DP/StockBuySell.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int maxProfit(int arr[], int n) { 6 | int buyProfit = -arr[0]; // Buy stock profit 7 | int sellProfit = 0; // Sell stock profit 8 | 9 | for (int i = 1; i < n; i++) { 10 | int newBuyProfit = (sellProfit - arr[i] > buyProfit)? sellProfit - arr[i] : buyProfit; 11 | int newSellProfit = (buyProfit + arr[i] > sellProfit)? buyProfit + arr[i] : sellProfit; 12 | buyProfit = newBuyProfit; 13 | sellProfit = newSellProfit; 14 | } 15 | return sellProfit; 16 | } 17 | 18 | int maxProfitTC(int arr[], int n, int t) { 19 | int buyProfit = -arr[0]; 20 | int sellProfit = 0; 21 | 22 | for (int i = 1;i < n;i++) { 23 | int newBuyProfit = ((sellProfit - arr[i]) > buyProfit) ? (sellProfit - arr[i]) : buyProfit; 24 | int newSellProfit = ((buyProfit + arr[i] - t) > sellProfit) ? (buyProfit + arr[i] - t) : sellProfit; 25 | buyProfit = newBuyProfit; 26 | sellProfit = newSellProfit; 27 | } 28 | return sellProfit; 29 | } 30 | 31 | int maxProfit2(int arr[], int n) { 32 | int dp[n][2]; 33 | memset(dp, 0, sizeof(dp)); 34 | dp[0][0] = -arr[0]; // Buy stock profit 35 | dp[0][1] = 0; // Sell stock profit 36 | 37 | for (int i = 1;i < n;i++) { 38 | dp[i][0] = (dp[i - 1][1] - arr[i] > dp[i - 1][0]) ? dp[i - 1][1] - arr[i] : dp[i - 1][0]; 39 | dp[i][1] = (dp[i - 1][0] + arr[i] > dp[i - 1][1]) ? dp[i - 1][0] + arr[i] : dp[i - 1][1]; 40 | } 41 | return dp[n - 1][1]; 42 | } 43 | 44 | int maxProfitTC2(int arr[], int n, int t) { 45 | int dp[n][2]; 46 | memset(dp, 0, sizeof(dp)); 47 | dp[0][0] = -arr[0]; 48 | dp[0][1] = 0; 49 | 50 | for (int i = 1;i < n;i++) { 51 | dp[i][0] = ((dp[i - 1][1] - arr[i]) > dp[i - 1][0]) ? (dp[i - 1][1] - arr[i]) : dp[i - 1][0]; 52 | dp[i][1] = ((dp[i - 1][0] + arr[i] - t) > dp[i - 1][1]) ? (dp[i - 1][0] + arr[i] - t) : dp[i - 1][1]; 53 | } 54 | return dp[n - 1][1]; 55 | } 56 | 57 | int main() { 58 | int arr[] = {10, 12, 9, 23, 25, 55, 49, 70}; 59 | int n = sizeof(arr)/sizeof(int); 60 | printf("Total profit: %d\n" , maxProfit(arr, n)); 61 | printf("Total profit: %d\n" , maxProfit2(arr, n)); 62 | printf("Total profit: %d\n" , maxProfitTC(arr, n, 2)); 63 | printf("Total profit: %d\n" , maxProfitTC2(arr, n, 2)); 64 | } 65 | 66 | /* 67 | Total profit: 69 68 | Total profit: 69 69 | Total profit: 63 70 | Total profit: 63 71 | */ -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "(gdb) Launch", 9 | "type": "cppdbg", 10 | "request": "launch", 11 | "program": "enter program name, for example ${workspaceFolder}/a.out", 12 | "args": [], 13 | "stopAtEntry": false, 14 | "cwd": "${fileDirname}", 15 | "environment": [], 16 | "externalConsole": false, 17 | "MIMode": "gdb", 18 | "setupCommands": [ 19 | { 20 | "description": "Enable pretty-printing for gdb", 21 | "text": "-enable-pretty-printing", 22 | "ignoreFailures": true 23 | }, 24 | { 25 | "description": "Set Disassembly Flavor to Intel", 26 | "text": "-gdb-set disassembly-flavor intel", 27 | "ignoreFailures": true 28 | } 29 | ] 30 | }, 31 | { 32 | "name": "gdb Launch", 33 | "type": "cppdbg", 34 | "request": "launch", 35 | "program": "gcc ${file}", 36 | "args": [], 37 | "stopAtEntry": false, 38 | "cwd": "${fileDirname}", 39 | "environment": [], 40 | "externalConsole": false, 41 | "MIMode": "gdb", 42 | "setupCommands": [ 43 | { 44 | "description": "Enable pretty-printing for gdb", 45 | "text": "-enable-pretty-printing", 46 | "ignoreFailures": true 47 | } 48 | ] 49 | }, 50 | { 51 | "address": "TCP/IP address of process to be debugged", 52 | "localRoot": "${workspaceFolder}", 53 | "name": "Attach to Remote", 54 | "port": 9229, 55 | "remoteRoot": "Absolute path to the remote directory containing the program", 56 | "request": "attach", 57 | "skipFiles": [ 58 | "/**" 59 | ], 60 | "type": "pwa-node" 61 | }, 62 | ] 63 | } -------------------------------------------------------------------------------- /Algo/BT/GraphColouring.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void printSolution(int V, int colour[]) { 4 | printf("Assigned colours are::"); 5 | for (int i = 0; i < V; i++) 6 | printf(" %d" , colour[i]); 7 | 8 | printf("\n"); 9 | } 10 | 11 | int isSafe2(int V, int graph[][V], int colour[]) { 12 | for (int i = 0; i < V; i++) { 13 | for (int j = i + 1; j < V; j++) { 14 | if (graph[i][j] && colour[j] == colour[i]) 15 | return 0; 16 | } 17 | } 18 | return 1; 19 | } 20 | 21 | int graphColouring2Util(int V, int graph[][V], int m, int colour[], int i) { 22 | if (i == V) { 23 | if (isSafe2(V, graph, colour)) { 24 | printSolution(V, colour); 25 | return 1; 26 | } 27 | return 0; 28 | } 29 | 30 | // Assign each colour from 1 to m 31 | for (int j = 1; j <= m; j++) { 32 | colour[i] = j; 33 | if (graphColouring2Util(V, graph, m, colour, i + 1)) 34 | return 1; 35 | } 36 | return 0; 37 | } 38 | 39 | int graphColouring2(int V, int graph[][V], int m) { 40 | int colour[V]; 41 | if (graphColouring2Util(V, graph, m, colour, 0)) 42 | return 1; 43 | 44 | return 0; 45 | } 46 | 47 | int isSafe(int V, int graph[][V], int colour[], int v, int c) { 48 | for (int i = 0; i < V; i++) { 49 | if (graph[v][i] == 1 && c == colour[i]) 50 | return 0; 51 | } 52 | return 1; 53 | } 54 | 55 | int graphColouringUtil(int V, int graph[][V], int m, int colour[], int i) { 56 | if (i == V) { 57 | printSolution(V, colour); 58 | return 1; 59 | } 60 | 61 | for (int j = 1; j <= m; j++) { 62 | if (isSafe(V, graph, colour, i, j)) { 63 | colour[i] = j; 64 | if (graphColouringUtil(V, graph, m, colour, i + 1)) 65 | return 1; 66 | } 67 | } 68 | return 0; 69 | } 70 | 71 | int graphColouring(int V, int graph[][V], int m) { 72 | int colour[V]; 73 | if (graphColouringUtil(V, graph, m, colour, 0)) 74 | return 1; 75 | 76 | return 0; 77 | } 78 | 79 | int main() { 80 | int graph[][5] = {{0, 1, 0, 0, 1}, 81 | {1, 0, 1, 0, 1}, 82 | {0, 1, 0, 1, 1}, 83 | {0, 0, 1, 0, 1}, 84 | {1, 1, 1, 1, 0}}; 85 | int V = 5; // Number of vertices 86 | int m = 4; // Number of colours 87 | if (!graphColouring2(V, graph, m)) 88 | printf("Solution does not exist"); 89 | 90 | if (!graphColouring(V, graph, m)) 91 | printf("Solution does not exist"); 92 | 93 | return 0; 94 | } 95 | 96 | /* 97 | Assigned colours are:: 1 2 1 2 3 98 | Assigned colours are:: 1 2 1 2 3 99 | */ -------------------------------------------------------------------------------- /Algo/DP/MinCostBinaryTree.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | int INFINITY = 99999; 5 | 6 | int max(int a, int b) { 7 | return (a > b)? a : b; 8 | } 9 | 10 | int min(int a, int b) { 11 | return (a < b)? a : b; 12 | } 13 | 14 | int maxVal(int n, int maxArr[][n], int i, int j) { 15 | if (maxArr[i][j] != 0) 16 | return maxArr[i][j]; 17 | 18 | for (int k = i;k < j;k++) 19 | maxArr[i][j] = max(maxArr[i][j], max(maxVal(n, maxArr, i, k), maxVal(n, maxArr, k + 1, j))); 20 | 21 | return maxArr[i][j]; 22 | } 23 | 24 | int minCostBstTDUtil(int n, int dp[][n], int maxArr[][n], int i, int j) { 25 | if (dp[i][j] != INFINITY) 26 | return dp[i][j]; 27 | 28 | for (int k = i;k < j;k++) { 29 | dp[i][j] = min(dp[i][j], minCostBstTDUtil(n, dp, maxArr, i, k) + 30 | minCostBstTDUtil(n, dp, maxArr, k + 1, j) + 31 | maxVal(n, maxArr, i, k) * maxVal(n, maxArr, k + 1,j)); 32 | } 33 | return dp[i][j]; 34 | } 35 | 36 | int minCostBstTD(int arr[], int n) { 37 | int dp[n][n]; 38 | int maxArr[n][n]; 39 | 40 | for(int i=0;i 3 | 4 | int andEx(int a, int b) { 5 | return a & b; 6 | } 7 | 8 | int orEx(int a, int b) { 9 | return a | b; 10 | } 11 | 12 | int xorEx(int a, int b) { 13 | return a ^ b; 14 | } 15 | 16 | int leftShiftEx(int a) // multiply by 2 17 | { 18 | return a << 1; 19 | } 20 | 21 | int rightShiftEx(int a) // divide by 2 22 | { 23 | return a >> 1; 24 | } 25 | 26 | int bitReversalEx(int a) { 27 | return ~a; 28 | } 29 | 30 | int twoComplementEx(int a) { 31 | return -a; 32 | } 33 | 34 | int kthBitCheck(int a, int k) { 35 | return (a & 1 << (k - 1)) > 0; 36 | } 37 | 38 | int kthBitSet(int a, int k) { 39 | return (a | 1 << (k - 1)); 40 | } 41 | 42 | int kthBitReset(int a, int k) { 43 | return (a & ~(1 << (k - 1))); 44 | } 45 | 46 | int kthBitToggle(int a, int k) { 47 | return (a ^ (1 << (k - 1))); 48 | } 49 | 50 | int rightMostBit(int a) { 51 | return a & -a; 52 | } 53 | 54 | int resetRightMostBit(int a) { 55 | return a & (a - 1); 56 | } 57 | 58 | int isPowerOf2(int a) { 59 | if ((a & (a - 1)) == 0) { 60 | return 1; 61 | } else { 62 | return 0; 63 | } 64 | } 65 | 66 | int countBits(int a) { 67 | int count = 0; 68 | while (a > 0) { 69 | count += 1; 70 | a = a & (a - 1); // reset least significant bit. 71 | } 72 | return count; 73 | } 74 | 75 | int main() { 76 | int a = 4; 77 | int b = 8; 78 | printf("%d\n", andEx(a, b)); 79 | printf("%d\n", orEx(a, b)); 80 | printf("%d\n", xorEx(a, b)); 81 | printf("%d\n", leftShiftEx(a)); // multiply by 2 82 | printf("%d\n", rightShiftEx(a)); // divide by 2 83 | printf("%d\n", bitReversalEx(a)); 84 | printf("%d\n", twoComplementEx(a)); 85 | printf("%d\n", kthBitCheck(a, 3)); 86 | printf("%d\n", kthBitSet(a, 2)); 87 | printf("%d\n", kthBitReset(a, 3)); 88 | printf("%d\n", kthBitToggle(a, 3)); 89 | printf("%d\n", rightMostBit(a)); 90 | printf("%d\n", resetRightMostBit(a)); 91 | printf("%d\n", isPowerOf2(a)); 92 | 93 | for (int i = 0;i < 10;i++) { 94 | printf("%d bit count : %d\n", i, countBits(i)); 95 | } 96 | return 0; 97 | } 98 | 99 | /* 100 | 0 101 | 12 102 | 12 103 | 8 104 | 2 105 | -5 106 | -4 107 | 1 108 | 6 109 | 0 110 | 0 111 | 4 112 | 0 113 | 1 114 | 0 bit count : 0 115 | 1 bit count : 1 116 | 2 bit count : 1 117 | 3 bit count : 2 118 | 4 bit count : 1 119 | 5 bit count : 2 120 | 6 bit count : 2 121 | 7 bit count : 3 122 | 8 bit count : 1 123 | 9 bit count : 2 124 | */ -------------------------------------------------------------------------------- /Tree/BinaryIndexTree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct BinaryIndexTree { 6 | int* BIT; 7 | int size; 8 | }BinaryIndexTree; 9 | 10 | void update(BinaryIndexTree* tree, int index, int val) { 11 | // Index in bit is 1 more than the input array. 12 | index = index + 1; 13 | 14 | // Traverse to ancestors of nodes. 15 | while (index <= tree->size) { 16 | // Add val to current node of Binary Index Tree. 17 | tree->BIT[index] += val; 18 | 19 | // Next element which need to store val. 20 | index += index & (-index); 21 | } 22 | } 23 | 24 | BinaryIndexTree* createBinaryIndexTree(int arr[], int n) { 25 | BinaryIndexTree* tree = (BinaryIndexTree*)malloc(sizeof(BinaryIndexTree)); 26 | tree->size = n; 27 | tree->BIT = (int*)malloc((n+1)*sizeof(int)); 28 | for (int i = 0; i < tree->size; i++) // Populating bit. 29 | { 30 | update(tree, i, arr[i]); 31 | } 32 | return tree; 33 | } 34 | 35 | void set(BinaryIndexTree* tree, int arr[], int index, int val) { 36 | int diff = val - arr[index]; 37 | arr[index] = val; 38 | 39 | // Difference is propagated. 40 | update(tree, index, diff); 41 | } 42 | 43 | // Prefix sum in the range 0 to index. 44 | int prefixSum(BinaryIndexTree* tree, int index) { 45 | int sum = 0; 46 | index = index + 1; 47 | 48 | // Traverse ancestors of Binary Index Tree nodes. 49 | while (index > 0) { 50 | // Add current element to sum. 51 | sum += tree->BIT[index]; 52 | 53 | // Parent index calculation. 54 | index -= index & (-index); 55 | } 56 | return sum; 57 | } 58 | 59 | // Range sum in the range start to end. 60 | int rangeSum(BinaryIndexTree* tree, int start, int end) { 61 | // Check for error conditions. 62 | if (start > end || start < 0 || end > tree->size - 1) { 63 | printf("Invalid Input.\n"); 64 | return -1; 65 | } 66 | 67 | return prefixSum(tree, end) - prefixSum(tree, start - 1); 68 | } 69 | 70 | int main() { 71 | int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 72 | BinaryIndexTree *tree = createBinaryIndexTree(arr, 10); 73 | printf("Sum of elements in range(0, 5): %d\n", prefixSum(tree, 5)); 74 | printf("Sum of elements in range(2, 5): %d\n", rangeSum(tree, 2, 5)); 75 | // Set fourth element to 10. 76 | set(tree, arr, 3, 10); 77 | 78 | // Find sum after the value is updated 79 | printf("Sum of elements in range(0, 5): %d\n", prefixSum(tree, 5)); 80 | //delete tree; 81 | } 82 | 83 | /* 84 | Sum of elements in range(0, 5): 21 85 | Sum of elements in range(2, 5): 18 86 | Sum of elements in range(0, 5): 27 87 | */ -------------------------------------------------------------------------------- /Algo/DP/ALS.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int min(int a, int b) { 5 | return (a < b)? a : b; 6 | } 7 | 8 | int fastestWayBU2(int n, int a[][n], int t[][n], int e[], int x[]) { 9 | int f1[n], f2[n]; 10 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | typedef struct Node { 6 | char c; 7 | int freq; 8 | struct Node *left; 9 | struct Node *right; 10 | } Node; 11 | 12 | typedef struct HuffmanTree { 13 | Node *root; 14 | }HuffmanTree; 15 | 16 | typedef struct Heap { 17 | int capacity; 18 | int size; 19 | Node**array; 20 | int(* compare)(Node* , Node*); 21 | } Heap; 22 | 23 | void proclateDown(Node* arr[], int position, int size, int(* compare)(Node* , Node*)) { 24 | int lChild = 2 * position + 1; 25 | int rChild = lChild + 1; 26 | int small = -1; 27 | 28 | if (lChild < size) 29 | small = lChild; 30 | 31 | if (rChild < size && compare(arr[lChild], arr[rChild])) 32 | small = rChild; 33 | 34 | if (small != -1 && compare(arr[position], arr[small])) { 35 | Node* temp = arr[position]; 36 | arr[position] = arr[small]; 37 | arr[small] = temp; 38 | proclateDown(arr, small, size, compare); 39 | } 40 | } 41 | 42 | void proclateUp(Node* arr[], int position, int(* compare)(Node* , Node*)) { 43 | int parent = (position - 1) / 2; 44 | if (parent >= 0) { 45 | if (compare(arr[parent], arr[position])) { 46 | Node* temp = arr[position]; 47 | arr[position] = arr[parent]; 48 | arr[parent] = temp; 49 | 50 | proclateUp(arr, parent, compare); 51 | } 52 | } 53 | } 54 | 55 | void heapify(Node* arr[], int size, int(* compare)(Node* , Node*)) { 56 | for (int i = size/2; i >= 0; i--) 57 | proclateDown(arr, i, size, compare); 58 | } 59 | 60 | Node* heapRemove(Heap *hp) { 61 | Node* value = hp->array[0]; 62 | hp->array[0] = hp->array[hp->size - 1]; 63 | hp->size--; 64 | proclateDown(hp->array, 0, hp->size, hp->compare); 65 | return value; 66 | } 67 | 68 | void heapAdd(Heap *hp, Node* value) { 69 | if (hp->size == hp->capacity) 70 | return; 71 | hp->size++; 72 | hp->array[hp->size - 1] = value; 73 | proclateUp(hp->array, hp->size - 1, hp->compare); 74 | } 75 | 76 | Heap* createHeap2(Node* arr[], int size, int(* compare)(Node* , Node*)) { 77 | Heap* hp = (Heap*)malloc(sizeof(Heap)); 78 | hp->size = hp->capacity = size; 79 | hp->array = arr; 80 | hp->compare = compare; 81 | heapify(arr, size, compare); 82 | return hp; 83 | } 84 | 85 | Heap* createHeap(int(* compare)(Node* , Node*)) { 86 | Heap* hp = (Heap*)malloc(sizeof(Heap)); 87 | hp->size = 0; 88 | hp->capacity = 100; 89 | hp->array = (Node **)malloc((hp->capacity) * sizeof(Node)); 90 | hp->compare = compare; 91 | return hp; 92 | } 93 | 94 | int heapSize(Heap *hp) { 95 | return hp->size; 96 | } 97 | -------------------------------------------------------------------------------- /HashTable/HashSC.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TABLE_SIZE 517 5 | #define TABLE_BITS 9 6 | 7 | int Hash(int key, int tableSize) { //division method 8 | return key % tableSize; 9 | } 10 | 11 | typedef struct HTNode { 12 | int value; 13 | struct HTNode* next; 14 | } HTNode; 15 | 16 | HTNode* createHTNode(int value, HTNode* next) { 17 | HTNode* node = (HTNode*)malloc(sizeof(HTNode)); 18 | node->value = value; 19 | node->next = next; 20 | return node; 21 | } 22 | 23 | typedef struct HashTable { 24 | int tableSize; 25 | HTNode** listArray;//double pointer 26 | } HashTable; 27 | 28 | HashTable* createHashTable(int size) { 29 | HashTable* hTable = (HashTable*)malloc(sizeof(HashTable)); 30 | hTable->tableSize = size; 31 | hTable->listArray = (HTNode**)malloc(hTable->tableSize * sizeof(HTNode*)); 32 | 33 | for (int i = 0; itableSize; i++) 34 | hTable->listArray[i] = NULL; 35 | 36 | return hTable; 37 | } 38 | 39 | void HashPrint(HashTable* hTable) { 40 | HTNode* head; 41 | for (int i = 0; itableSize; i++) { 42 | head = hTable->listArray[i]; 43 | while (head) { 44 | printf("%d ", head->value); 45 | head = head->next; 46 | } 47 | } 48 | printf("\n"); 49 | } 50 | 51 | int HashFind(HashTable* hTable, int value) { 52 | HTNode* head; 53 | int index = Hash(value, hTable->tableSize); 54 | head = hTable->listArray[index]; 55 | while (head) { 56 | if(head->value == value) 57 | return 1; 58 | head = head->next; 59 | } 60 | return 0; 61 | } 62 | 63 | 64 | void HashAdd(HashTable* hTable, int value) { 65 | int index = Hash(value, hTable->tableSize); 66 | hTable->listArray[index] = createHTNode(value, hTable->listArray[index]); 67 | } 68 | 69 | int HashRemove(HashTable* hTable, int value) { 70 | int index = Hash(value, hTable->tableSize); 71 | HTNode*currNode = hTable->listArray[index]; 72 | 73 | if (currNode && currNode->value == value) { 74 | hTable->listArray[index] = currNode->next; 75 | free(currNode); 76 | return 1; 77 | } 78 | 79 | HTNode* nextNode; 80 | while (currNode) { 81 | nextNode = currNode->next; 82 | if (nextNode && nextNode->value == value) { 83 | currNode->next = nextNode->next; 84 | free(nextNode); 85 | return 1; 86 | } 87 | currNode = nextNode; 88 | } 89 | return 0; 90 | } 91 | 92 | 93 | int main() { 94 | HashTable* ht = createHashTable(100); 95 | HashAdd(ht, 1); 96 | HashAdd(ht, 2); 97 | HashAdd(ht, 3); 98 | HashPrint(ht); 99 | printf("Find 2 : %d\n", HashFind(ht, 2)); 100 | HashRemove(ht, 2); 101 | printf("Find 2 : %d\n", HashFind(ht, 18)); 102 | HashPrint(ht); 103 | return 0; 104 | } 105 | 106 | /* 107 | 1 2 3 108 | Find 2 : 1 109 | Find 2 : 0 110 | 1 3 111 | */ -------------------------------------------------------------------------------- /LinkedList/Poly.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct Node { 5 | int coeff; 6 | int pow; 7 | struct Node *next; 8 | } Node; 9 | 10 | Node* createNode(int c, int p) { 11 | Node *node = (Node*)malloc(sizeof(Node)); 12 | node->coeff = c; 13 | node->pow = p; 14 | node->next = NULL; 15 | return node; 16 | } 17 | 18 | typedef struct Polynomial { 19 | Node *head; 20 | } Polynomial; 21 | 22 | Polynomial* createPolynomial() { 23 | Polynomial* list = (Polynomial*)malloc(sizeof(Polynomial)); 24 | list->head = NULL; 25 | return list; 26 | } 27 | 28 | Polynomial* add(Polynomial* poly1, Polynomial* poly2) { 29 | Polynomial* poly = createPolynomial(); 30 | 31 | Node* tail=NULL; 32 | Node* temp=NULL; 33 | Node* p1=poly1->head; 34 | Node* p2=poly2->head; 35 | 36 | while (p1 != NULL || p2 != NULL) { 37 | if (p1 == NULL || (p2 != NULL && p1->pow < p2->pow)) { 38 | temp = createNode(p2->coeff, p2->pow); 39 | p2 = p2->next; 40 | } else if (p2 == NULL || p1->pow > p2->pow) { 41 | temp = createNode(p1->coeff, p1->pow); 42 | p1 = p1->next; 43 | } else if (p1->pow == p2->pow) { 44 | temp = createNode(p1->coeff + p2->coeff, p1->pow); 45 | p1 = p1->next; 46 | p2 = p2->next; 47 | } 48 | 49 | if(poly->head == NULL) 50 | poly->head = tail = temp; 51 | else { 52 | tail->next = temp; 53 | tail=tail->next; 54 | } 55 | } 56 | return poly; 57 | } 58 | 59 | Polynomial* create(int coeffs[], int pows[], int size) { 60 | Polynomial* poly = createPolynomial(); 61 | Node *tail=NULL, *temp=NULL; 62 | for (int i=0; i < size; i++) { 63 | temp = createNode(coeffs[i], pows[i]); 64 | if(poly->head == NULL) 65 | poly->head = tail = temp; 66 | else { 67 | tail->next = temp; 68 | tail=tail->next; 69 | } 70 | } 71 | return poly; 72 | } 73 | 74 | void print(Polynomial* poly) { 75 | Node* head = poly->head; 76 | while (head != NULL) { 77 | printf("%d", head->coeff); 78 | if(head->pow != 0) 79 | printf("x^%d", head->pow); 80 | 81 | if (head->next != NULL) 82 | printf(" + "); 83 | head = head->next; 84 | } 85 | } 86 | 87 | int main() { 88 | int c1[] = { 6, 5, 4 }; 89 | int p1[] = { 2, 1, 0 }; 90 | int s1 = 3; 91 | Polynomial* first = create(c1, p1, s1); 92 | 93 | int c2[] = { 3, 2, 1 }; 94 | int p2[] = { 3, 1, 0 }; 95 | int s2 = 3; 96 | Polynomial* second = create(c2, p2, s2); 97 | 98 | Polynomial* sum = add(first, second); 99 | print(sum); 100 | return 0; 101 | } 102 | 103 | /* 104 | 3x^3 + 6x^2 + 7x^1 + 5 105 | */ -------------------------------------------------------------------------------- /String/Trie.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct TrieNode { 6 | int isLastChar; 7 | struct TrieNode *child[26]; 8 | } TrieNode; 9 | 10 | TrieNode *createNode() { 11 | TrieNode *node = (TrieNode *)malloc(sizeof(TrieNode)); 12 | for (int i = 0; i < 26; i++) 13 | node->child[i] = NULL; 14 | node->isLastChar = 0; 15 | return node; 16 | } 17 | 18 | typedef struct Trie { 19 | TrieNode *root; 20 | } Trie; 21 | 22 | Trie *createTrie() { 23 | Trie *trie = (Trie*)malloc(sizeof(Trie)); 24 | trie->root = createNode(); // first node with dummy value. 25 | return trie; 26 | } 27 | 28 | TrieNode* addTrieUtil(TrieNode *curr, char *str, int start) { 29 | if(curr == NULL) 30 | curr = createNode(); 31 | 32 | if(strlen(str) == start) 33 | curr->isLastChar = 1; 34 | else{ 35 | int index = (str[start] > 'a' && str[start] < 'z') ? str[start] - 'a' : str[start] - 'A'; 36 | curr->child[index] = addTrieUtil(curr->child[index], str, start + 1); 37 | } 38 | return curr; 39 | } 40 | 41 | void addTrie(Trie *trie, char *str) { 42 | if (str == NULL || *str == '\0') 43 | return; 44 | addTrieUtil(trie->root, str, 0); 45 | } 46 | 47 | void removeTrieUtil(TrieNode *curr, char *str, int start) { 48 | if(curr == NULL) 49 | return; 50 | 51 | if(strlen(str) == start) { 52 | curr->isLastChar = 0; 53 | return; 54 | } 55 | int index = (str[start] > 'a' && str[start] < 'z') ? str[start] - 'a' : str[start] - 'A'; 56 | removeTrieUtil(curr->child[index], str, start + 1); 57 | } 58 | 59 | void removeTrie(Trie *trie, char *str) { 60 | if (str == NULL || *str == '\0') 61 | return; 62 | removeTrieUtil(trie->root, str, 0); 63 | } 64 | 65 | int findTrieUtil(TrieNode *curr, char *str, int start) { 66 | if (curr == NULL) 67 | return 0; 68 | 69 | if(strlen(str) == start) 70 | return curr->isLastChar; 71 | 72 | int index = (str[start] > 'a' && str[start] < 'z') ? str[start] - 'a' : str[start] - 'A'; 73 | return findTrieUtil(curr->child[index], str, start + 1); 74 | } 75 | 76 | int findTrie(Trie *trie, char *str) { 77 | if (str == NULL || *str == '\0') 78 | return 0; 79 | return findTrieUtil(trie->root, str, 0); 80 | } 81 | 82 | int main() { 83 | Trie *trie = createTrie(); 84 | addTrie(trie, "banana"); 85 | addTrie(trie, "apple"); 86 | addTrie(trie, "Apple"); 87 | addTrie(trie, "APPLE"); 88 | addTrie(trie, "mango"); 89 | 90 | printf("find apple : %d\n", findTrie(trie, "apple")); 91 | printf("find banana : %d\n", findTrie(trie, "banana")); 92 | printf("find grapes : %d\n", findTrie(trie, "grapes")); 93 | printf("find mango : %d\n", findTrie(trie, "mango")); 94 | } 95 | 96 | /* 97 | find apple : 1 98 | find banana : 1 99 | find grapes : 0 100 | find mango : 1 101 | */ -------------------------------------------------------------------------------- /Graph/GraphAM.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct graph { 5 | int count; 6 | int **adj; 7 | } Graph; 8 | 9 | typedef struct graphEdge { 10 | int src; 11 | int dest; 12 | int cost; 13 | } GraphEdge; 14 | 15 | GraphEdge* createGraphEdge(int src, int dst, int cost) { 16 | GraphEdge *edge = (GraphEdge *)malloc(sizeof(GraphEdge)); 17 | edge->src = src; 18 | edge->dest = dst; 19 | edge->cost = cost; 20 | return edge; 21 | } 22 | 23 | int greater(GraphEdge* a, GraphEdge* b) { 24 | return a->cost > b->cost; 25 | } 26 | 27 | int max(int first, int second) { 28 | return (first > second) ? first : second; 29 | } 30 | 31 | typedef struct Heap { 32 | int capacity; 33 | int size; 34 | GraphEdge** array; 35 | int(* compare)(GraphEdge* , GraphEdge*); 36 | } Heap; 37 | 38 | Heap* createHeap(int(* compare)(GraphEdge* , GraphEdge*)) { 39 | Heap* hp = (Heap*)malloc(sizeof(Heap)); 40 | hp->size = 0; 41 | hp->capacity = 100; 42 | hp->array = (GraphEdge **)malloc((hp->capacity) * sizeof(GraphEdge)); 43 | hp->compare = compare; 44 | return hp; 45 | } 46 | 47 | void proclateDown(GraphEdge* arr[], int position, int size, int(* compare)(GraphEdge* , GraphEdge*)) { 48 | int lChild = 2 * position + 1; 49 | int rChild = lChild + 1; 50 | int small = -1; 51 | 52 | if (lChild < size) 53 | small = lChild; 54 | 55 | if (rChild < size && compare(arr[lChild], arr[rChild])) 56 | small = rChild; 57 | 58 | if (small != -1 && compare(arr[position], arr[small])) { 59 | GraphEdge* temp = arr[position]; 60 | arr[position] = arr[small]; 61 | arr[small] = temp; 62 | proclateDown(arr, small, size, compare); 63 | } 64 | } 65 | 66 | void proclateUp(GraphEdge* arr[], int position, int(* compare)(GraphEdge* , GraphEdge*)) { 67 | int parent = (position - 1) / 2; 68 | if (parent >= 0) { 69 | if (compare(arr[parent], arr[position])) { 70 | GraphEdge* temp = arr[position]; 71 | arr[position] = arr[parent]; 72 | arr[parent] = temp; 73 | proclateUp(arr, parent, compare); 74 | } 75 | } 76 | } 77 | 78 | void heapify(GraphEdge* arr[], int size, int(* compare)(GraphEdge* , GraphEdge*)) { 79 | for (int i = size/2; i >= 0; i--) 80 | proclateDown(arr, i, size, compare); 81 | } 82 | 83 | GraphEdge* heapRemove(Heap *hp) { 84 | GraphEdge* value = hp->array[0]; 85 | hp->array[0] = hp->array[hp->size - 1]; 86 | hp->size--; 87 | proclateDown(hp->array, 0, hp->size, hp->compare); 88 | return value; 89 | } 90 | 91 | void heapAdd(Heap *hp, GraphEdge* value) { 92 | if (hp->size == hp->capacity) 93 | return; 94 | hp->size++; 95 | hp->array[hp->size - 1] = value; 96 | proclateUp(hp->array, hp->size - 1, hp->compare); 97 | } 98 | 99 | int heapSize(Heap *hp) { 100 | return hp->size; 101 | } 102 | -------------------------------------------------------------------------------- /Graph/Graph.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "../Stack/Stack.c" 5 | #include "../Queue/Queue.c" 6 | 7 | typedef struct graphEdge { 8 | int src; 9 | int dest; 10 | int cost; 11 | struct graphEdge *next; 12 | } GraphEdge; 13 | 14 | typedef struct graph { 15 | int count; 16 | GraphEdge **adj; 17 | } Graph; 18 | 19 | int greater(GraphEdge* a, GraphEdge* b) { 20 | return a->cost > b->cost; 21 | } 22 | 23 | int max(int first, int second) { 24 | return (first > second) ? first : second; 25 | } 26 | 27 | #define CAPACITY 100 28 | 29 | #ifndef ERROR_VALUE 30 | #define ERROR_VALUE -99999 31 | #endif 32 | 33 | #define INFINITE 9999999 34 | 35 | typedef struct Heap { 36 | int capacity; 37 | int size; 38 | GraphEdge**array; 39 | int(* compare)(GraphEdge* , GraphEdge*); 40 | } Heap; 41 | 42 | Heap* createHeap(int(* compare)(GraphEdge* , GraphEdge*)) { 43 | Heap* hp = (Heap*)malloc(sizeof(Heap)); 44 | hp->size = 0; 45 | hp->capacity = 100; 46 | hp->array = (GraphEdge **)malloc((hp->capacity) * sizeof(GraphEdge)); 47 | hp->compare = compare; 48 | return hp; 49 | } 50 | 51 | void proclateDown(GraphEdge* arr[], int position, int size, int(* compare)(GraphEdge* , GraphEdge*)) { 52 | int lChild = 2 * position + 1; 53 | int rChild = lChild + 1; 54 | int small = -1; 55 | 56 | if (lChild < size) 57 | small = lChild; 58 | 59 | if (rChild < size && compare(arr[lChild], arr[rChild])) 60 | small = rChild; 61 | 62 | if (small != -1 && compare(arr[position], arr[small])) { 63 | GraphEdge* temp = arr[position]; 64 | arr[position] = arr[small]; 65 | arr[small] = temp; 66 | proclateDown(arr, small, size, compare); 67 | } 68 | } 69 | 70 | void proclateUp(GraphEdge* arr[], int position, int(* compare)(GraphEdge* , GraphEdge*)) { 71 | int parent = (position - 1) / 2; 72 | if (parent >= 0) { 73 | if (compare(arr[parent], arr[position])) { 74 | GraphEdge* temp = arr[position]; 75 | arr[position] = arr[parent]; 76 | arr[parent] = temp; 77 | 78 | proclateUp(arr, parent, compare); 79 | } 80 | } 81 | } 82 | 83 | void heapify(GraphEdge* arr[], int size, int(* compare)(GraphEdge* , GraphEdge*)) { 84 | for (int i = size/2; i >= 0; i--) 85 | proclateDown(arr, i, size, compare); 86 | } 87 | 88 | GraphEdge* heapRemove(Heap *hp) { 89 | GraphEdge* value = hp->array[0]; 90 | hp->array[0] = hp->array[hp->size - 1]; 91 | hp->size--; 92 | proclateDown(hp->array, 0, hp->size, hp->compare); 93 | return value; 94 | } 95 | 96 | void heapAdd(Heap *hp, GraphEdge* value) { 97 | if (hp->size == hp->capacity) 98 | return; 99 | hp->size++; 100 | hp->array[hp->size - 1] = value; 101 | proclateUp(hp->array, hp->size - 1, hp->compare); 102 | } 103 | 104 | int heapSize(Heap *hp) { 105 | return hp->size; 106 | } -------------------------------------------------------------------------------- /Heap/fibonacci.py: -------------------------------------------------------------------------------- 1 | function MakeFibonacciHeap(): 2 | H = CreateFibonnacciHeap() 3 | H.n = 0 4 | H.min = Null 5 | return H 6 | 7 | function FibonacciHeapMinimum(H): 8 | return H.min 9 | 10 | function FibonacciHeapLink(H, y, x) 11 | remove y from the root list of H 12 | make y a child of x 13 | x.degree = x.degree + 1 14 | y.mark = FALSE 15 | 16 | function Consolidate(H) 17 | for i=0 to Len(H) 18 | A[i] = Null 19 | 20 | for each root w in the root list of H 21 | x = w 22 | d = x.degree 23 | while A[d] != Null 24 | y = A[d] 25 | if x.key > y.key 26 | swap x & y 27 | FibonacciHeapLink(H, y, x) 28 | A[d] = Null 29 | d = d+1 30 | A[d] = x 31 | 32 | if H.min = Null or H.min.key > x.key: 33 | H.min = x 34 | 35 | function FibonacciHeapUnion(H1,H2) 36 | Concatinate the root list of H2 into H1 37 | 38 | if (H1.min = Null) or (H2.min != Null and H2.min.key < H1.min.key) 39 | H1.min = H2.min 40 | H1.n = H1.n + H2.n 41 | free H2 42 | return H1 43 | 44 | 45 | function FibonacciHeapInsert(H, x) 46 | x.degree = 0 47 | x.parent = Null 48 | x.child = Null 49 | x.left = x 50 | x.right = x 51 | mark = FALSE 52 | 53 | concatenate the root x into root list of H 54 | if H.min = Null or x.key < H.min.key 55 | H.min = x 56 | H.n = H.n + 1 57 | 58 | funciton FibonacciHeapExtractMin(H) 59 | z = H.min 60 | if z != Null 61 | for each child x of z 62 | x.parent = Null 63 | add x to the root list of H 64 | remove z from the root list of H 65 | 66 | if z = z.right 67 | H.min = Null 68 | else 69 | H.min = z.right 70 | Consolidate(H) 71 | H.n = H.n - 1 72 | return z 73 | 74 | function FibonacciHeapDecreaseKey(H, x, k) 75 | if k > x.key 76 | error "new key is greater than current key" 77 | x.key = k 78 | y = x.parent 79 | if y != Null and x.key < y.key 80 | Cut(H, x, y) 81 | CascadingCut(H,y) 82 | if x.key < H.min.key 83 | H.min = x 84 | 85 | function Cut(H,x,y) 86 | Remove x from the child list of y, decrementing y.degree 87 | Add x to the root list of H 88 | x.parent = Null 89 | x.mark = FALSE 90 | 91 | function CascadingCut(H,y) 92 | z = y.parent 93 | if z != Null 94 | if y.mark = FALSE 95 | y.mark = TRUE 96 | else 97 | Cut(H, y, z) 98 | CascadingCut(H, z) 99 | 100 | function FibonacciHeapDelete(H,x) 101 | FibonacciHeapDecrease-Key(H,x,-infinity) 102 | FibonacciHeapExtractMin(H) 103 | 104 | 105 | 106 | 107 | 108 | It is the most important operation on a fibonacci heap. In this operation, the node with minimum value is removed from the heap and the tree is re-adjusted. 109 | 110 | The following steps are followed: 111 | 112 | -------------------------------------------------------------------------------- /String/TST.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct TSTNode { 6 | char data; 7 | unsigned isLastChar : 1; 8 | struct TSTNode *left, *equal, *right; 9 | } TSTNode; 10 | 11 | TSTNode* createNode(char data) { 12 | TSTNode *node = (TSTNode *)malloc(sizeof(TSTNode)); 13 | node->data = data; 14 | node->isLastChar = 0; 15 | node->left = node->equal = node->right = NULL; 16 | return node; 17 | } 18 | 19 | typedef struct TST { 20 | TSTNode *root; 21 | } TST; 22 | 23 | TST* createTST() { 24 | TST* tst = (TST*)malloc(sizeof(TST)); 25 | tst->root = NULL; 26 | return tst; 27 | } 28 | 29 | TSTNode* addTSTUtil(TSTNode *node, char *word) { 30 | if (!node) 31 | node = createNode(*word); 32 | 33 | if ((*word) < node->data) 34 | node->left = addTSTUtil(node->left, word); 35 | else if ((*word) > node->data) 36 | node->right = addTSTUtil(node->right, word); 37 | else if (*(word + 1)) // equal but not last char. 38 | node->equal = addTSTUtil(node->equal, word + 1); 39 | else // equal and last char. 40 | node->isLastChar = 1; 41 | 42 | return node; 43 | } 44 | 45 | void addTST(TST *tst, char *word) { 46 | tst->root = addTSTUtil(tst->root, word); 47 | } 48 | 49 | int findTSTUtil(TSTNode *node, char *word) { 50 | if (!node) 51 | return 0; 52 | 53 | if (*word < node->data) 54 | return findTSTUtil(node->left, word); 55 | else if (*word > node->data) 56 | return findTSTUtil(node->right, word); 57 | else if (*(word + 1)) // equal but not last character. 58 | return findTSTUtil(node->equal, word + 1); 59 | else // equal and last character. 60 | return node->isLastChar; 61 | } 62 | 63 | int findTST(TST *tst, char *word) { 64 | return findTSTUtil(tst->root, word); 65 | } 66 | 67 | int removeTSTUtil(TSTNode *node, char *word) { 68 | if (!node) 69 | return 0; 70 | 71 | if (*word < (node)->data) 72 | return removeTSTUtil(node->left, word); 73 | else if (*word > node->data) 74 | return removeTSTUtil(node->right, word); 75 | else if (*(word + 1)) // equal but not last character. 76 | return removeTSTUtil(node->equal, word + 1); 77 | else if(node->isLastChar)// equal and last character. 78 | { 79 | node->isLastChar = 0; 80 | return 1; 81 | } 82 | return 0; 83 | 84 | } 85 | 86 | int removeTST(TST *tst, char *word) { 87 | return removeTSTUtil(tst->root, word); 88 | } 89 | 90 | int main() { 91 | TST *tst = createTST(); 92 | addTST(tst, "banana"); 93 | addTST(tst, "apple"); 94 | addTST(tst, "mango"); 95 | 96 | printf("find apple : %d\n", findTST(tst, "apple")); 97 | printf("find banana : %d\n", findTST(tst, "banana")); 98 | printf("find grapes : %d\n", findTST(tst, "grapes")); 99 | printf("find mango : %d\n", findTST(tst, "mango")); 100 | 101 | return 0; 102 | } 103 | 104 | /* 105 | find apple : 1 106 | find banana : 1 107 | find grapes : 0 108 | find mango : 1 109 | */ -------------------------------------------------------------------------------- /HashTable/Set.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TABLE_SIZE 517 5 | #define TABLE_BITS 9 6 | 7 | typedef struct SetNode { 8 | int key; 9 | struct SetNode *next; 10 | } SetNode; 11 | 12 | SetNode* createSetNode(int key, SetNode* next) { 13 | SetNode* node = (SetNode*)malloc(sizeof(SetNode)); 14 | node->key = key; 15 | node->next = next; 16 | return node; 17 | } 18 | 19 | typedef struct Set { 20 | int tableSize; 21 | SetNode **listArray; //double pointer 22 | } Set; 23 | 24 | Set * createSet() { 25 | Set *hTable = (Set*) malloc(sizeof(Set)); 26 | hTable->tableSize = TABLE_SIZE; 27 | hTable->listArray = (SetNode **)malloc(hTable->tableSize * sizeof(SetNode *)); 28 | for (int i = 0; i < hTable->tableSize; i++) 29 | hTable->listArray[i] = NULL; 30 | return hTable; 31 | } 32 | /* 33 | unsigned int Hash(int key, int tableSize) { //division method 34 | unsigned int hashValue = 0; 35 | hashValue = key; 36 | return hashValue % tableSize; 37 | } 38 | */ 39 | 40 | void SetPrint(Set *hTable) { 41 | printf("[ "); 42 | for (int i = 0; i < hTable->tableSize; i++) { 43 | SetNode *head = hTable->listArray[i]; 44 | while (head) { 45 | printf("%d ", head->key); 46 | head = head->next; 47 | } 48 | } 49 | printf("]\n"); 50 | } 51 | 52 | int SetFind(Set *hTable, int key) { 53 | SetNode *head; 54 | int index = Hash(key, hTable->tableSize); 55 | head = hTable->listArray[index]; 56 | while(head) { 57 | if (head->key == key) 58 | return 1; 59 | head = head->next; 60 | } 61 | return 0; 62 | } 63 | 64 | void SetAdd(Set *hTable, int key) { 65 | int index = Hash(key, hTable->tableSize); 66 | SetNode *head = hTable->listArray[index]; 67 | while(head) { 68 | if (head->key == key) { 69 | return; 70 | } 71 | head = head->next; 72 | } 73 | hTable->listArray[index] = createSetNode(key, hTable->listArray[index]); 74 | } 75 | 76 | int SetRemove(Set *hTable, int key) { 77 | int index = Hash(key, hTable->tableSize); 78 | SetNode *currNode = hTable->listArray[index]; 79 | if(currNode && currNode->key == key) { 80 | hTable->listArray[index] = currNode->next; 81 | free(currNode); 82 | return 1; 83 | } 84 | 85 | SetNode *nextNode; 86 | while (currNode) { 87 | nextNode = currNode->next; 88 | if (nextNode && nextNode->key == key) { 89 | currNode->next = nextNode->next; 90 | free(nextNode); 91 | return 1; 92 | } 93 | currNode = nextNode; 94 | } 95 | return 0; 96 | } 97 | 98 | int mainB() { 99 | Set* st = createSet(); 100 | SetAdd(st, 2); 101 | SetAdd(st, 3); 102 | SetAdd(st, 3); 103 | SetAdd(st, 5); 104 | SetAdd(st, 5); 105 | SetPrint(st); 106 | printf("SetFind 3 : %d\n", SetFind(st, 3)); 107 | 108 | SetRemove(st, 3); 109 | SetPrint(st); 110 | 111 | printf("SetFind 5 : %d\n", SetFind(st, 5)); 112 | printf("SetFind 3 : %d\n", SetFind(st, 3)); 113 | return 0; 114 | } 115 | 116 | /* 117 | [2->1] [3->2] [5->3] 118 | [2->1] [3->1] [5->3] 119 | [2->1] [5->3] 120 | SetFind 5 : 1 121 | SetFind 3 : 0 122 | GetCount 5 : 3 123 | GetCount 3 : 0 124 | */ 125 | -------------------------------------------------------------------------------- /Tree/Tree.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct TreeNode { 6 | int value; 7 | struct TreeNode *lChild; 8 | struct TreeNode *rChild; 9 | } TreeNode; 10 | 11 | typedef struct Tree { 12 | TreeNode* root; 13 | } Tree; 14 | 15 | #define ERROR_VALUE -999 16 | #define MAX_CAPACITY 100 17 | 18 | typedef struct Stack 19 | { 20 | int top; 21 | TreeNode **data; 22 | int capacity; 23 | } Stack; 24 | 25 | Stack* createStack() { 26 | Stack *stk = (Stack*)malloc(sizeof(Stack)); 27 | stk->data = (TreeNode **)malloc(MAX_CAPACITY * sizeof(TreeNode *)); 28 | stk->top = -1; 29 | stk->capacity = MAX_CAPACITY; 30 | return stk; 31 | } 32 | 33 | void stackPush(Stack *stk, TreeNode *value) { 34 | if (stk->top + 1 == stk->capacity) { 35 | printf("Stack is full.\n"); 36 | return; 37 | } 38 | stk->top++; 39 | stk->data[stk->top] = value; 40 | } 41 | 42 | TreeNode* stackPop(Stack *stk) { 43 | if (stk->top == -1) { 44 | printf("stack empty.\n"); 45 | return NULL; 46 | } 47 | 48 | TreeNode* value = stk->data[stk->top]; 49 | stk->top--; 50 | return value; 51 | } 52 | 53 | TreeNode* stackTop(Stack *stk) { 54 | TreeNode* value = stk->data[stk->top]; 55 | return value; 56 | } 57 | 58 | int stackIsEmpty(Stack *stk) { 59 | return (stk->top == -1); 60 | } 61 | 62 | int stackSize(Stack *stk) { 63 | return (stk->top + 1); 64 | } 65 | 66 | void stackPrint(Stack *stk) { 67 | printf("["); 68 | for (int i = stk->top; i >= 0; i--) { 69 | printf("%d ", stk->data[i]->value); 70 | } 71 | printf("]\n"); 72 | } 73 | 74 | typedef struct Queue 75 | { 76 | int front; 77 | int back; 78 | int size; 79 | TreeNode* data[MAX_CAPACITY]; 80 | } Queue; 81 | 82 | Queue* createQueue() { 83 | Queue* que = (Queue*)malloc(sizeof(Queue)); 84 | que->back = 0; 85 | que->front = 0; 86 | que->size = 0; 87 | return que; 88 | } 89 | 90 | void queueAdd(Queue *que, TreeNode * value) { 91 | if (que->size == MAX_CAPACITY) { 92 | printf("Queue is full.\n"); 93 | return; 94 | } 95 | que->size++; 96 | que->data[que->back] = value; 97 | que->back = (que->back + 1) % MAX_CAPACITY; 98 | } 99 | 100 | TreeNode * queueRemove(Queue *que) { 101 | TreeNode* value; 102 | if (que->size == 0) { 103 | printf("Queue is empty.\n"); 104 | return NULL; 105 | } 106 | que->size--; 107 | value = que->data[que->front]; 108 | que->front = (que->front + 1) % MAX_CAPACITY; 109 | return value; 110 | } 111 | 112 | TreeNode * queueFront(Queue *que) { 113 | return que->data[que->front]; 114 | } 115 | 116 | TreeNode * queueBack(Queue *que) { 117 | return que->data[que->back-1]; 118 | } 119 | 120 | TreeNode * queueRemoveBack(Queue *que) { 121 | if (que->size == 0) { 122 | printf("Queue is empty.\n"); 123 | return NULL; 124 | } 125 | que->size--; 126 | TreeNode *value = que->data[que->back - 1]; 127 | que->back = (que->back - 1) % MAX_CAPACITY; 128 | return value; 129 | } 130 | 131 | int queueIsEmpty(Queue *que) { 132 | return que->size == 0; 133 | } 134 | 135 | int queueSize(Queue *que) { 136 | return que->size; 137 | } 138 | 139 | void queuePrint(Queue *que) { 140 | int size = que->size; 141 | printf("[ "); 142 | int index = que->front; 143 | for (int i=0;idata[index]->value); 145 | index = (index + 1) % MAX_CAPACITY; 146 | } 147 | printf("]\n"); 148 | } 149 | -------------------------------------------------------------------------------- /HashTable/HashLP.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define EMPTY_NODE 0 5 | #define FILLED_NODE 1 6 | #define DELETED_NODE 2 7 | 8 | int Hash(int key, int size) { //division method 9 | return key % size; 10 | } 11 | 12 | int CollisionFunction(int i) { 13 | //return i*i; 14 | return i; 15 | } 16 | 17 | typedef struct HashTable { 18 | int size; 19 | int *array; 20 | char *flag; 21 | } HashTable; 22 | 23 | HashTable * createHashTable(int size) { 24 | HashTable *hTable = (HashTable*)malloc(sizeof(HashTable)); 25 | hTable->size = size; 26 | hTable->array = (int *)malloc(hTable->size * sizeof(int)); 27 | hTable->flag = (char *)malloc(hTable->size * sizeof(char)); 28 | for (int i = 0; i < hTable->size; i++) 29 | hTable->flag[i] = EMPTY_NODE; 30 | return hTable; 31 | } 32 | 33 | void HashPrint(HashTable *hTable) { 34 | for (int i = 0; i < hTable->size; i++) { 35 | if (hTable->flag[i] == FILLED_NODE) 36 | printf("%d ", hTable->array[i]); 37 | } 38 | printf("\n"); 39 | } 40 | 41 | 42 | int HashFind(HashTable *hTable, int value) { 43 | int hashValue = Hash(value, hTable->size); 44 | for (int i = 0; i < hTable->size; i++) { 45 | if ((hTable->flag[hashValue] == FILLED_NODE && 46 | hTable->array[hashValue] == value) || 47 | hTable->flag[hashValue] == EMPTY_NODE) { 48 | break; 49 | } 50 | hashValue += CollisionFunction(i); 51 | hashValue = hashValue % hTable->size; 52 | } 53 | 54 | if (hTable->flag[hashValue] == FILLED_NODE && 55 | hTable->array[hashValue] == value) 56 | return 1; 57 | else 58 | return 0; 59 | } 60 | 61 | int HashAdd(HashTable *hTable, int value) { 62 | int hashValue = Hash(value, hTable->size); 63 | int i = 0; 64 | for (i = 0; i < hTable->size; i++) { 65 | if (hTable->flag[hashValue] == EMPTY_NODE || 66 | hTable->flag[hashValue] == DELETED_NODE) { 67 | hTable->array[hashValue] = value; 68 | hTable->flag[hashValue] = FILLED_NODE; 69 | break; 70 | } 71 | hashValue += CollisionFunction(i); 72 | hashValue = hashValue % hTable->size; 73 | } 74 | 75 | if (i != hTable->size) 76 | return 1; 77 | else 78 | return 0; /* Table is full */ 79 | } 80 | 81 | int HashRemove(HashTable *hTable, int value) { 82 | int hashValue = Hash(value, hTable->size); 83 | for (int i = 0; i < hTable->size; i++) { 84 | if (( hTable->flag[hashValue] == FILLED_NODE && 85 | hTable->array[hashValue] == value ) || 86 | hTable->flag[hashValue] == EMPTY_NODE) { 87 | break; 88 | } 89 | hashValue += CollisionFunction(i); 90 | hashValue = hashValue % hTable->size; 91 | } 92 | 93 | if (hTable->flag[hashValue] == FILLED_NODE && 94 | hTable->array[hashValue] == value) { 95 | hTable->flag[hashValue] = DELETED_NODE; 96 | return 1; 97 | } 98 | else 99 | return 0; 100 | } 101 | 102 | int main() { 103 | HashTable* ht = createHashTable(100); 104 | HashAdd(ht, 1); 105 | HashAdd(ht, 2); 106 | HashAdd(ht, 3); 107 | HashPrint(ht); 108 | printf("Find 2 : %d\n", HashFind(ht, 2)); 109 | HashRemove(ht, 2); 110 | printf("Find 2 : %d\n", HashFind(ht, 18)); 111 | HashPrint(ht); 112 | return 0; 113 | } 114 | 115 | /* 116 | 1 2 3 117 | Find 2 : 1 118 | Find 2 : 0 119 | 1 3 120 | */ -------------------------------------------------------------------------------- /Algo/DP/OptimalBST.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int min(int a, int b) { 5 | return (a < b)? a : b; 6 | } 7 | 8 | int sum(int freq[], int i, int j) { 9 | int s = 0; 10 | for (int k = i; k <= j; k++) 11 | s += freq[k]; 12 | 13 | return s; 14 | } 15 | 16 | void sumInit(int sum[], int freq[], int n) { 17 | sum[0] = freq[0]; 18 | for (int i = 1; i < n; i++) 19 | sum[i] = sum[i - 1] + freq[i]; 20 | } 21 | 22 | int sumRange(int sum[], int i, int j) { 23 | if (i == 0) 24 | return sum[j]; 25 | return sum[j] - sum[i - 1]; 26 | } 27 | 28 | int optimalBstUtil(int freq[], int i, int j) { 29 | if (i > j) 30 | return 0; 31 | 32 | if (j == i) // one element in this subarray 33 | return freq[i]; 34 | 35 | int minval = 99999; 36 | for (int r = i; r <= j; r++) 37 | minval = min(minval, optimalBstUtil(freq, i, r - 1) + optimalBstUtil(freq, r + 1, j)); 38 | 39 | return minval + sum(freq, i, j); 40 | } 41 | 42 | int optimalBst(int keys[], int freq[], int n) { 43 | return optimalBstUtil(freq, 0, n - 1); 44 | } 45 | 46 | int optimalBstTDUtil(int freq[], int n, int cost[][n], int i, int j) { 47 | if (i > j) 48 | return 0; 49 | 50 | if (cost[i][j] != 99999) 51 | return cost[i][j]; 52 | 53 | int s = sum(freq, i, j); 54 | for (int r = i; r <= j; r++) { 55 | cost[i][j] = min(cost[i][j], optimalBstTDUtil(freq, n, cost, i, r - 1) + 56 | optimalBstTDUtil(freq, n, cost, r + 1, j) + s); 57 | } 58 | return cost[i][j]; 59 | } 60 | 61 | int optimalBstTD(int keys[], int freq[], int n) { 62 | int cost[n][n]; 63 | for (int i = 0; i < n; i++) 64 | for (int j = 0; j < n; j++) 65 | cost[i][j] = 99999; 66 | 67 | for (int i = 0; i < n; i++) 68 | cost[i][i] = freq[i]; 69 | 70 | return optimalBstTDUtil(freq, n, cost, 0, n - 1); 71 | } 72 | 73 | int optimalBstBU(int keys[], int freq[], int n) { 74 | int cost[n][n]; 75 | for (int i = 0; i < n; i++) 76 | for (int j = 0; j < n; j++) 77 | cost[i][j] = 99999; 78 | 79 | for (int i = 0; i < n; i++) 80 | cost[i][i] = freq[i]; 81 | 82 | int sm = 0; 83 | for (int l = 1; l < n; l++) { // l is length of range. 84 | for (int i = 0, j = i + l; j < n; i++, j++) { 85 | sm = sum(freq, i, j); 86 | for (int r = i; r <= j; r++) { 87 | cost[i][j] = min(cost[i][j], sm + ((r - 1 >= i)? cost[i][r - 1] : 0) + ((r + 1 <= j)? cost[r + 1][j] : 0)); 88 | } 89 | } 90 | } 91 | return cost[0][n - 1]; 92 | } 93 | 94 | int optimalBstBU2(int keys[], int freq[], int n) { 95 | int cost[n][n]; 96 | for (int i = 0; i < n; i++) 97 | for (int j = 0; j < n; j++) 98 | cost[i][j] = 99999; 99 | 100 | for (int i = 0; i < n; i++) 101 | cost[i][i] = freq[i]; 102 | 103 | int sumArr[n]; 104 | sumInit(sumArr, freq, n); 105 | int sm = 0; 106 | for (int l = 1; l < n; l++) { // l is length of range. 107 | for (int i = 0, j = i + l; j < n; i++, j++) { 108 | sm = sumRange(sumArr, i, j); 109 | for (int r = i; r <= j; r++) { 110 | cost[i][j] = min(cost[i][j], sm + ((r - 1 >= i)? cost[i][r - 1] : 0) + ((r + 1 <= j)? cost[r + 1][j] : 0)); 111 | } 112 | } 113 | } 114 | return cost[0][n - 1]; 115 | } 116 | 117 | int main() { 118 | int keys[] = {9, 15, 25}; 119 | int freq[] = {30, 10, 40}; 120 | int size = 3; 121 | printf("OBst cost: %d\n", optimalBst(keys, freq, size)); 122 | printf("OBst cost: %d\n", optimalBstTD(keys, freq, size)); 123 | printf("OBst cost: %d\n", optimalBstBU(keys, freq, size)); 124 | printf("OBst cost: %d\n", optimalBstBU2(keys, freq, size)); 125 | } 126 | 127 | /* 128 | OBst cost:130 129 | OBst cost:130 130 | OBst cost:130 131 | OBst cost:130 132 | */ -------------------------------------------------------------------------------- /String/StringTree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct TreeNode { 6 | char *value; 7 | int count; 8 | struct TreeNode *lChild; 9 | struct TreeNode *rChild; 10 | } TreeNode; 11 | 12 | TreeNode *createTreeNode(char* value, TreeNode *left, TreeNode *right) { 13 | TreeNode *node = (TreeNode*) malloc(sizeof(TreeNode)); 14 | node->value = (char *)malloc((1 + strlen(value)) * sizeof(char)); 15 | strcpy(node->value, value); 16 | node->count = 1; 17 | node->lChild = left; 18 | node->rChild = right; 19 | return node; 20 | } 21 | 22 | typedef struct StringTree { 23 | TreeNode *root; 24 | } StringTree; 25 | 26 | StringTree *createTree() { 27 | StringTree *tree = (StringTree*)malloc(sizeof(StringTree)); 28 | tree->root = NULL; 29 | return tree; 30 | } 31 | 32 | void printTreeUtil(TreeNode *root) /* pre order */ 33 | { 34 | if (root) { 35 | printf("(value: %s, count: %d) ", root->value, root->count); 36 | printTreeUtil(root->lChild); 37 | printTreeUtil(root->rChild); 38 | } 39 | } 40 | 41 | void printTree(StringTree* tree) { 42 | printTreeUtil(tree->root); 43 | printf("\n"); 44 | } 45 | 46 | TreeNode *addTreeUtil(TreeNode *root, char *value) { 47 | if (root == NULL) { 48 | return createTreeNode(value, NULL, NULL); 49 | } 50 | 51 | int compare = strcmp(root->value, value); 52 | if (compare == 0) { 53 | root->count++; 54 | } else if (compare > 0) { 55 | root->lChild = addTreeUtil(root->lChild, value); 56 | } else { 57 | root->rChild = addTreeUtil(root->rChild, value); 58 | } 59 | return root; 60 | } 61 | 62 | void addTree(StringTree* tree, char *value) { 63 | tree->root = addTreeUtil(tree->root, value); 64 | } 65 | 66 | TreeNode *freeTreeUtil(TreeNode *root) { 67 | if (root) { 68 | freeTreeUtil(root->lChild); 69 | freeTreeUtil(root->rChild); 70 | free(root->value); 71 | free(root); 72 | } 73 | return NULL; 74 | } 75 | 76 | void freeTree(StringTree* tree) { 77 | tree->root = freeTreeUtil(tree->root); 78 | } 79 | 80 | TreeNode *findTreeUtil(TreeNode *root, char *value) { 81 | if (!root) 82 | return NULL; 83 | 84 | int compare = strcmp(root->value, value); 85 | 86 | if (compare == 0) 87 | return root; 88 | else if (compare > 0) 89 | return findTreeUtil(root->lChild, value); 90 | else 91 | return findTreeUtil(root->rChild, value); 92 | } 93 | 94 | int findTree(StringTree* tree, char *value) { 95 | if(findTreeUtil(tree->root, value)) 96 | return 1; 97 | return 0; 98 | } 99 | 100 | int frequency(TreeNode *root, char *value) { 101 | if (!root) 102 | return 0; 103 | 104 | int compare = strcmp(root->value, value); 105 | if (compare == 0) 106 | return root->count; 107 | else if (compare > 0) 108 | return frequency(root->lChild, value); 109 | else 110 | return frequency(root->rChild, value); 111 | } 112 | 113 | int main() { 114 | StringTree *tt = createTree(); 115 | addTree(tt, "banana"); 116 | addTree(tt, "apple"); 117 | addTree(tt, "mango"); 118 | 119 | printf("find apple : %d\n", findTree(tt, "apple")); 120 | printf("find apple : %d\n", findTree(tt, "banana")); 121 | printf("find apple : %d\n", findTree(tt, "grapes")); 122 | printf("find apple : %d\n", findTree(tt, "mango")); 123 | } 124 | 125 | /* 126 | find apple : 1 127 | find apple : 1 128 | find apple : 0 129 | find apple : 1 130 | */ -------------------------------------------------------------------------------- /Algo/DP/JobScheduling.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct Job { 6 | int start; 7 | int stop; 8 | int value; 9 | } Job ; 10 | 11 | Job* createJob(int s, int f, int v) { 12 | Job* jb = (Job*)malloc(sizeof(Job)); 13 | jb->start = s; 14 | jb->stop = f; 15 | jb->value = v; 16 | return jb; 17 | } 18 | 19 | int max(int a, int b) { 20 | return (a>b)? a : b; 21 | } 22 | 23 | int greater(Job *j1, Job *j2) { // swap condition for sorting. 24 | return j1->stop > j2->stop; 25 | } 26 | 27 | int maxValueJobUtil(Job* arr[], int n) { 28 | // Base case 29 | if (n == 1) 30 | return arr[0]->value; 31 | 32 | // Find Value when current job is included 33 | int incl = arr[n - 1]->value; 34 | for (int j = n - 1; j >= 0; j--) { 35 | if (arr[j]->stop <= arr[n - 1]->start) { 36 | incl += maxValueJobUtil(arr, j + 1); 37 | break; 38 | } 39 | } 40 | 41 | // Find Value when current job is excluded 42 | int excl = maxValueJobUtil(arr, n - 1); 43 | 44 | return max(incl, excl); 45 | } 46 | 47 | void sort(Job* arr[], int size, int (*comp)(Job* p1, Job* p2)) { 48 | int i, j; 49 | Job* temp; 50 | for (i = 0; i < (size - 1); i++) { 51 | for (j = 0; j < size - i - 1; j++) { 52 | if (comp(arr[j], arr[j + 1])) { 53 | /* Swapping */ 54 | temp = arr[j]; 55 | arr[j] = arr[j + 1]; 56 | arr[j + 1] = temp; 57 | } 58 | } 59 | } 60 | } 61 | 62 | int maxValueJobs(int s[], int f[], int v[], int n) { 63 | Job* act[n]; 64 | for (int i = 0;i < n;i++) 65 | act[i] = createJob(s[i], f[i], v[i]); 66 | 67 | sort(act, n, greater); // sort according to finish time. 68 | return maxValueJobUtil(act, n); 69 | } 70 | 71 | int maxValueJobTDUtil(int dp[], Job* arr[], int n) { 72 | if (dp[n - 1] != 0) 73 | return dp[n - 1]; 74 | 75 | // Find Value when current job is included 76 | int incl = arr[n - 1]->value; 77 | for (int j = n - 2; j >= 0; j--) { 78 | if (arr[j]->stop <= arr[n - 1]->start) { 79 | incl += maxValueJobTDUtil(dp, arr, j + 1); 80 | break; 81 | } 82 | } 83 | 84 | // Find Value when current job is excluded 85 | int excl = maxValueJobTDUtil(dp, arr, n - 1); 86 | dp[n - 1] = max(incl, excl); 87 | return dp[n - 1]; 88 | } 89 | 90 | int maxValueJobsTD(int s[], int f[], int v[], int n) { 91 | Job* act[n]; 92 | for (int i = 0;i < n;i++) 93 | act[i] = createJob(s[i], f[i], v[i]); 94 | 95 | sort(act, n, greater); // sort according to finish time. 96 | int dp[n]; 97 | memset(dp, 0, sizeof(dp)); 98 | dp[0] = act[0]->value; 99 | 100 | return maxValueJobTDUtil(dp, act, n); 101 | } 102 | 103 | int maxValueJobsBU(int s[], int f[], int v[], int n) { 104 | Job* act[n]; 105 | for (int i = 0;i < n;i++) 106 | act[i] = createJob(s[i], f[i], v[i]); 107 | 108 | sort(act, n, greater); // sort according to finish time. 109 | int dp[n]; 110 | dp[0] = act[0]->value; 111 | 112 | for (int i = 1; i < n; i++) { 113 | int incl = act[i]->value; 114 | for (int j = i - 1; j >= 0; j--) { 115 | if (act[j]->stop <= act[i]->start) { 116 | incl += dp[j]; 117 | break; 118 | } 119 | } 120 | dp[i] = max(incl, dp[i - 1]); 121 | } 122 | return dp[n - 1]; 123 | } 124 | 125 | int main() { 126 | int start[] = {1, 5, 0, 3, 5, 6, 8}; 127 | int finish[] = {2, 6, 5, 4, 9, 7, 9}; 128 | int value[] = {2, 2, 4, 3, 10, 2, 8}; 129 | int n = 7; 130 | printf("%d\n", maxValueJobs(start, finish, value, n)); 131 | printf("%d\n", maxValueJobsTD(start, finish, value, n)); 132 | printf("%d\n", maxValueJobsBU(start, finish, value, n)); 133 | } 134 | 135 | /* 136 | 17 137 | 17 138 | 17 139 | */ -------------------------------------------------------------------------------- /Algo/DAC/ClosestPair.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct Point { 6 | int x; 7 | int y; 8 | } Point; 9 | 10 | Point* createPoint(int a, int b) { 11 | Point *pt = (Point *)malloc(sizeof(Point)); 12 | pt->x = a; 13 | pt->y = b; 14 | return pt; 15 | } 16 | 17 | int xCompare(Point *p1, Point *p2) { 18 | return (p1->x > p2->x); 19 | } 20 | 21 | int yCompare(Point *p1, Point *p2) { 22 | return (p1->y > p2->y); 23 | } 24 | 25 | double min(double x, double y) { 26 | return (x < y)? x : y; 27 | } 28 | 29 | void sort(Point* arr[], int size, int (*comp)(Point* p1, Point* p2)) { 30 | int i, j; 31 | Point* temp; 32 | for (i = 0; i < (size - 1); i++) { 33 | for (j = 0; j < size - i - 1; j++) { 34 | if (comp(arr[j], arr[j + 1])) { 35 | /* Swapping */ 36 | temp = arr[j]; 37 | arr[j] = arr[j + 1]; 38 | arr[j + 1] = temp; 39 | } 40 | } 41 | } 42 | } 43 | 44 | double closestPairBF(int arr[][2], int n) { 45 | double dmin = 999999; 46 | for (int i = 0; i < n - 1 ; i++) { 47 | for (int j = i + 1; j < n ; j++) { 48 | double val = sqrt((arr[i][0] - arr[j][0]) * (arr[i][0] - arr[j][0]) + 49 | (arr[i][1] - arr[j][1]) * (arr[i][1] - arr[j][1])); 50 | dmin = min(dmin, val); 51 | } 52 | } 53 | return dmin; 54 | } 55 | 56 | double distance(Point *a, Point *b) { 57 | return sqrt((a->x - b->x) * (a->x - b->x) + (a->y - b->y) * (a->y - b->y)); 58 | } 59 | 60 | double stripMin(Point* q[], int n, double d) { 61 | double dmin = d; 62 | 63 | // Find the distance between all the points in the strip. 64 | // Array q is sorted according to the y axis coordinate. 65 | // The inner loop will run at most 6 times for each point. 66 | for (int i = 0; i < n; ++i) { 67 | for (int j = i + 1; j < n && (q[j]->y - q[i]->y) < dmin; ++j) { 68 | dmin = min(dmin, distance(q[i],q[j])); 69 | } 70 | } 71 | return dmin; 72 | } 73 | 74 | double closestPairUtil(Point* p[], int start, int stop, Point* q[], int n) { 75 | if (stop - start < 1) { 76 | return 999999; 77 | } 78 | 79 | if (stop - start == 1) { 80 | return distance(p[start], p[stop]); 81 | } 82 | 83 | // Find the middle point 84 | int mid = (start + stop) / 2; 85 | double dl = closestPairUtil(p, start, mid, q, n); 86 | double dr = closestPairUtil(p, mid + 1, stop, q, n); 87 | double d = min(dl, dr); 88 | 89 | // Build an array strip[] that contains points whose x axis coordinate 90 | // in the range p[mid]-d and p[mid]+d 91 | // Points are already sorted according to y axis. 92 | Point* strip[n]; 93 | int j = 0; 94 | for (int i = 0; i < n; i++) { 95 | if (abs(q[i]->x - p[mid]->x) < d) { 96 | strip[j] = q[i]; 97 | j++; 98 | } 99 | } 100 | // Find the closest points in strip and compare with d. 101 | return min(d, stripMin(strip, j, d)); 102 | } 103 | 104 | double closestPairDC(int arr[][2], int n) { 105 | Point* p[n]; 106 | Point* q[n]; 107 | for (int i = 0; i < n; i++) { 108 | p[i] = createPoint(arr[i][0], arr[i][1]); 109 | q[i] = createPoint(arr[i][0], arr[i][1]); 110 | } 111 | sort(p, n, &xCompare); // Sort according to x axis. 112 | sort(q, n, &yCompare); // Sort according to y axis. 113 | return closestPairUtil(p, 0, n - 1, q, n); 114 | } 115 | 116 | int main() { 117 | int arr[][2] = {{648, 896}, {269, 879}, {250, 922}, {453, 347}, {213, 17}}; 118 | printf("Smallest distance is: %lf\n" , closestPairBF(arr, 5) ); 119 | printf("Smallest distance is: %lf\n" , closestPairDC(arr, 5) ); 120 | return 0; 121 | } 122 | 123 | /* 124 | Smallest distance is: 47.010637 125 | Smallest distance is: 47.010637 126 | */ -------------------------------------------------------------------------------- /String/StrStr.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int BruteForceSearch(char *text, char *pattern) { 6 | const int n = strlen(text); 7 | const int m = strlen(pattern); 8 | int j; 9 | 10 | for (int i = 0; i <= n - m; i++) { 11 | for (j = 0; j < m; j++) { 12 | if (pattern[j] != text[i + j]) 13 | break; 14 | } 15 | if (j == m) 16 | return i; 17 | } 18 | return -1; 19 | } 20 | 21 | int RobinKarp(char *text, char *pattern) { 22 | const int n = strlen(text); 23 | const int m = strlen(pattern); 24 | int prime = 101; 25 | int powm = 1; 26 | int textHash = 0, patternHash = 0; 27 | 28 | if (m == 0 || m > n) 29 | return -1; 30 | 31 | for (int i = 0; i < m - 1; i++) 32 | powm = (powm << 1) % prime; 33 | 34 | for (int i = 0; i < m; i++) { 35 | patternHash = ((patternHash << 1) + pattern[i]) % prime; 36 | textHash = ((textHash << 1) + text[i]) % prime; 37 | } 38 | 39 | for (int i = 0; i <= (n - m); i++) { 40 | if (textHash == patternHash) { 41 | int j; 42 | for (j = 0; j < m; j++) { 43 | if (text[i + j] != pattern[j]) 44 | break; 45 | } 46 | 47 | if (j == m) 48 | return i; 49 | } 50 | 51 | if(i < (n - m)) 52 | textHash = (((textHash - text[i] * powm) << 1) + text[i + m]) % prime; 53 | 54 | if (textHash < 0) 55 | textHash = (textHash + prime); 56 | } 57 | return -1; 58 | } 59 | 60 | void KMPPreprocess(char *pattern, int *ShiftArr) { 61 | const int m = strlen(pattern); 62 | int i = 0, j = -1; 63 | ShiftArr[i] = -1; 64 | while (i < m) { 65 | while (j >= 0 && pattern[i] != pattern[j]) 66 | j = ShiftArr[j]; 67 | i++; 68 | j++; 69 | ShiftArr[i] = j; 70 | } 71 | } 72 | 73 | int KMP(char *text, char *pattern) { 74 | int i = 0, j = 0, count = 0; 75 | const int n = strlen(text); 76 | const int m = strlen(pattern); 77 | int *ShiftArr = (int *)calloc(m + 1, sizeof(int)); 78 | 79 | KMPPreprocess(pattern, ShiftArr); 80 | 81 | while (i < n) { 82 | while (j >= 0 && text[i] != pattern[j]) 83 | j = ShiftArr[j]; 84 | i++; 85 | j++; 86 | if (j == m) { 87 | return (i - m); 88 | } 89 | } 90 | return -1; 91 | } 92 | int KMPFindCount(char *text, char *pattern) { 93 | int i = 0, j = 0, count = 0; 94 | const int n = strlen(text); 95 | const int m = strlen(pattern); 96 | int *ShiftArr = (int *)calloc(m + 1, sizeof(int)); 97 | 98 | KMPPreprocess(pattern, ShiftArr); 99 | while (i < n) { 100 | while (j >= 0 && text[i] != pattern[j]) 101 | j = ShiftArr[j]; 102 | 103 | i++; 104 | j++; 105 | 106 | if (j == m) { 107 | count++; 108 | j = ShiftArr[j]; 109 | } 110 | } 111 | return count; 112 | } 113 | 114 | int main1() { 115 | char *text = "hello, world!"; 116 | char *pattern = "world"; 117 | printf("BruteForceSearch returns: %d \n", BruteForceSearch(text, pattern)); 118 | printf("RobinKarp returns: %d \n", RobinKarp(text, pattern)); 119 | printf("KMP returns: %d \n", KMP(text, pattern)); 120 | return 0; 121 | } 122 | 123 | /* 124 | BruteForceSearch : 7 125 | RobinKarp : 7 126 | KMP : 7 127 | */ 128 | 129 | int main() { 130 | main1(); 131 | char* str = "Only time will tell if we stand the test of time"; 132 | printf("Frequency of 'time' is : %d\n", KMPFindCount(str, "time")); 133 | return 0; 134 | } 135 | /* 136 | Frequency of 'time' is : 2 137 | */ -------------------------------------------------------------------------------- /Algo/DP/MatrixCM.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int min(int a, int b) { 5 | return (a < b)? a : b; 6 | } 7 | int INFINITE = 99999; 8 | 9 | 10 | int MatrixChainMulBruteForceUtil(int p[], int i, int j) { 11 | if (i == j) // self product cost 0 12 | return 0; 13 | 14 | int min = INFINITE; 15 | 16 | // place parenthesis at different places between first and last matrix, recursively calculate 17 | // count of multiplications for each parenthesis placement and return the minimum count 18 | for (int k = i; k < j; k++) { 19 | int count = MatrixChainMulBruteForceUtil(p, i, k) + 20 | MatrixChainMulBruteForceUtil(p, k + 1, j) + 21 | p[i - 1] * p[k] * p[j]; 22 | 23 | if (count < min) 24 | min = count; 25 | } 26 | return min; // Return minimum count 27 | } 28 | 29 | int MatrixChainMulBruteForce(int p[], int n) { 30 | return MatrixChainMulBruteForceUtil(p, 1, n - 1); 31 | } 32 | 33 | 34 | int MatrixChainMulTDUtil(int n, int dp[][n], int p[], int i, int j) { 35 | if (dp[i][j] != INFINITE) 36 | return dp[i][j]; 37 | 38 | for (int k = i; k < j; k++) { 39 | dp[i][j] = min(dp[i][j], MatrixChainMulTDUtil(n, dp, p, i, k) + 40 | MatrixChainMulTDUtil(n, dp, p, k+1, j) + p[i-1]*p[k]*p[j]); 41 | } 42 | return dp[i][j]; 43 | } 44 | 45 | int MatrixChainMulTD(int p[], int n) { 46 | int dp[n][n]; 47 | for (int i = 0; i < n; i++) 48 | for (int j = 0; j < n; j++) 49 | dp[i][j] = INFINITE; 50 | 51 | for (int i = 1; i < n; i++) 52 | dp[i][i] = 0; 53 | 54 | return MatrixChainMulTDUtil(n, dp, p, 1, n - 1); 55 | } 56 | 57 | int MatrixChainMulBU(int p[], int n) { 58 | int dp[n][n]; 59 | for (int i = 0; i < n; i++) 60 | for (int j = 0; j < n; j++) 61 | dp[i][j] = INFINITE; 62 | 63 | for (int i = 1; i < n; i++) 64 | dp[i][i] = 0; 65 | 66 | for (int l = 1; l < n; l++) { // l is length of range. 67 | for (int i = 1,j = i + l ; j < n; i++, j++) { 68 | for (int k = i; k < j; k++) 69 | dp[i][j] = min(dp[i][j], dp[i][k] + p[i-1]*p[k]*p[j] + dp[k+1][j]); 70 | } 71 | } 72 | return dp[1][n - 1]; 73 | } 74 | 75 | void PrintOptPar(int n, int pos[][n], int i, int j) { 76 | if (i == j) 77 | printf ("M%d ", pos[i][i]); 78 | else { 79 | printf("( "); 80 | PrintOptPar(n, pos, i, pos[i][j]); 81 | PrintOptPar(n, pos, pos[i][j]+1, j); 82 | printf (") "); 83 | } 84 | } 85 | 86 | void PrintOptimalParenthesis(int n, int pos[][n]) { 87 | printf("OptimalParenthesis : "); 88 | PrintOptPar(n, pos, 1, n-1); 89 | printf("\n"); 90 | } 91 | 92 | int MatrixChainMulBU2(int p[], int n) { 93 | int dp[n][n]; 94 | int pos[n][n]; 95 | 96 | for (int i = 0; i < n; i++) { 97 | for (int j = 0; j < n; j++) { 98 | dp[i][j] = INFINITE; 99 | } 100 | } 101 | 102 | for (int i = 1; i < n; i++) { 103 | dp[i][i] = 0; 104 | pos[i][i] = i; 105 | } 106 | 107 | for (int l = 1; l < n; l++) { // l is length of range. 108 | for (int i = 1,j = i + l ; j < n; i++, j++) { 109 | for (int k = i; k < j; k++) { 110 | dp[i][j] = min(dp[i][j], dp[i][k] + p[i-1]*p[k]*p[j] + dp[k+1][j]); 111 | pos[i][j] = k; 112 | } 113 | } 114 | } 115 | 116 | PrintOptimalParenthesis(n, pos); 117 | return dp[1][n - 1]; 118 | } 119 | 120 | int main() { 121 | int arr[] = {40, 10, 50, 20, 15}; 122 | int n = sizeof(arr)/sizeof(int); 123 | printf("Matrix Chain Multiplication is: %d.\n" , MatrixChainMulBruteForce(arr, n) ); 124 | printf("Matrix Chain Multiplication is: %d.\n" , MatrixChainMulTD(arr, n) ); 125 | printf("Matrix Chain Multiplication is: %d.\n" , MatrixChainMulBU(arr, n) ); 126 | printf("Matrix Chain Multiplication is: %d.\n" , MatrixChainMulBU2(arr, n) ); 127 | return 0; 128 | } 129 | 130 | /* 131 | Matrix Chain Multiplication is: 19000. 132 | Matrix Chain Multiplication is: 19000. 133 | Matrix Chain Multiplication is: 19000. 134 | ( ( ( M1 M2 ) M3 ) M4 ) Matrix Chain Multiplication is: 19000. 135 | */ 136 | -------------------------------------------------------------------------------- /Stack/Stack.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include 4 | #include "string.h" 5 | 6 | #ifndef ERROR_VALUE 7 | #define ERROR_VALUE -99999 8 | #endif 9 | 10 | 11 | 12 | typedef struct Stack { 13 | int top; 14 | int *data; 15 | int capacity; 16 | } Stack; 17 | 18 | 19 | #define STACK_CAPACITY 100 20 | 21 | Stack* createStack() { 22 | Stack *stk = (Stack*)malloc(sizeof(Stack)); 23 | stk->data = (int *)malloc(STACK_CAPACITY * sizeof(int)); 24 | stk->top = -1; 25 | stk->capacity = STACK_CAPACITY; 26 | return stk; 27 | } 28 | 29 | void stackPush(Stack *stk, int value) { 30 | if (stk->top + 1 == stk->capacity) { 31 | printf("Stack is full.\n"); 32 | return; 33 | } 34 | stk->top++; 35 | stk->data[stk->top] = value; 36 | } 37 | 38 | int stackPop(Stack *stk) { 39 | if (stk->top == -1) { 40 | printf("stack empty.\n"); 41 | return ERROR_VALUE; 42 | } 43 | 44 | int value = stk->data[stk->top]; 45 | stk->top--; 46 | return value; 47 | } 48 | 49 | int stackTop(Stack *stk) { 50 | if (stk->top == -1) { 51 | printf("stack empty.\n"); 52 | return ERROR_VALUE; 53 | } 54 | int value = stk->data[stk->top]; 55 | return value; 56 | } 57 | 58 | int stackIsEmpty(Stack *stk) { 59 | return (stk->top == -1); 60 | } 61 | 62 | int stackSize(Stack *stk) { 63 | return (stk->top + 1); 64 | } 65 | 66 | void stackPrint(Stack *stk) { 67 | printf("["); 68 | for (int i = stk->top; i >= 0; i--) { 69 | printf("%d ", stk->data[i]); 70 | } 71 | printf("]\n"); 72 | } 73 | 74 | int mainA() { 75 | Stack* stk = createStack(); 76 | stackPush(stk, 1); 77 | stackPush(stk, 2); 78 | stackPush(stk, 3); 79 | stackPrint(stk); 80 | printf("%d ",stackPop(stk)); 81 | printf("%d ",stackPop(stk)); 82 | return 0; 83 | } 84 | 85 | /* 86 | [3 2 1 ] 87 | 3 2 88 | */ 89 | 90 | int mainB() { 91 | Stack* stk = createStack(); 92 | for (int i = 0; i < 20; i++) 93 | stackPush(stk, i); 94 | printf("stackTop %d \n", stackTop(stk)); 95 | printf("stackSize %d \n", stackSize(stk)); 96 | printf("stackIsEmpty %d \n", stackIsEmpty(stk)); 97 | stackPrint(stk); 98 | for (int i = 0; i < 20; i++) 99 | printf("%d ",stackPop(stk)); 100 | printf("stackIsEmpty %d \n", stackIsEmpty(stk)); 101 | return 0; 102 | } 103 | 104 | typedef struct Stack2 { 105 | int top; 106 | int *data; 107 | int capacity; 108 | int mincapacity; 109 | } Stack2; 110 | 111 | Stack2* createStack2(int size) { 112 | Stack2 *stk = (Stack2*)malloc(sizeof(Stack)); 113 | stk->data = (int *)malloc(size * sizeof(int)); 114 | stk->top = -1; 115 | stk->capacity = size; 116 | stk->mincapacity = size; // flex stack 117 | return stk; 118 | } 119 | 120 | // flex stack push 121 | void stackPush2(Stack2 *stk, int value) { 122 | if (stk->top + 1 == stk->capacity) { 123 | printf("Stack size doubled.\n"); 124 | stk->capacity = stk->capacity * 2; 125 | stk->data = (int *)realloc(stk->data, stk->capacity * sizeof(int)); 126 | } 127 | stk->top++; 128 | stk->data[stk->top] = value; 129 | } 130 | 131 | // flex stack pop 132 | int stackPop2(Stack2 *stk) { 133 | if (stk->top == -1) { 134 | printf("stack empty.\n"); 135 | return ERROR_VALUE; 136 | } 137 | 138 | int topVal = stk->data[stk->top]; 139 | stk->top--; 140 | 141 | if (stk->top + 1 < (stk->capacity / 2) && stk->capacity > stk->mincapacity) { 142 | printf("Stack size halfed.\n"); 143 | stk->capacity = stk->capacity / 2; 144 | stk->data = (int *)realloc(stk->data, stk->capacity * sizeof(int)); 145 | } 146 | return topVal; 147 | } 148 | 149 | int mainC() { 150 | Stack2* stk = createStack2(5); 151 | for (int i = 0; i <= 11; i++) 152 | stackPush2(stk, i); 153 | for (int i = 0; i <= 11; i++) 154 | printf("%d ", stackPop2(stk)); 155 | return 0; 156 | } 157 | 158 | int main() { 159 | //mainA(); 160 | //mainB(); 161 | mainC(); 162 | } -------------------------------------------------------------------------------- /HashTable/HashTableExercise.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include "HashLP.c" 6 | 7 | int isAnagram(char *str1, char *str2) { 8 | int size1 = strlen(str1); 9 | int size2 = strlen(str2); 10 | if (size1 != size2) 11 | return 0; 12 | 13 | HashTable* ht = createHashTable(100); 14 | 15 | for (int i = 0; i < size1; i++) 16 | HashAdd(ht, str1[i]); 17 | 18 | for (int i = 0; i < size2; i++) { 19 | if (HashRemove(ht, str2[i]) == 0) 20 | return 0; 21 | } 22 | return 1; 23 | } 24 | 25 | char *removeDuplicate(char *str, int size) { 26 | HashTable* hs = createHashTable(100); 27 | char *ret = (char *)malloc(sizeof(char) * size); 28 | int retIndex = 0; 29 | for (int i = 0; i < size; i++) { 30 | if (HashFind(hs, str[i]) == 0) { 31 | ret[retIndex] = str[i]; 32 | retIndex += 1; 33 | HashAdd(hs, str[i]); 34 | } 35 | } 36 | ret[retIndex] = '\0'; 37 | return ret; 38 | } 39 | 40 | int findMissing(int arr[], int size, int start, int end) { 41 | HashTable* ht = createHashTable(100); 42 | 43 | for (int i = 0; i < size; i++) 44 | HashAdd(ht, arr[i]); 45 | 46 | for (int i = start; i <= end; i++) { 47 | if (HashFind(ht, i) == 0) 48 | return i; 49 | } 50 | return -99999; 51 | } 52 | 53 | void printRepeating(int arr[], int size) { 54 | HashTable* ht = createHashTable(100); 55 | printf("Repeating elements are: "); 56 | for (int i = 0; i < size; i++) { 57 | if (HashFind(ht, arr[i])) 58 | printf("%d ", arr[i]); 59 | else 60 | HashAdd(ht, arr[i]); 61 | } 62 | printf("\n"); 63 | } 64 | 65 | int printFirstRepeating(int arr[], int size) { 66 | HashTable* ht = createHashTable(100); 67 | int firstRepeating = -99999; 68 | 69 | for (int i = size - 1; i >= 0; i--) { 70 | if (HashFind(ht, arr[i])) { 71 | firstRepeating = arr[i]; 72 | } else { 73 | HashAdd(ht, arr[i]); 74 | } 75 | } 76 | if(firstRepeating != -99999) 77 | printf("First Repeating number is : %d\n", firstRepeating); 78 | else 79 | printf("No Repeating number\n"); 80 | 81 | return firstRepeating; 82 | } 83 | 84 | void PrintSortByOrder(int arr[], int size, int arr2[], int size2) { 85 | int i; 86 | HashTable* ht = createHashTable(100); 87 | for (i = 0; i < size; i++) { 88 | HashAdd(ht, arr[i]); 89 | } 90 | i = 0; 91 | while (i < size2) { 92 | if (HashRemove(ht, arr2[i]) == 1) { 93 | printf("%d ", arr2[i]); 94 | continue; 95 | } 96 | i++; 97 | } 98 | for (i = 0; i < size; i++) { 99 | if (HashRemove(ht, arr[i]) == 1) 100 | printf("%d ", arr[i]); 101 | } 102 | } 103 | 104 | int hornerHash(char key[], int size, int tableSize) { 105 | int h = 0; 106 | int i = 0; 107 | while (i < size) { 108 | h = (32 * h + key[i]) % tableSize; 109 | i += 1; 110 | } 111 | return h; 112 | } 113 | 114 | //Testing code 115 | int main() { 116 | char *first = "hello"; 117 | char *second = "elloh"; 118 | char *third = "world"; 119 | printf("isAnagram : %d\n", isAnagram(first, second)); 120 | printf("isAnagram : %d\n", isAnagram(first, third)); 121 | printf(" %s \n", removeDuplicate(first, strlen(first))); 122 | int arr[] = {1, 2, 3, 5, 6, 7, 8, 9, 10}; 123 | int size = 9; 124 | printf("findMissing : %d\n", findMissing(arr, 9, 1, 10)); 125 | int arr1[] = {1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 1}; 126 | int size2 = 11; 127 | printRepeating(arr1, 11); 128 | printFirstRepeating(arr1, 11); 129 | 130 | int arr2[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}; 131 | int arr3[] = {2, 1, 8, 3}; 132 | PrintSortByOrder(arr2, 11, arr3, 4); 133 | return 0; 134 | } 135 | 136 | /* 137 | isAnagram : 1 138 | isAnagram : 0 139 | helo 140 | findMissing : 4 141 | Repeating elements are: 4 1 142 | First Repeating number is : 1 143 | 2 2 1 1 8 8 3 5 7 9 6 144 | */ 145 | -------------------------------------------------------------------------------- /Introduction/Analysis.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | int fun1(int n) { 6 | int m = 0; 7 | for (int i = 0; i < n; i++) { 8 | m += 1; 9 | } 10 | return m; 11 | } 12 | 13 | int fun2(int n) { 14 | int i, j, m = 0; 15 | for (i = 0; i < n; i++) { 16 | for (j = 0; j < n; j++) { 17 | m += 1; 18 | } 19 | } 20 | return m; 21 | } 22 | 23 | int fun3(int n) { 24 | int i, j, k, m = 0; 25 | for (i = 0; i < n; i++) { 26 | for (j = 0; j < n; j++) { 27 | for (k = 0; k < n; k++) 28 | { 29 | m += 1; 30 | } 31 | } 32 | } 33 | return m; 34 | } 35 | 36 | int fun4(int n) { 37 | int i, j, k, m = 0; 38 | for (i = 0; i < n; i++) { 39 | for (j = i; j < n; j++) { 40 | for (k = j + 1; k < n; k++) 41 | { 42 | m += 1; 43 | } 44 | } 45 | } 46 | return m; 47 | } 48 | 49 | int fun5(int n) { 50 | int i, j, m = 0; 51 | for (i = 0; i < n; i++) { 52 | for (j = 0; j < i; j++) { 53 | m += 1; 54 | } 55 | } 56 | return m; 57 | } 58 | 59 | int fun6(int n) { 60 | int i, j, m = 0; 61 | for (i = 0; i < n; i++) { 62 | for (j = i; j > 0; j--) { 63 | m += 1; 64 | } 65 | } 66 | return m; 67 | } 68 | 69 | int fun7(int n) { 70 | int i, j, m = 0; 71 | for (i = n; i > 0; i /= 2) { 72 | for (j = 0; j < i; j++) { 73 | m += 1; 74 | } 75 | } 76 | return m; 77 | } 78 | 79 | int fun8(int n) { 80 | int i, j, m = 0; 81 | for (i = 1; i <= n; i *= 2) { 82 | for (j = 0; j <= i; j++) { 83 | m += 1; 84 | } 85 | } 86 | return m; 87 | } 88 | 89 | int fun9(int n) { 90 | int i, m = 0; 91 | i = 1; 92 | while (i < n) { 93 | m += 1; 94 | i = i * 2; 95 | } 96 | return m; 97 | } 98 | 99 | int fun10(int n) { 100 | int i, m = 0; 101 | i = n; 102 | while (i > 0) { 103 | m += 1; 104 | i = i / 2; 105 | } 106 | return m; 107 | } 108 | 109 | int fun11(int n) { 110 | int i, j, k, m = 0; 111 | for (i = 0; i < n; i++) { 112 | for (j = 0; j < n; j++) { 113 | m += 1; 114 | } 115 | } 116 | for (i = 0; i < n; i++) { 117 | for (k = 0; k < n; k++) { 118 | m += 1; 119 | } 120 | } 121 | return m; 122 | } 123 | 124 | int fun12(int n) { 125 | int i, j, m = 0; 126 | for (i = 0; i < n; i++) { 127 | for (j = 0; j < sqrt(n); j++) { 128 | m += 1; 129 | } 130 | } 131 | return m; 132 | } 133 | 134 | int fun13(int n) { 135 | int i, j = 0, m = 0; 136 | for (i = 0; i < n; i++) { 137 | for (; j < n; j++) { 138 | m += 1; 139 | } 140 | } 141 | return m; 142 | } 143 | 144 | int main() { 145 | printf("N = 100, Number of instructions O(n):: %d \n" ,fun1(100) ); 146 | printf("N = 100, Number of instructions O(n^2):: %d \n" ,fun2(100) ); 147 | printf("N = 100, Number of instructions O(n^3):: %d \n" ,fun3(100) ); 148 | printf("N = 100, Number of instructions O(n^3):: %d \n" ,fun4(100) ); 149 | printf("N = 100, Number of instructions O(n^2):: %d \n" ,fun5(100) ); 150 | printf("N = 100, Number of instructions O(n^2):: %d \n" ,fun6(100) ); 151 | printf("N = 100, Number of instructions O(n):: %d \n" ,fun7(100) ); 152 | printf("N = 100, Number of instructions O(n):: %d \n" ,fun8(100) ); 153 | printf("N = 100, Number of instructions O(log(n)):: %d \n" ,fun9(100) ); 154 | printf("N = 100, Number of instructions O(log(n)):: %d \n" ,fun10(100) ); 155 | printf("N = 100, Number of instructions O(n^2):: %d \n" ,fun11(100) ); 156 | printf("N = 100, Number of instructions O(n^(3/2)):: %d \n" ,fun12(100) ); 157 | printf("N = 100, Number of instructions O(n):: %d \n" ,fun13(100) ); 158 | return 0; 159 | } 160 | /* 161 | N = 100, Number of instructions O(n):: 100 162 | N = 100, Number of instructions O(n^2):: 10000 163 | N = 100, Number of instructions O(n^2):: 4950 164 | N = 100, Number of instructions O(log(n)):: 7 165 | N = 100, Number of instructions O(log(n)):: 7 166 | N = 100, Number of instructions O(n^3):: 1000000 167 | N = 100, Number of instructions O(n^2):: 20000 168 | N = 100, Number of instructions O(n^(3/2)):: 1000 169 | N = 100, Number of instructions O(log(n)):: 197 170 | N = 100, Number of instructions O(n^2):: 4950 171 | N = 100, Number of instructions O(n^3):: 166650 172 | N = 100, Number of instructions O(n):: 100 173 | N = 100, Number of instructions O(n):: 134 174 | */ 175 | -------------------------------------------------------------------------------- /Tree/SegmentTree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | typedef struct SegmentTree { 7 | int* segArr; 8 | int size; 9 | }SegmentTree; 10 | 11 | int constructST(SegmentTree* tree, int input[], int start, int end, int index) { 12 | // Store it in current node of the segment tree and return 13 | if (start == end) { 14 | tree->segArr[index] = input[start]; 15 | return input[start]; 16 | } 17 | 18 | // If there are more than one elements, 19 | // then traverse left and right subtrees 20 | // and store the sum of values in current node. 21 | int mid = (start + end) / 2; 22 | tree->segArr[index] = constructST(tree, input, start, mid, index * 2 + 1) + 23 | constructST(tree, input, mid + 1, end, index * 2 + 2); 24 | return tree->segArr[index]; 25 | } 26 | 27 | SegmentTree* createSegmentTree(int input[], int size) { 28 | SegmentTree* tree = (SegmentTree*)malloc(sizeof(SegmentTree)); 29 | // Height of segment tree. 30 | int x = ceil(log(size)/log(2)); 31 | //Maximum size of segment tree 32 | int maxSize = 2 * pow(2, x) - 1; 33 | // Allocate memory for segment tree 34 | tree->segArr = (int*) malloc(sizeof(int) *maxSize); 35 | tree->size = size; 36 | constructST(tree, input, 0, size - 1, 0); 37 | return tree; 38 | } 39 | 40 | int getSumUtil(SegmentTree* tree, int segStart, int segEnd, int queryStart, int queryEnd, int index) { 41 | if (queryStart <= segStart && segEnd <= queryEnd) // complete overlapping case. 42 | { 43 | return tree->segArr[index]; 44 | } 45 | 46 | if (segEnd < queryStart || queryEnd < segStart) // no overlapping case. 47 | { 48 | return 0; 49 | } 50 | 51 | // Segment tree is partly overlaps with the query range. 52 | int mid = (segStart + segEnd) / 2; 53 | return getSumUtil(tree, segStart, mid, queryStart, queryEnd, 2 * index + 1) + 54 | getSumUtil(tree, mid + 1, segEnd, queryStart, queryEnd, 2 * index + 2); 55 | } 56 | 57 | 58 | int getSum(SegmentTree* tree, int start, int end) { 59 | // Check for error conditions. 60 | if (start > end || start < 0 || end > tree->size - 1) { 61 | printf("Invalid Input."); 62 | return -1; 63 | } 64 | return getSumUtil(tree, 0, tree->size - 1, start, end, 0); 65 | } 66 | 67 | int setUtil(SegmentTree* tree, int segStart, int segEnd, int ind, int val, int index) { 68 | // set index lies outside the range of current segment. 69 | // So diff to its parent node will be zero. 70 | if (ind < segStart || ind > segEnd) { 71 | return 0; 72 | } 73 | 74 | // If the input index is in range of this node, then set the 75 | // value of the node and its children 76 | if (segStart == segEnd) { 77 | if (segStart == ind) { // Index that need to be set. 78 | int diff = val - tree->segArr[index]; 79 | tree->segArr[index] = val; 80 | return diff; 81 | } else { 82 | return 0; 83 | } 84 | } 85 | 86 | int mid = (segStart + segEnd) / 2; 87 | int diff = setUtil(tree, segStart, mid, ind, val, 2 * index + 1) + 88 | setUtil(tree, mid + 1, segEnd, ind, val, 2 * index + 2); 89 | 90 | // Current node value is set with diff. 91 | tree->segArr[index] = tree->segArr[index] + diff; 92 | 93 | // Value of diff is propagated to the parent node. 94 | return diff; 95 | } 96 | 97 | 98 | void set(SegmentTree* tree, int arr[], int ind, int val) { 99 | // Check for error conditions. 100 | if (ind < 0 || ind > tree->size - 1) { 101 | printf("Invalid Input."); 102 | return; 103 | } 104 | 105 | arr[ind] = val; 106 | 107 | // Set new value in segment tree 108 | setUtil(tree, 0, tree->size - 1, ind, val, 0); 109 | } 110 | 111 | int main() { 112 | int arr[] = {1, 2, 4, 8, 16, 32, 64}; 113 | int n = 7; 114 | SegmentTree *tree = createSegmentTree(arr, n); 115 | printf("Sum of values in the range(0, 3): %d\n", getSum(tree, 1, 3)); 116 | printf("Sum of values of all the elements: %d\n", getSum(tree, 0, n - 1)); 117 | 118 | set(tree, arr, 1, 10); 119 | printf("Sum of values in the range(0, 3): %d\n", getSum(tree, 1, 3)); 120 | printf("Sum of values of all the elements: %d\n", getSum(tree, 0, n - 1)); 121 | } 122 | 123 | /* 124 | Sum of values in the range(0, 3): 14 125 | Sum of values of all the elements: 127 126 | Sum of values in the range(0, 3): 22 127 | Sum of values of all the elements: 135 128 | */ -------------------------------------------------------------------------------- /Algo/DP/Knapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int max(int a, int b) { 6 | return (a > b)? a : b; 7 | } 8 | 9 | int maxCost01KnapsackUtil(int wt[], int cost[], int n, int capacity) { 10 | // Base Case 11 | if (n == 0 || capacity == 0) 12 | return 0; 13 | 14 | // Return the maximum of two cases: 15 | // (1) nth item is included 16 | // (2) nth item is not included 17 | int first = 0; 18 | if (wt[n - 1] <= capacity) 19 | first = cost[n - 1] + maxCost01KnapsackUtil(wt, cost, n - 1, capacity - wt[n - 1]); 20 | 21 | int second = maxCost01KnapsackUtil(wt, cost, n - 1, capacity); 22 | return max(first, second); 23 | } 24 | 25 | int maxCost01Knapsack(int wt[], int cost[], int n, int capacity) { 26 | return maxCost01KnapsackUtil(wt, cost, n, capacity); 27 | } 28 | 29 | int maxCost01KnapsackTDUtil(int n, int dp[][n+1], int wt[], int cost[], int i, int w) { 30 | if (w == 0 || i == 0) 31 | return 0; 32 | 33 | if (dp[w][i] != 0) 34 | return dp[w][i]; 35 | 36 | // Their are two cases: 37 | // (1) ith item is included 38 | // (2) ith item is not included 39 | int first = 0; 40 | if (wt[i - 1] <= w) 41 | first = maxCost01KnapsackTDUtil(n, dp, wt, cost, i - 1, w - wt[i - 1]) + cost[i - 1]; 42 | 43 | int second = maxCost01KnapsackTDUtil(n, dp, wt, cost, i - 1, w); 44 | return dp[w][i] = max(first,second); 45 | } 46 | 47 | int maxCost01KnapsackTD(int wt[], int cost[], int n, int capacity) { 48 | int dp[capacity + 1][n + 1]; 49 | memset(dp, 0, sizeof(dp)); 50 | return maxCost01KnapsackTDUtil(n, dp, wt, cost, n, capacity); 51 | } 52 | 53 | 54 | void printItems(int n, int dp[][n+1], int wt[], int cost[], int capacity) { 55 | int totalProfit = dp[capacity][n]; 56 | printf("Selected items are: "); 57 | for (int i = n-1; i > -1 && totalProfit > 0; i--) { 58 | if (totalProfit != dp[capacity][i - 1]) { 59 | printf("(wt:%d, cost:%d) ", wt[i] ,cost[i]); 60 | capacity -= wt[i]; 61 | totalProfit -= cost[i]; 62 | } 63 | } 64 | printf("\n"); 65 | } 66 | 67 | int maxCost01KnapsackBU(int wt[], int cost[], int n, int capacity) { 68 | int dp[capacity + 1][n + 1] ; 69 | memset(dp, 0, sizeof(dp)); 70 | // Build table dp[][] in bottom up approach. 71 | // Weights considered against capacity. 72 | for (int w = 1; w <= capacity; w++) { 73 | for (int i = 1; i <= n; i++) { 74 | // Their are two cases: 75 | // (1) ith item is included 76 | // (2) ith item is not included 77 | int first = 0; 78 | if (wt[i - 1] <= w) 79 | first = dp[w - wt[i - 1]][i - 1] + cost[i - 1]; 80 | 81 | int second = dp[w][i - 1]; 82 | dp[w][i] = max(first,second); 83 | } 84 | } 85 | printItems(n, dp, wt, cost, capacity); 86 | return dp[capacity][n]; // Number of weights considered and final capacity. 87 | } 88 | 89 | int KS01UnboundBU(int wt[], int cost[], int n, int capacity) { 90 | int dp[capacity + 1]; 91 | memset(dp, 0, sizeof(dp)); 92 | 93 | // Build table dp[] in bottom up approach. 94 | // Weights considered against capacity. 95 | for (int w = 1; w <= capacity; w++) { 96 | for (int i = 1; i <= n; i++) { 97 | // Their are two cases: 98 | // (1) ith item is included 99 | // (2) ith item is not included 100 | if (wt[i - 1] <= w) 101 | dp[w] = max(dp[w], dp[w - wt[i - 1]] + cost[i - 1]); 102 | } 103 | } 104 | return dp[capacity]; // Number of weights considered and final capacity. 105 | } 106 | 107 | int main() { 108 | int wt[] = {10, 40, 20, 30}; 109 | int cost[] = {60, 40, 90, 120}; 110 | int capacity = 50; 111 | int n = 4; 112 | double maxCost = KS01UnboundBU(wt, cost, n, capacity); 113 | printf("Maximum cost obtained = %f\n" , maxCost ); 114 | maxCost = maxCost01Knapsack(wt, cost, n, capacity); 115 | printf("Maximum cost obtained = %f\n" , maxCost ); 116 | maxCost = maxCost01KnapsackBU(wt, cost, n, capacity); 117 | printf("Maximum cost obtained = %f\n" , maxCost ); 118 | maxCost = maxCost01KnapsackTD(wt, cost, n, capacity); 119 | printf("Maximum cost obtained = %f\n" , maxCost ); 120 | return 0; 121 | } 122 | 123 | /* 124 | Maximum cost obtained = 300.000000 125 | Maximum cost obtained = 210.000000 126 | Selected items are: (wt:30, cost:120) (wt:20, cost:90) 127 | Maximum cost obtained = 210.000000 128 | Maximum cost obtained = 210.000000 129 | */ -------------------------------------------------------------------------------- /HashTable/Counter.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TABLE_SIZE 517 5 | #define TABLE_BITS 9 6 | 7 | unsigned int Hash(int key, int tableSize) { //division method 8 | unsigned int hashValue = 0; 9 | hashValue = key; 10 | return hashValue % tableSize; 11 | } 12 | 13 | typedef struct CounterNode { 14 | int key; 15 | int value; 16 | struct CounterNode *next; 17 | } CounterNode; 18 | 19 | CounterNode* createCounterNode(int key, int value, CounterNode* next) { 20 | CounterNode* node = (CounterNode*)malloc(sizeof(CounterNode)); 21 | node->key = key; 22 | node->value = value; 23 | node->next = next; 24 | return node; 25 | } 26 | 27 | typedef struct Counter { 28 | int tableSize; 29 | CounterNode **listArray; //double pointer 30 | } Counter; 31 | 32 | Counter * createCounter() { 33 | Counter *hTable = (Counter*) malloc(sizeof(Counter)); 34 | hTable->tableSize = TABLE_SIZE; 35 | hTable->listArray = (CounterNode **)malloc(hTable->tableSize * sizeof(CounterNode *)); 36 | 37 | for (int i = 0; i < hTable->tableSize; i++) 38 | hTable->listArray[i] = NULL; 39 | return hTable; 40 | } 41 | 42 | void CounterPrint(Counter *hTable) { 43 | for (int i = 0; i < hTable->tableSize; i++) { 44 | CounterNode *head = hTable->listArray[i]; 45 | while (head) { 46 | printf("[%d->%d] ", head->key, head->value); 47 | head = head->next; 48 | } 49 | } 50 | printf("\n"); 51 | } 52 | 53 | int FindKey(Counter *hTable, int key) { 54 | CounterNode *head; 55 | int index = Hash(key, hTable->tableSize); 56 | head = hTable->listArray[index]; 57 | while(head) { 58 | if (head->key == key) 59 | return 1; 60 | head = head->next; 61 | } 62 | return 0; 63 | } 64 | 65 | int GetCount(Counter *hTable, int key) { 66 | int index = Hash(key, hTable->tableSize); 67 | CounterNode *head = hTable->listArray[index]; 68 | while(head) { 69 | if(head->key == key) 70 | return head->value; 71 | head = head->next; 72 | } 73 | return 0; 74 | } 75 | 76 | void CounterAdd(Counter *hTable, int key) { 77 | int index = Hash(key, hTable->tableSize); 78 | CounterNode *head = hTable->listArray[index]; 79 | while(head) { 80 | if (head->key == key) { 81 | head->value += 1; 82 | return; 83 | } 84 | head = head->next; 85 | } 86 | hTable->listArray[index] = createCounterNode(key, 1, hTable->listArray[index]); 87 | } 88 | 89 | int CounterRemove(Counter *hTable, int key) { 90 | int index = Hash(key, hTable->tableSize); 91 | CounterNode *currNode = hTable->listArray[index]; 92 | 93 | if(currNode && currNode->key == key) { 94 | if(currNode->value == 1) { 95 | hTable->listArray[index] = currNode->next; 96 | free(currNode); 97 | } else { 98 | currNode->value -= 1; 99 | } 100 | return 1; 101 | } 102 | 103 | CounterNode *nextNode; 104 | while (currNode) { 105 | nextNode = currNode->next; 106 | if (nextNode && nextNode->key == key) { 107 | if (nextNode->value == 1) { 108 | currNode->next = nextNode->next; 109 | free(nextNode); 110 | } else { 111 | nextNode->value -= 1; 112 | } 113 | return 1; 114 | } 115 | currNode = nextNode; 116 | } 117 | return 0; 118 | } 119 | 120 | int mainA() { 121 | Counter* ctr = createCounter(); 122 | CounterAdd(ctr, 2); 123 | CounterAdd(ctr, 3); 124 | CounterAdd(ctr, 3); 125 | CounterAdd(ctr, 5); 126 | CounterAdd(ctr, 5); 127 | CounterAdd(ctr, 5); 128 | CounterPrint(ctr); 129 | 130 | CounterRemove(ctr, 3); 131 | CounterPrint(ctr); 132 | CounterRemove(ctr, 3); 133 | CounterPrint(ctr); 134 | 135 | printf("FindKey 5 : %d\n", FindKey(ctr, 5)); 136 | printf("FindKey 3 : %d\n", FindKey(ctr, 3)); 137 | printf("GetCount 5 : %d\n", GetCount(ctr, 5)); 138 | printf("GetCount 3 : %d\n", GetCount(ctr, 3)); 139 | return 0; 140 | } 141 | 142 | /* 143 | [2->1] [3->2] [5->3] 144 | [2->1] [3->1] [5->3] 145 | [2->1] [5->3] 146 | FindKey 5 : 1 147 | FindKey 3 : 0 148 | GetCount 5 : 3 149 | GetCount 3 : 0 150 | */ 151 | -------------------------------------------------------------------------------- /Algo/DP/CoinChange.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int INFINITE = 99999 ; 4 | 5 | int greater(int a, int b) { 6 | return (a > b); 7 | } 8 | 9 | int min(int a, int b) { 10 | return (a < b)? a : b; 11 | } 12 | 13 | void sort(int arr[], int size, int (*comp)(int p1, int p2)) { 14 | int temp; 15 | for (int i = 0; i < (size - 1); i++) { 16 | for (int j = 0; j < size - i - 1; j++) { 17 | if (comp(arr[j], arr[j + 1])) { 18 | /* Swapping */ 19 | temp = arr[j]; 20 | arr[j] = arr[j + 1]; 21 | arr[j + 1] = temp; 22 | } 23 | } 24 | } 25 | } 26 | 27 | int minCoins(int d[], int n, int val) {// Greedy may be wrong. 28 | if (val <= 0) 29 | return 0; 30 | 31 | int count = 0; 32 | sort(d, n, greater); 33 | for (int i = n - 1; i >= 0 && val > 0;) { 34 | if (d[i] <= val) { 35 | count++; 36 | val -= d[i]; 37 | } else { 38 | i--; 39 | } 40 | } 41 | return (val == 0)? count : -1; 42 | } 43 | 44 | int minCoins2(int d[], int n, int val) // Brute force. 45 | { 46 | if (val == 0) 47 | return 0; 48 | 49 | int count = INFINITE ; 50 | for (int i = 0; i < n ; i++) { 51 | if (d[i] <= val) { 52 | int subCount = minCoins2(d, n, val - d[i]); 53 | if (subCount != -1) { 54 | count = min(count, subCount + 1); 55 | } 56 | } 57 | } 58 | return (count != INFINITE )? count : -1; 59 | } 60 | 61 | 62 | int minCoinsTDUtil(int coins[], int d[], int n, int val) { 63 | // Base case 64 | if (coins[val] != INFINITE ) 65 | return coins[val]; 66 | 67 | // Recursion 68 | for (int i = 0; i < n; i++) { 69 | if (d[i] <= val) { // check validity of a sub-problem 70 | int subCount = minCoinsTDUtil(coins, d, n, val - d[i]); 71 | 72 | if (subCount != INFINITE && coins[val] > (subCount + 1)) { 73 | coins[val] = subCount + 1; 74 | } 75 | } 76 | } 77 | return coins[val]; 78 | } 79 | 80 | 81 | int minCoinsTD(int d[], int n, int val) { 82 | int coins[val + 1]; 83 | for(int i = 0; i< val + 1; i++) 84 | coins[i] = INFINITE ; 85 | 86 | coins[0] = 0; // zero val need zero coins. 87 | return minCoinsTDUtil(coins, d, n, val); 88 | } 89 | 90 | int minCoinsBU(int d[], int n, int val) { // DP bottom up approach. 91 | int coins[val + 1]; 92 | for(int i = 0; i< val + 1; i++) 93 | coins[i] = INFINITE ; 94 | 95 | coins[0] = 0; // Base value. 96 | 97 | for (int i = 1; i <= val; i++) { 98 | for (int j = 0; j < n; j++) { 99 | // For all coins smaller than or equal to i. 100 | 101 | if (d[j] <= i && 102 | coins[i - d[j]] != INFINITE ) { 103 | coins[i] = min(coins[i], coins[i - d[j]] + 1); 104 | } 105 | } 106 | } 107 | 108 | return (coins[val] != INFINITE )? coins[val] : -1; 109 | } 110 | 111 | 112 | void printCoinsUtil(int deno[], int val) { 113 | if (val > 0){ 114 | printCoinsUtil(deno, val - deno[val]); 115 | printf("%d ", deno[val]); 116 | } 117 | } 118 | 119 | void printCoins(int deno[], int val) { 120 | printf("Coins are : "); 121 | printCoinsUtil(deno, val); 122 | printf("\n"); 123 | } 124 | 125 | int minCoinsBU2(int d[], int n, int val) { // DP bottom up approach. 126 | int coins[val + 1]; 127 | int deno[val + 1]; 128 | 129 | for(int i = 0; i< val + 1; i++){ 130 | coins[i] = INFINITE ; 131 | deno[i] = INFINITE ; 132 | } 133 | 134 | coins[0] = 0; // Base value. 135 | 136 | for (int i = 1; i <= val; i++) { 137 | for (int j = 0; j < n; j++) { 138 | // For all coins smaller than or equal to i. 139 | if (d[j] <= i 140 | && coins[i - d[j]] != INFINITE && coins[i] > (coins[i - d[j]] + 1)) { 141 | coins[i] = coins[i - d[j]] + 1; 142 | deno[i] = d[j]; 143 | } 144 | } 145 | } 146 | 147 | printCoins(deno, val); 148 | return (coins[val] != INFINITE )? coins[val] : -1; 149 | } 150 | 151 | int main() { 152 | int d[] = {1, 4, 6, 9, 12}; 153 | int value = 15; 154 | int n = 5; 155 | printf("Count is : %d\n" , minCoins(d, n, value)); 156 | printf("Count is : %d\n" , minCoins2(d, n, value)); 157 | printf("Count is : %d\n" , minCoinsBU(d, n, value)); 158 | printf("Count is : %d\n" , minCoinsTD(d, n, value)); 159 | printf("Count is : %d\n" , minCoinsBU2(d, n, value)); 160 | } 161 | 162 | /* 163 | Count is : 4 164 | Count is : 2 165 | Count is : 2 166 | Count is : 2 167 | Coins are : 9 6 168 | Count is : 2 169 | */ 170 | -------------------------------------------------------------------------------- /Tree/rangeMaxST.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | typedef struct RangeMaxST { 7 | int* segArr; 8 | int n; 9 | } RangeMaxST; 10 | 11 | int max(int first, int second) { 12 | return (first > second)? first : second; 13 | } 14 | 15 | int constructST(RangeMaxST* tree, int* input, int start, int end, int index) { 16 | // Store it in current node of the segment tree and return 17 | if (start == end) { 18 | tree->segArr[index] = input[start]; 19 | return input[start]; 20 | } 21 | 22 | // If there are more than one elements, 23 | // then traverse left and right subtrees 24 | // and store the minimum of values in current node. 25 | int mid = (start + end) / 2; 26 | tree->segArr[index] = max(constructST(tree, input, start, mid, index * 2 + 1), 27 | constructST(tree, input, mid + 1, end, index * 2 + 2)); 28 | return tree->segArr[index]; 29 | } 30 | 31 | RangeMaxST* createRangeMaxST(int input[], int n) { 32 | RangeMaxST* tree = (RangeMaxST*)malloc(sizeof(RangeMaxST)); 33 | // Height of segment tree. 34 | int x = ceil(log(n)/log(2)); 35 | //Maximum size of segment tree 36 | int maxSize = 2 * pow(2, x) - 1; 37 | // Allocate memory for segment tree 38 | tree->segArr = (int*) malloc(sizeof(int) *maxSize); 39 | tree->n = n; 40 | constructST(tree, input, 0, n - 1, 0); 41 | return tree; 42 | } 43 | 44 | int getMaxUtil(RangeMaxST* tree, int segStart, int segEnd, int queryStart, int queryEnd, int index) { 45 | if (queryStart <= segStart && segEnd <= queryEnd) // complete overlapping case. 46 | { 47 | return tree->segArr[index]; 48 | } 49 | 50 | if (segEnd < queryStart || queryEnd < segStart) // no overlapping case. 51 | { 52 | return -999999; 53 | } 54 | 55 | // Segment tree is partly overlaps with the query range. 56 | int mid = (segStart + segEnd) / 2; 57 | return max(getMaxUtil(tree, segStart, mid, queryStart, queryEnd, 2 * index + 1), 58 | getMaxUtil(tree, mid + 1, segEnd, queryStart, queryEnd, 2 * index + 2)); 59 | } 60 | 61 | int getMax(RangeMaxST* tree, int start, int end) { 62 | // Check for error conditions. 63 | if (start > end || start < 0 || end > tree->n - 1) { 64 | printf("Invalid Input.\n"); 65 | return -999999; 66 | } 67 | return getMaxUtil(tree, 0, tree->n - 1, start, end, 0); 68 | } 69 | 70 | int updateUtil(RangeMaxST* tree, int segStart, int segEnd, int ind, int val, int index) { 71 | // Update index lies outside the range of current segment. 72 | // So minimum will not change. 73 | if (ind < segStart || ind > segEnd) { 74 | return tree->segArr[index]; 75 | } 76 | 77 | // If the input index is in range of this node, then update the 78 | // value of the node and its children 79 | 80 | if (segStart == segEnd) { 81 | if (segStart == ind) { // Index value need to be updated. 82 | tree->segArr[index] = val; 83 | return val; 84 | } else { 85 | return tree->segArr[index]; // index value is not changed. 86 | } 87 | } 88 | 89 | int mid = (segStart + segEnd) / 2; 90 | 91 | // Current node value is updated with min. 92 | tree->segArr[index] = max(updateUtil(tree, segStart, mid, ind, val, 2 * index + 1), 93 | updateUtil(tree, mid + 1, segEnd, ind, val, 2 * index + 2)); 94 | 95 | // Value of diff is propagated to the parent node. 96 | return tree->segArr[index]; 97 | } 98 | 99 | void update(RangeMaxST* tree, int ind, int val) { 100 | // Check for error conditions. 101 | if (ind < 0 || ind > tree->n - 1) { 102 | printf("Invalid Input.\n"); 103 | return; 104 | } 105 | 106 | // Update the values in segment tree 107 | updateUtil(tree, 0, tree->n - 1, ind, val, 0); 108 | } 109 | 110 | int main() { 111 | int arr[] = {1, 8, 2, 7, 3, 6, 4, 5}; 112 | RangeMaxST *tree = createRangeMaxST(arr, 8); 113 | printf("Max value in the range(1, 5): %d\n", getMax(tree, 1, 5)); 114 | printf("Max value in the range(2, 7): %d\n", getMax(tree, 2, 7)); 115 | printf("Max value of all the elements: %d\n", getMax(tree, 0, sizeof(arr)/sizeof(int) - 1)); 116 | update(tree, 2, 9); 117 | printf("Max value in the range(1, 5): %d\n", getMax(tree, 1, 5)); 118 | printf("Max value of all the elements: %d\n", getMax(tree, 0, sizeof(arr)/sizeof(int) - 1)); 119 | return 0; 120 | } 121 | 122 | /* 123 | Max value in the range(1, 5): 8 124 | Max value in the range(2, 7): 7 125 | Max value of all the elements: 8 126 | Max value in the range(1, 5): 9 127 | Max value of all the elements: 9 128 | */ -------------------------------------------------------------------------------- /Tree/rmqST.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | typedef struct RmqST { 7 | int* segArr; 8 | int n; 9 | }RmqST; 10 | 11 | int min(int a, int b) { 12 | return (a < b)? a : b; 13 | } 14 | 15 | int constructST(RmqST* tree, int input[], int start, int end, int index) { 16 | // Store it in current node of the segment tree and return 17 | if (start == end) { 18 | tree->segArr[index] = input[start]; 19 | return input[start]; 20 | } 21 | 22 | // If there are more than one elements, 23 | // then traverse left and right subtrees 24 | // and store the minimum of values in current node. 25 | int mid = (start + end) / 2; 26 | tree->segArr[index] = min(constructST(tree, input, start, mid, index * 2 + 1), 27 | constructST(tree, input, mid + 1, end, index * 2 + 2)); 28 | return tree->segArr[index]; 29 | } 30 | 31 | RmqST* createRmqST(int input[], int n) { 32 | RmqST* tree = (RmqST*)malloc(sizeof(RmqST)); 33 | // Height of segment tree. 34 | int x = ceil(log(n)/log(2)); 35 | //Maximum size of segment tree 36 | int maxSize = 2 * pow(2, x) - 1; 37 | // Allocate memory for segment tree 38 | tree->segArr = (int*) malloc(sizeof(int) *maxSize); 39 | tree->n = n; 40 | constructST(tree, input, 0, n - 1, 0); 41 | return tree; 42 | } 43 | 44 | int getMinUtil(RmqST* tree, int segStart, int segEnd, int queryStart, int queryEnd, int index) { 45 | if (queryStart <= segStart && segEnd <= queryEnd) // complete overlapping case. 46 | { 47 | return tree->segArr[index]; 48 | } 49 | 50 | if (segEnd < queryStart || queryEnd < segStart) // no overlapping case. 51 | { 52 | return 99999; 53 | } 54 | 55 | // Segment tree is partly overlaps with the query range. 56 | int mid = (segStart + segEnd) / 2; 57 | return min(getMinUtil(tree, segStart, mid, queryStart, queryEnd, 2 * index + 1), 58 | getMinUtil(tree, mid + 1, segEnd, queryStart, queryEnd, 2 * index + 2)); 59 | } 60 | 61 | int getMin(RmqST* tree, int start, int end) { 62 | // Check for error conditions. 63 | if (start > end || start < 0 || end > tree->n - 1) { 64 | printf("Invalid Input.\n"); 65 | return 99999; 66 | } 67 | return getMinUtil(tree, 0, tree->n - 1, start, end, 0); 68 | } 69 | 70 | int updateUtil(RmqST* tree, int segStart, int segEnd, int ind, int val, int index) { 71 | // Update index lies outside the range of current segment. 72 | // So minimum will not change. 73 | if (ind < segStart || ind > segEnd) { 74 | return tree->segArr[index]; 75 | } 76 | 77 | // If the input index is in range of this node, then update the 78 | // value of the node and its children 79 | 80 | if (segStart == segEnd) { 81 | if (segStart == ind) { // Index value need to be updated. 82 | tree->segArr[index] = val; 83 | return val; 84 | } else { 85 | return tree->segArr[index]; // index value is not changed. 86 | } 87 | } 88 | 89 | int mid = (segStart + segEnd) / 2; 90 | 91 | // Current node value is updated with min. 92 | tree->segArr[index] = min(updateUtil(tree, segStart, mid, ind, val, 2 * index + 1), 93 | updateUtil(tree, mid + 1, segEnd, ind, val, 2 * index + 2)); 94 | 95 | // Value of diff is propagated to the parent node. 96 | return tree->segArr[index]; 97 | } 98 | 99 | void update(RmqST* tree, int ind, int val) { 100 | // Check for error conditions. 101 | if (ind < 0 || ind > tree->n - 1) { 102 | printf("Invalid Input.\n"); 103 | return; 104 | } 105 | 106 | // Update the values in segment tree 107 | updateUtil(tree, 0, tree->n - 1, ind, val, 0); 108 | } 109 | 110 | int main() { 111 | int arr[] = {2, 3, 1, 7, 12, 5}; 112 | int n = 6; 113 | RmqST *tree = createRmqST(arr, 6); 114 | printf("Min value in the range(1, 5): %d\n", getMin(tree, 1, 5)); 115 | printf("Min value of all the elements: %d\n", getMin(tree, 0, n - 1)); 116 | 117 | update(tree, 2, -1); 118 | printf("Min value in the range(1, 5): %d\n", getMin(tree, 1, 5)); 119 | printf("Min value of all the elements: %d\n", getMin(tree, 0, n - 1)); 120 | 121 | update(tree, 5, -2); 122 | printf("Min value in the range(0, 4): %d\n", getMin(tree, 0, 4)); 123 | printf("Min value of all the elements: %d\n", getMin(tree, 0, n - 1)); 124 | } 125 | 126 | /* 127 | Min value in the range(1, 5): 1 128 | Min value of all the elements: 1 129 | Min value in the range(1, 5): -1 130 | Min value of all the elements: -1 131 | Min value in the range(0, 4): -1 132 | Min value of all the elements: -2 133 | */ 134 | -------------------------------------------------------------------------------- /LinkedList/DCLL.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct Node { 5 | int value; 6 | struct Node *next; 7 | struct Node *prev; 8 | } Node; 9 | 10 | Node* createNode(int value) { 11 | Node* node = (Node*)malloc(sizeof(Node)); 12 | node->value = value; 13 | node->next = node->prev = node; 14 | return node; 15 | } 16 | 17 | typedef struct DCLL { 18 | Node *head; 19 | } DCLL; 20 | 21 | DCLL* createDCLL() { 22 | DCLL *list = (DCLL *)malloc(sizeof(DCLL)); 23 | list->head = NULL; 24 | return list; 25 | } 26 | 27 | int insertAtHead(DCLL *list, int value) { 28 | Node *temp = createNode(value); 29 | Node *head = list->head; 30 | if (!head) { 31 | list->head = temp; 32 | } else { 33 | temp->prev = head->prev; 34 | temp->prev->next = temp; 35 | 36 | temp->next = head; 37 | head->prev = temp; 38 | 39 | list->head = temp; 40 | } 41 | return 1; 42 | } 43 | 44 | int insertAtTail(DCLL *list, int value) { 45 | Node *temp = createNode(value); 46 | Node *head = list->head; 47 | if (!head) { 48 | list->head = temp; 49 | } else { 50 | temp->prev = head->prev; 51 | temp->prev->next = temp; 52 | temp->next = head; 53 | head->prev = temp; 54 | } 55 | return 1; 56 | } 57 | 58 | int deleteFromHead(DCLL *list) { 59 | Node *head = list->head; 60 | if (!head) { 61 | printf("Empty List Error"); 62 | return -99999; 63 | } 64 | 65 | int value = head->value; 66 | if (head->next == head) { 67 | free(head); 68 | list->head = NULL; 69 | return value; 70 | } 71 | 72 | Node *tail = head->prev; 73 | Node *next = head->next; 74 | 75 | next->prev = tail; 76 | tail->next = next; 77 | free(head); 78 | list->head = next; 79 | return value; 80 | } 81 | 82 | int deleteFromTail(DCLL *list) { 83 | Node *head = list->head; 84 | if (!head) { 85 | printf("Empty List Error"); 86 | return -99999; 87 | } 88 | 89 | Node *tail = head->prev; 90 | int value = tail->value; 91 | 92 | if (tail->next == tail) { 93 | free(tail); 94 | list->head = NULL; 95 | return value; 96 | } 97 | 98 | Node *prev = tail->prev; 99 | prev->next = head; 100 | head->prev = prev; 101 | free(tail); 102 | return value; 103 | } 104 | 105 | int searchList(DCLL *list, int key) { 106 | Node *head = list->head; 107 | if (!head) 108 | return 0; 109 | 110 | Node *curr = head; 111 | 112 | do 113 | { 114 | if (curr->value == key) { 115 | return 1; 116 | } 117 | curr = curr->next; 118 | } while (curr != head); 119 | 120 | return 0; 121 | } 122 | 123 | void deleteList(DCLL *list) { 124 | Node *head = list->head; 125 | if (!head) 126 | return; 127 | 128 | Node *curr = head->next; 129 | Node *next; 130 | while (curr != head) { 131 | next = curr->next; 132 | free(curr); 133 | curr = next; 134 | } 135 | free(head); 136 | list->head = NULL; 137 | } 138 | 139 | int printList(DCLL *list) { 140 | Node *head = list->head; 141 | if (!head) 142 | return 0; 143 | Node *curr = head; 144 | do 145 | { 146 | printf("%d ", curr->value); 147 | curr = curr->next; 148 | } while (curr != head); 149 | printf("\n"); 150 | return 0; 151 | } 152 | 153 | int main1() { 154 | DCLL* list = createDCLL(); 155 | insertAtHead(list, 1); 156 | insertAtHead(list, 2); 157 | insertAtHead(list, 3); 158 | printList(list); 159 | deleteFromHead(list); 160 | printList(list); 161 | deleteList(list); 162 | printList(list); 163 | return 0; 164 | } 165 | /* 166 | 3 2 1 167 | 2 1 168 | */ 169 | 170 | int main2() { 171 | DCLL* list = createDCLL(); 172 | insertAtTail(list, 1); 173 | insertAtTail(list, 2); 174 | insertAtTail(list, 3); 175 | printList(list); 176 | return 0; 177 | } 178 | 179 | /* 180 | 1 2 3 181 | */ 182 | 183 | int main3() { 184 | DCLL* list = createDCLL(); 185 | insertAtHead(list, 1); 186 | insertAtHead(list, 2); 187 | insertAtHead(list, 3); 188 | printList(list); 189 | printf("Search list : %d\n", searchList(list, 3)); 190 | printf("Search list : %d\n", searchList(list, 6)); 191 | deleteFromTail(list); 192 | printList(list); 193 | return 0; 194 | } 195 | /* 196 | 3 2 1 197 | Search list : 1 198 | Search list : 0 199 | 3 2 200 | */ 201 | 202 | 203 | int main() { 204 | main1(); 205 | main2(); 206 | main3(); 207 | return 0; 208 | } -------------------------------------------------------------------------------- /Heap/Heap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #ifndef ERROR_VALUE 6 | #define ERROR_VALUE -99999 7 | #endif 8 | 9 | // min heap compare function. 10 | int greater(int a, int b) { 11 | return a > b; 12 | } 13 | 14 | // max heap compare function. 15 | int less(int a, int b) { 16 | return a < b; 17 | } 18 | 19 | 20 | typedef struct Heap { 21 | int capacity; 22 | int size; 23 | int *array; 24 | int(* compare)(int , int); 25 | } Heap; 26 | 27 | void proclateDown(int arr[], int position, int size, int(* compare)(int , int)) { 28 | int lChild = 2 * position + 1; 29 | int rChild = lChild + 1; 30 | 31 | int child = -1; 32 | int temp; 33 | 34 | if (lChild < size) 35 | child = lChild; 36 | 37 | if (rChild < size && compare(arr[lChild], arr[rChild])) 38 | child = rChild; 39 | 40 | if (child != -1 && compare(arr[position], arr[child])) { 41 | temp = arr[position]; 42 | arr[position] = arr[child]; 43 | arr[child] = temp; 44 | proclateDown(arr, child, size, compare); 45 | } 46 | } 47 | 48 | void proclateUp(int arr[], int position, int(* compare)(int , int)) { 49 | int parent = (position - 1) / 2; 50 | int temp; 51 | 52 | if (parent >= 0 && compare(arr[parent], arr[position])) { 53 | temp = arr[position]; 54 | arr[position] = arr[parent]; 55 | arr[parent] = temp; 56 | proclateUp(arr, parent, compare); 57 | } 58 | } 59 | 60 | void heapify(int arr[], int size, int(* compare)(int , int)) { 61 | for (int i = size/2; i >= 0; i--) 62 | proclateDown(arr, i, size, compare); 63 | } 64 | 65 | Heap* createHeap2(int arr[], int size, int(* compare)(int , int)) { 66 | Heap* hp = (Heap*) malloc(sizeof(Heap)); 67 | hp->size = hp->capacity = size; 68 | hp->array = arr; 69 | hp->compare = compare; 70 | heapify(arr, size, compare); 71 | return hp; 72 | } 73 | 74 | Heap* createHeap(int(* compare)(int , int)) { 75 | Heap* hp = (Heap*) malloc(sizeof(Heap)); 76 | hp->size = 0; 77 | hp->capacity = 100; 78 | hp->array = (int *)malloc((hp->capacity) * sizeof(int)); 79 | hp->compare = compare; 80 | return hp; 81 | } 82 | 83 | int heapRemove(Heap *hp) { 84 | if (hp->size == 0) 85 | return ERROR_VALUE; 86 | int value = hp->array[0]; 87 | hp->array[0] = hp->array[hp->size - 1]; 88 | hp->size--; 89 | proclateDown(hp->array, 0, hp->size, hp->compare); 90 | return value; 91 | } 92 | 93 | void heapAdd(Heap *hp, int value) { 94 | if (hp->size == hp->capacity) 95 | return; 96 | hp->size++; 97 | hp->array[hp->size - 1] = value; 98 | proclateUp(hp->array, hp->size - 1, hp->compare); 99 | } 100 | 101 | int heapTop(Heap *hp) { 102 | return hp->array[0]; 103 | } 104 | 105 | int heapSize(Heap *hp) { 106 | return hp->size; 107 | } 108 | 109 | int isEmpty(Heap *hp) { 110 | return hp->size == 0; 111 | } 112 | 113 | void printHeap(Heap *hp) { 114 | for (int i = 0; i < hp->size; i++) 115 | printf("%d ", hp->array[i]); 116 | printf("\n"); 117 | } 118 | 119 | void heapSort(int arr[], int size, int inc) { 120 | int(* comp )(int , int); 121 | if(inc) 122 | comp = less; // max heap for increasing. 123 | else 124 | comp = greater; // min heap for decreasing. 125 | 126 | Heap* hp = createHeap2(arr, size, comp); 127 | for (int i = size-1; i >=0; i--) 128 | arr[i] = heapRemove(hp); 129 | } 130 | 131 | int heapDelete(Heap *hp, int value) { 132 | for (int i = 0; i < hp->size; i++) { 133 | if(hp->array[i] == value){ 134 | hp->array[i] = hp->array[hp->size-1]; 135 | hp->size -= 1; 136 | proclateUp(hp->array, i, hp->compare); 137 | proclateDown(hp->array, i, hp->size, hp->compare); 138 | return 1; 139 | } 140 | } 141 | return 0; 142 | } 143 | 144 | int main0() { 145 | int a[10] = {4, 5, 3, 2, 6, 7, 10, 8, 9, 1}; 146 | Heap* hp = createHeap2(a, 10, greater);//min heap 147 | printHeap(hp); 148 | while (!isEmpty(hp)) 149 | printf("%d ", heapRemove(hp)); 150 | return 0; 151 | } 152 | 153 | /* 154 | 1 2 3 4 5 7 10 8 9 6 155 | 1 2 3 4 5 6 7 8 9 10 156 | */ 157 | 158 | void printArray(int *array, int size) { 159 | for (int i = 0; i < size; i++) 160 | printf("%d ", array[i]); 161 | printf("\n"); 162 | } 163 | 164 | int mainB() { 165 | int b[10] = {4, 5, 3, 2, 6, 7, 10, 8, 9, 1}; 166 | heapSort(b, 10, 1); // increasing 167 | printArray(b, 10); 168 | 169 | heapSort(b, 10, 0); // decreasing 170 | printArray(b, 10); 171 | return 0; 172 | } 173 | 174 | /* 175 | 1 2 3 4 5 6 7 8 9 10 176 | 10 9 8 7 6 5 4 3 2 1 177 | */ -------------------------------------------------------------------------------- /LinkedList/CLL.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | typedef struct Node { 6 | int value; 7 | struct Node *next; 8 | } Node; 9 | 10 | Node* createNode(int value) { 11 | Node* node = (Node*)malloc(sizeof(Node)); 12 | node->value = value; 13 | node->next = node; 14 | return node; 15 | } 16 | 17 | typedef struct CircularLL { 18 | Node *tail; 19 | } CircularLL; 20 | 21 | CircularLL* createCircularLL() { 22 | CircularLL *list = (CircularLL *)malloc(sizeof(CircularLL)); 23 | list->tail = NULL; 24 | return list; 25 | } 26 | 27 | int insertAtHead(CircularLL* list, int value) { 28 | Node *temp = createNode(value); 29 | Node *tail = list->tail; 30 | if (!tail) 31 | { 32 | list->tail = temp; 33 | } else { 34 | temp->next = tail->next; 35 | tail->next = temp; 36 | } 37 | return 1; 38 | } 39 | 40 | int insertAtTail(CircularLL *list, int value) { 41 | Node *temp = createNode(value); 42 | Node *tail = list->tail; 43 | if (!tail) { 44 | list->tail = temp; 45 | } else { 46 | temp->next = tail->next; 47 | tail->next = temp; 48 | list->tail = temp; 49 | } 50 | return 1; 51 | } 52 | 53 | void printList(CircularLL *list) { 54 | Node* tail = list->tail; 55 | if (!tail) 56 | return; 57 | 58 | Node *curr = tail->next; 59 | while (curr != tail) { 60 | printf("%d ", curr->value); 61 | curr = curr->next; 62 | } 63 | printf("%d \n", curr->value); 64 | } 65 | 66 | int searchList(CircularLL *list, int value) { 67 | Node* tail = list->tail; 68 | if (!tail) 69 | return 0; 70 | 71 | if (tail->value == value) 72 | return 1; 73 | 74 | Node *curr = tail->next; 75 | while (curr != tail) { 76 | if (curr->value == value) 77 | return 1; 78 | curr = curr->next; 79 | } 80 | return 0; 81 | } 82 | 83 | void deleteList(CircularLL *list) { 84 | Node *tail = list->tail; 85 | if (!tail) 86 | return; 87 | 88 | Node *curr = tail->next; 89 | free(tail); 90 | Node *next; 91 | 92 | while (curr != tail) { 93 | next = curr->next; 94 | free(curr); 95 | curr = next; 96 | } 97 | list->tail = NULL; 98 | } 99 | 100 | int deleteNode(CircularLL *list, int value) { 101 | Node *tail = list->tail; 102 | if (!tail) 103 | return 0; 104 | 105 | Node *curr = tail; 106 | Node *prev = curr; 107 | curr = curr->next; 108 | while (curr != tail) { 109 | if (curr->value == value) { 110 | prev->next = curr->next; 111 | free(curr); 112 | return 1; 113 | } 114 | prev = curr; 115 | curr = curr->next; 116 | } 117 | if (curr->value == value) { 118 | prev->next = curr->next; 119 | free(curr); 120 | list->tail = prev; 121 | return 1; 122 | } 123 | return 0; 124 | } 125 | 126 | int deleteHeadNode(CircularLL *list) { 127 | Node *tail = list->tail; 128 | if (!tail) 129 | return 0; 130 | 131 | if (tail->next == tail) { 132 | free(tail); 133 | list->tail = NULL; 134 | return 1; 135 | } 136 | Node *deleteMe = tail->next; 137 | tail->next = deleteMe->next; 138 | free(deleteMe); 139 | return 1; 140 | } 141 | 142 | CircularLL* copyListReversed(CircularLL *list) { 143 | CircularLL* l2 = createCircularLL(); 144 | Node* tail = list->tail; 145 | if (!tail) 146 | return l2; 147 | 148 | Node *curr = tail->next; 149 | while (curr != tail) { 150 | insertAtHead(l2, curr->value); 151 | curr = curr->next; 152 | } 153 | insertAtHead(l2, curr->value); 154 | return l2; 155 | } 156 | 157 | CircularLL* copyList(CircularLL *list) { 158 | CircularLL* l2 = createCircularLL(); 159 | Node* tail = list->tail; 160 | if (!tail) 161 | return l2; 162 | 163 | Node *curr = tail->next; 164 | while (curr != tail) { 165 | insertAtTail(l2, curr->value); 166 | curr = curr->next; 167 | } 168 | insertAtTail(l2, curr->value); 169 | return l2; 170 | } 171 | 172 | int main1() { 173 | CircularLL* list = createCircularLL(); 174 | insertAtHead(list, 1); 175 | insertAtHead(list, 2); 176 | insertAtHead(list, 3); 177 | printList(list); 178 | deleteHeadNode(list); 179 | printList(list); 180 | deleteList(list); 181 | printList(list); 182 | return 0; 183 | } 184 | /* 185 | 3 2 1 186 | 2 1 */ 187 | 188 | int main2() { 189 | CircularLL* list = createCircularLL(); 190 | insertAtTail(list, 1); 191 | insertAtTail(list, 2); 192 | insertAtTail(list, 3); 193 | printList(list); 194 | return 0; 195 | } 196 | 197 | /* 198 | 1 2 3 199 | */ 200 | 201 | int main3() { 202 | CircularLL* list = createCircularLL(); 203 | insertAtHead(list, 1); 204 | insertAtHead(list, 2); 205 | insertAtHead(list, 3); 206 | printList(list); 207 | printf("Search list : %d\n", searchList(list, 3)); 208 | printf("Search list : %d\n", searchList(list, 6)); 209 | deleteNode(list, 2); 210 | printList(list); 211 | return 0; 212 | } 213 | /* 214 | 3 2 1 215 | Search list : 1 216 | Search list : 0 217 | 3 1 218 | */ 219 | 220 | int main4() { 221 | CircularLL* list = createCircularLL(); 222 | insertAtHead(list, 1); 223 | insertAtHead(list, 2); 224 | insertAtHead(list, 3); 225 | printList(list); 226 | CircularLL* list2 = copyList(list); 227 | printList(list2); 228 | CircularLL* list3 = copyListReversed(list); 229 | printList(list3); 230 | return 0; 231 | } 232 | 233 | int main() { 234 | /* 235 | main1(); 236 | main2(); 237 | main3(); 238 | */ 239 | main4(); 240 | return 0; 241 | } -------------------------------------------------------------------------------- /Tree/AVLTree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct Node { 6 | int data; 7 | struct Node* left; 8 | struct Node* right; 9 | int height; 10 | }Node; 11 | 12 | Node* createNode(int d, Node* l, Node* r) { 13 | Node* node = (Node*)malloc(sizeof(Node)); 14 | node->data = d; 15 | node->left = l; 16 | node->right = r; 17 | node->height = 0; 18 | return node; 19 | } 20 | 21 | typedef struct AVLTree { 22 | Node* root; 23 | } AVLTree; 24 | 25 | AVLTree* createAVLTree() { 26 | AVLTree* tree = (AVLTree*) malloc (sizeof(AVLTree)); 27 | tree->root = NULL; 28 | return tree; 29 | } 30 | 31 | void insert(AVLTree* tree, int data); 32 | Node* insertUtil(Node* node, int data); 33 | void delete(AVLTree* tree, int data); 34 | Node* deleteUtil(Node* node, int data); 35 | void printTree(AVLTree* tree); 36 | void printTreeUtil(Node* node, char* indent, int isLeft); 37 | int max(int a, int b); 38 | Node* rightRotate(Node* x); 39 | Node* leftRotate(Node* x); 40 | Node* rightLeftRotate(Node* x); 41 | Node* leftRightRotate(Node* x); 42 | Node* findMin(Node* curr); 43 | int height(Node* n); 44 | int getBalance(Node* node); 45 | 46 | 47 | int height(Node* n) { 48 | if (n == NULL) 49 | return -1; 50 | 51 | return n->height; 52 | } 53 | 54 | int getBalance(Node* node) { 55 | return (node == NULL) ? 0 : height(node->left) - height(node->right); 56 | } 57 | 58 | int max(int x, int y) { 59 | if (x > y) 60 | return x; 61 | return y; 62 | } 63 | 64 | void insert(AVLTree* tree, int data) { 65 | tree->root = insertUtil(tree->root, data); 66 | } 67 | 68 | Node* insertUtil(Node* node, int data) { 69 | if (node == NULL) 70 | return createNode(data, NULL, NULL); 71 | 72 | if (node->data > data) 73 | node->left = insertUtil(node->left, data); 74 | else if (node->data < data) 75 | node->right = insertUtil(node->right, data); 76 | else 77 | return node; // Duplicate data not allowed 78 | 79 | node->height = max(height(node->left), height(node->right)) + 1; 80 | int balance = getBalance(node); 81 | 82 | if (balance > 1) { 83 | if (data < node->left->data) // Left Left Case 84 | return rightRotate(node); 85 | 86 | if (data > node->left->data) // Left Right Case 87 | return leftRightRotate(node); 88 | } 89 | 90 | if (balance < -1) { 91 | if (data > node->right->data) // Right Right Case 92 | return leftRotate(node); 93 | 94 | if (data < node->right->data) // Right Left Case 95 | return rightLeftRotate(node); 96 | } 97 | return node; 98 | } 99 | 100 | // Function to right rotate subtree rooted with x 101 | Node* rightRotate(Node* x) { 102 | Node* y = x->left; 103 | Node* T = y->right; 104 | 105 | // Rotation 106 | y->right = x; 107 | x->left = T; 108 | 109 | // Update heights 110 | x->height = max(height(x->left), height(x->right)) + 1; 111 | y->height = max(height(y->left), height(y->right)) + 1; 112 | 113 | // Return new root 114 | return y; 115 | } 116 | 117 | // Function to left rotate subtree rooted with x 118 | Node* leftRotate(Node* x) { 119 | Node* y = x->right; 120 | Node* T = y->left; 121 | 122 | // Rotation 123 | y->left = x; 124 | x->right = T; 125 | 126 | // Update heights 127 | x->height = max(height(x->left), height(x->right)) + 1; 128 | y->height = max(height(y->left), height(y->right)) + 1; 129 | 130 | // Return new root 131 | return y; 132 | } 133 | 134 | // Function to right then left rotate subtree rooted with x 135 | Node* rightLeftRotate(Node* x) { 136 | x->right = rightRotate(x->right); 137 | return leftRotate(x); 138 | } 139 | 140 | // Function to left then right rotate subtree rooted with x 141 | Node* leftRightRotate(Node* x) { 142 | x->left = leftRotate(x->left); 143 | return rightRotate(x); 144 | } 145 | Node* findMin(Node* curr) { 146 | Node* node = curr; 147 | if (node == NULL) 148 | return NULL; 149 | while (node->left != NULL) 150 | node = node->left; 151 | return node; 152 | } 153 | 154 | void delete(AVLTree* tree, int data) { 155 | tree->root = deleteUtil(tree->root, data); 156 | } 157 | 158 | Node* deleteUtil(Node* node, int data) { 159 | if (node == NULL) 160 | return NULL; 161 | 162 | if (node->data == data) { 163 | if (node->left == NULL && node->right == NULL) 164 | return NULL; 165 | else if (node->left == NULL) 166 | return node->right; // no need to modify height 167 | else if (node->right == NULL) 168 | return node->left; // no need to modify height 169 | else 170 | { 171 | Node* minNode = findMin(node->right); 172 | node->data = minNode->data; 173 | node->right = deleteUtil(node->right, minNode->data); 174 | } 175 | } else { 176 | if (node->data > data) 177 | node->left = deleteUtil(node->left, data); 178 | else 179 | node->right = deleteUtil(node->right, data); 180 | } 181 | 182 | node->height = max(height(node->left), height(node->right)) + 1; 183 | int balance = getBalance(node); 184 | 185 | if (balance > 1) { 186 | if (data >= node->left->data) // Left Left Case 187 | return rightRotate(node); 188 | 189 | if (data < node->left->data) // Left Right Case 190 | return leftRightRotate(node); 191 | } 192 | 193 | if (balance < -1) { 194 | if (data <= node->right->data) // Right Right Case 195 | return leftRotate(node); 196 | 197 | if (data > node->right->data) // Right Left Case 198 | return rightLeftRotate(node); 199 | } 200 | return node; 201 | } 202 | 203 | 204 | void printTreeUtil(Node* node, char* indent, int isLeft) { 205 | if (node == NULL) 206 | return; 207 | 208 | if (isLeft) { 209 | printf("%s%s", indent, "L:"); 210 | strcat(indent, "| "); 211 | } else { 212 | printf("%s%s", indent, "R:"); 213 | strcat(indent, " "); 214 | } 215 | 216 | printf("%d(%d)\n", node->data, node->height); 217 | printTreeUtil(node->left, indent, 1); 218 | printTreeUtil(node->right, indent, 0); 219 | indent[strlen(indent) - 3] = '\0'; 220 | } 221 | 222 | void printTree(AVLTree* tree) { 223 | char str[100] = ""; 224 | printTreeUtil(tree->root, str, 0); 225 | printf("\n"); 226 | } 227 | 228 | int main() { 229 | AVLTree *tree = createAVLTree(); 230 | insert(tree, 1); 231 | insert(tree, 2); 232 | insert(tree, 3); 233 | insert(tree, 4); 234 | insert(tree, 5); 235 | insert(tree, 6); 236 | insert(tree, 7); 237 | insert(tree, 8); 238 | printTree(tree); 239 | 240 | delete(tree, 5); 241 | printTree(tree); 242 | 243 | delete(tree, 1); 244 | printTree(tree); 245 | 246 | delete(tree, 2); 247 | printTree(tree); 248 | } 249 | 250 | /* 251 | R:4(3) 252 | L:2(1) 253 | | L:1(0) 254 | | R:3(0) 255 | R:6(2) 256 | L:5(0) 257 | R:7(1) 258 | R:8(0) 259 | 260 | R:4(2) 261 | L:2(1) 262 | | L:1(0) 263 | | R:3(0) 264 | R:7(1) 265 | L:6(0) 266 | R:8(0) 267 | 268 | R:4(2) 269 | L:2(1) 270 | | R:3(0) 271 | R:7(1) 272 | L:6(0) 273 | R:8(0) 274 | 275 | R:4(2) 276 | L:3(0) 277 | R:7(1) 278 | L:6(0) 279 | R:8(0) 280 | */ 281 | -------------------------------------------------------------------------------- /Tree/SPLAYTree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct Node { 6 | int data; 7 | struct Node *left; 8 | struct Node *right; 9 | struct Node *parent; 10 | } Node; 11 | 12 | typedef struct SPLAYTree { 13 | Node *root; 14 | } SPLAYTree; 15 | 16 | int find(SPLAYTree* tree, int data); 17 | void insert(SPLAYTree* tree, int data); 18 | void delete(SPLAYTree* tree, int data); 19 | void printTree(SPLAYTree* tree); 20 | void splay(SPLAYTree* tree, Node *node); 21 | 22 | void printTreeUtil(Node *node, char* indent, int isLeft); 23 | Node *rightRotate(Node *x); // Function to right rotate subtree rooted with x 24 | Node *leftRotate(Node *x); // Function to left rotate subtree rooted with x 25 | Node *getParent(Node *node); 26 | Node *findMinNode(Node *curr); 27 | 28 | Node* createNode(int d, Node *l, Node *r) { 29 | Node* node = (Node*)malloc(sizeof(Node)); 30 | node->data = d; 31 | node->left = l; 32 | node->right = r; 33 | node->parent = NULL; 34 | return node; 35 | } 36 | 37 | SPLAYTree* createSPLAYTree() { 38 | SPLAYTree* tree = (SPLAYTree*)malloc(sizeof(SPLAYTree)); 39 | tree->root = NULL; 40 | return tree; 41 | } 42 | 43 | void printTreeUtil(Node *node, char* indent, int isLeft) { 44 | if (node == NULL) 45 | return; 46 | 47 | if (isLeft) { 48 | printf("%s%s", indent, "L:"); 49 | strcat(indent, "| "); 50 | } else { 51 | printf("%s%s", indent, "R:"); 52 | strcat(indent, " "); 53 | } 54 | 55 | printf("%d\n", node->data); 56 | printTreeUtil(node->left, indent, 1); 57 | printTreeUtil(node->right, indent, 0); 58 | indent[strlen(indent) - 3] = '\0'; 59 | } 60 | 61 | void printTree(SPLAYTree* tree) { 62 | char indent[100] = ""; 63 | printTreeUtil(tree->root, indent, 0); 64 | printf("\n"); 65 | } 66 | 67 | // Function to right rotate subtree rooted with x 68 | Node *rightRotate(Node *x) { 69 | Node *y = x->left; 70 | Node *T = y->right; 71 | 72 | // Rotation 73 | y->parent = x->parent; 74 | y->right = x; 75 | x->parent = y; 76 | x->left = T; 77 | if (T != NULL) { 78 | T->parent = x; 79 | } 80 | 81 | if (y->parent != NULL && y->parent->left == x) { 82 | y->parent->left = y; 83 | } else if (y->parent != NULL && y->parent->right == x) { 84 | y->parent->right = y; 85 | } 86 | // Return new root 87 | return y; 88 | } 89 | 90 | // Function to left rotate subtree rooted with x 91 | Node *leftRotate(Node *x) { 92 | Node *y = x->right; 93 | Node *T = y->left; 94 | 95 | // Rotation 96 | y->parent = x->parent; 97 | y->left = x; 98 | x->parent = y; 99 | x->right = T; 100 | if (T != NULL) { 101 | T->parent = x; 102 | } 103 | 104 | if (y->parent != NULL && y->parent->left == x) { 105 | y->parent->left = y; 106 | } else if (y->parent != NULL && y->parent->right == x) { 107 | y->parent->right = y; 108 | } 109 | // Return new root 110 | return y; 111 | } 112 | 113 | Node *getParent(Node *node) { 114 | if (node == NULL || node->parent == NULL) { 115 | return NULL; 116 | } 117 | return node->parent; 118 | } 119 | 120 | void splay(SPLAYTree* tree, Node *node) { 121 | Node *parent, *grand; 122 | while (node != tree->root) { 123 | parent = getParent(node); 124 | grand = getParent(parent); 125 | if (parent == NULL) { // rotations had created new root, always last condition. 126 | tree->root = node; 127 | } else if (grand == NULL) { // single rotation case. 128 | if (parent->left == node) { 129 | node = rightRotate(parent); 130 | } else { 131 | node = leftRotate(parent); 132 | } 133 | } else if (grand->left == parent && parent->left == node) { // Zig Zig case. 134 | rightRotate(grand); 135 | node = rightRotate(parent); 136 | } else if (grand->right == parent && parent->right == node) { // Zag Zag case. 137 | leftRotate(grand); 138 | node = leftRotate(parent); 139 | } else if (grand->left == parent && parent->right == node) { //Zig Zag case. 140 | leftRotate(parent); 141 | node = rightRotate(grand); 142 | } else if (grand->right == parent && parent->left == node) { // Zag Zig case. 143 | rightRotate(parent); 144 | node = leftRotate(grand); 145 | } 146 | } 147 | } 148 | 149 | int find(SPLAYTree* tree, int data) { 150 | Node *curr = tree->root; 151 | while (curr != NULL) { 152 | if (curr->data == data) { 153 | splay(tree, curr); 154 | return 1; 155 | } else if (curr->data > data) 156 | curr = curr->left; 157 | else 158 | curr = curr->right; 159 | } 160 | return 0; 161 | } 162 | 163 | void insert(SPLAYTree* tree, int data) { 164 | Node *newNode = createNode(data, NULL, NULL); 165 | if (tree->root == NULL) { 166 | tree->root = newNode; 167 | return; 168 | } 169 | 170 | Node *node = tree->root; 171 | Node *parent = NULL; 172 | while (node != NULL) { 173 | parent = node; 174 | if (node->data > data) 175 | node = node->left; 176 | else if (node->data < data) 177 | node = node->right; 178 | else { 179 | splay(tree, node); // duplicate insertion not allowed but splaying for it. 180 | return; 181 | } 182 | } 183 | 184 | newNode->parent = parent; 185 | if (parent->data > data) 186 | parent->left = newNode; 187 | else 188 | parent->right = newNode; 189 | 190 | splay(tree, newNode); 191 | } 192 | 193 | Node *findMinNode(Node *curr) { 194 | Node *node = curr; 195 | if (node == NULL) 196 | return NULL; 197 | 198 | while (node->left != NULL) 199 | node = node->left; 200 | 201 | return node; 202 | } 203 | 204 | void delete(SPLAYTree* tree, int data) { 205 | Node *node = tree->root; 206 | Node *parent = NULL; 207 | Node *next = NULL; 208 | while (node != NULL) { 209 | if (node->data == data) { 210 | parent = node->parent; 211 | if (node->left == NULL && node->right == NULL) 212 | next = NULL; 213 | else if (node->left == NULL) 214 | next = node->right; 215 | else if (node->right == NULL) 216 | next = node->left; 217 | 218 | if (node->left == NULL || node->right == NULL) { 219 | if (node == tree->root) { 220 | tree->root = next; 221 | return; 222 | } 223 | 224 | if (parent->left == node) 225 | parent->left = next; 226 | else 227 | parent->right = next; 228 | 229 | if (next != NULL) 230 | next->parent = parent; 231 | break; 232 | } 233 | 234 | Node *minNode = findMinNode(node->right); 235 | data = minNode->data; // new data to be deleted. 236 | node->data = data; 237 | node = node->right; 238 | } else if (node->data > data) { 239 | parent = node; 240 | node = node->left; 241 | } else { 242 | parent = node; 243 | node = node->right; 244 | } 245 | } 246 | splay(tree, parent); // Splaying for the parent of the node deleted. 247 | } 248 | 249 | int main() { 250 | SPLAYTree *tree = createSPLAYTree(); 251 | insert(tree, 5); 252 | insert(tree, 4); 253 | insert(tree, 6); 254 | insert(tree, 3); 255 | insert(tree, 2); 256 | insert(tree, 1); 257 | insert(tree, 3); 258 | printTree(tree); 259 | 260 | printf("Value 2 found: %d\n", find(tree, 2)); 261 | delete(tree, 2); 262 | delete(tree, 5); 263 | printTree(tree); 264 | } 265 | 266 | /* 267 | R:3 268 | L:2 269 | | L:1 270 | R:6 271 | L:4 272 | | R:5 273 | 274 | Value 2 found: 1 275 | R:4 276 | L:3 277 | | L:1 278 | R:6 279 | */ -------------------------------------------------------------------------------- /LinkedList/DLL.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | typedef struct Node { 6 | int value; 7 | struct Node *next; 8 | struct Node *prev; 9 | } Node; 10 | 11 | Node* createNode(int value, Node* next, Node* prev) { 12 | Node *node = (Node*)malloc(sizeof(Node)); 13 | node->value = value; 14 | node->next = next; 15 | node->prev = prev; 16 | return node; 17 | } 18 | 19 | typedef struct DLL { 20 | Node *head; 21 | Node *tail; 22 | } DLL; 23 | 24 | DLL *createDLL() { 25 | DLL *list = (DLL*)malloc(sizeof(DLL)); 26 | list->head = NULL; 27 | list->tail = NULL; 28 | return list; 29 | } 30 | 31 | void insertAtHead(DLL *list, int value) { 32 | Node *temp = createNode(value, NULL, NULL); 33 | Node *head = list->head; 34 | if (!head) { 35 | list->head = temp; 36 | list->tail = temp; 37 | } else { 38 | temp->next = head; 39 | head->prev = temp; 40 | list->head = temp; 41 | } 42 | } 43 | 44 | void sortedInsert(DLL *list, int value) { 45 | Node *temp = createNode(value, NULL, NULL); 46 | Node *curr = list->head; 47 | if (!curr) /*first element*/ 48 | { 49 | list->head = temp; 50 | return; 51 | } 52 | 53 | if (curr->value >= value) /*at the begining*/ 54 | { 55 | temp->next = curr; 56 | curr->prev = temp; 57 | list->head = temp; 58 | return; 59 | } 60 | 61 | while (curr->next && curr->next->value < value) /*traversal*/ 62 | { 63 | curr = curr->next; 64 | } 65 | 66 | if (!curr->next) /*at the end*/ 67 | { 68 | temp->prev = curr; 69 | curr->next = temp; 70 | list->tail = temp; 71 | } 72 | else /*all other*/ 73 | { 74 | temp->next = curr->next; 75 | temp->next->prev = temp; 76 | temp->prev = curr; 77 | curr->next = temp; 78 | } 79 | } 80 | 81 | /* Print A singly linked list */ 82 | void printList(DLL *list) { 83 | Node *head = list->head; 84 | while (head != NULL) { 85 | printf("%d ", head->value); 86 | head = head->next; 87 | } 88 | printf("\n"); 89 | } 90 | 91 | void printReverseListUtil(Node *head) { 92 | if (!head) 93 | return; 94 | 95 | printReverseListUtil(head->next); 96 | printf("%d ", head->value); 97 | } 98 | 99 | void printReverseList(DLL *list) { 100 | Node *head = list->head; 101 | printReverseListUtil(head); 102 | } 103 | 104 | /* Reverse a doubly linked List iteratively */ 105 | void reverseList(DLL *list) { 106 | Node *curr = list->head; 107 | list->tail = list->head; 108 | Node *tempNode; 109 | 110 | while (curr) { 111 | tempNode = curr->next; 112 | curr->next = curr->prev; 113 | curr->prev = tempNode; 114 | 115 | if (!curr->prev) { 116 | list->head = curr; 117 | return; 118 | } 119 | curr = curr->prev; 120 | } 121 | return; 122 | } 123 | 124 | void deleteList(DLL *list) { 125 | Node *curr = list->head; 126 | Node *next; 127 | while (curr != NULL) { 128 | next = curr->next; 129 | free(curr); 130 | curr = next; 131 | } 132 | list->head = NULL; 133 | list->tail = NULL; 134 | } 135 | 136 | void deleteFirstNode(DLL *list) { 137 | if(list->head == NULL) 138 | return; 139 | 140 | Node *deleteMe = list->head; 141 | list->head = list->head->next; 142 | if(list->head != NULL) 143 | list->head->prev = NULL; 144 | else 145 | list->tail = NULL; 146 | 147 | free(deleteMe); 148 | } 149 | 150 | void deleteNode(DLL *list, int value) { 151 | Node *curr = list->head; 152 | Node *next; 153 | Node *deleteMe; 154 | if(curr == NULL) 155 | return; 156 | 157 | if (curr->value == value) /*first node*/ 158 | { 159 | deleteMe = curr; 160 | curr = curr->next; 161 | if(curr) 162 | curr->prev = NULL; 163 | else 164 | list->tail = NULL; 165 | 166 | list->head = curr; 167 | free(deleteMe); 168 | return; 169 | } 170 | 171 | while (curr->next != NULL) { 172 | if (curr->next->value == value) { 173 | deleteMe = curr->next; 174 | curr->next = curr->next->next; 175 | if (curr->next) 176 | curr->next->prev = curr; 177 | else 178 | list->tail = curr; 179 | free(deleteMe); 180 | return; 181 | } 182 | curr = next; 183 | next = next->next; 184 | } 185 | } 186 | 187 | void removeDuplicates(DLL *list) { 188 | Node *curr = list->head; 189 | Node *deleteMe; 190 | while (curr) { 191 | if ((curr->next) && curr->value == curr->next->value) { 192 | deleteMe = curr->next; 193 | curr->next = deleteMe->next; 194 | if(curr->next) 195 | curr->next->prev = curr; 196 | else 197 | list->tail = curr; 198 | free(deleteMe); 199 | } else { 200 | curr = curr->next; 201 | } 202 | } 203 | } 204 | 205 | DLL *copyListReversed(DLL *list) { 206 | DLL *list2 = createDLL(); 207 | Node *head = list->head; 208 | while (head) { 209 | insertAtHead(list2, head->value); 210 | head = head->next; 211 | } 212 | return list2; 213 | } 214 | 215 | 216 | void insertAtTail(DLL *list, int value) { 217 | Node *temp = createNode(value, NULL, NULL); 218 | Node *tail = list->tail; 219 | if (!tail) { 220 | list->head = temp; 221 | list->tail = temp; 222 | } else { 223 | temp->prev = list->tail; 224 | list->tail->next = temp; 225 | list->tail = temp; 226 | } 227 | } 228 | 229 | DLL *copyList(DLL *list) { 230 | DLL *list2 = createDLL(); 231 | Node *head = list->head; 232 | while (head) { 233 | insertAtTail(list2, head->value); 234 | head = head->next; 235 | } 236 | return list2; 237 | } 238 | /* 239 | DLL *copyListReversed(DLL *list) { 240 | DLL *list2 = createDLL(); 241 | Node *head = list->head; 242 | if (!head) 243 | return list2; 244 | 245 | Node *head2 = createNode(head->value, NULL, NULL); 246 | Node *tail2 = head2; 247 | Node *temp = NULL; 248 | head = head->next; 249 | 250 | while (head) { 251 | temp = createNode(head->value, NULL, NULL); 252 | temp->next = head2; 253 | head2->prev = temp; 254 | head2 = temp; 255 | head = head->next; 256 | } 257 | list2->head = head2; 258 | list2->tail = tail2; 259 | return list2; 260 | } 261 | 262 | DLL *copyList(DLL *list) { 263 | Node *head2 = NULL; 264 | Node *tail2 = NULL; 265 | Node *tempNode = NULL; 266 | Node *head = list->head; 267 | DLL *list2 = createDLL(); 268 | 269 | if (!head) 270 | return list2; 271 | 272 | head2 = createNode(head->value, NULL, NULL); 273 | tail2 = head2; 274 | head = head->next; 275 | 276 | while (head) { 277 | tempNode = createNode(head->value, NULL, NULL); 278 | tail2->next = tempNode; 279 | tempNode->prev = tail2; 280 | tail2 = tempNode; 281 | head = head->next; 282 | } 283 | 284 | list2->head = head2; 285 | list2->tail = tail2; 286 | return list2; 287 | } 288 | */ 289 | int compareListUtil(Node *head1, Node *head2) { 290 | if (head1 == NULL && head2 == NULL) 291 | return 1; 292 | else if ((head1 == NULL) || (head2 == NULL) || (head1->value != head2->value)) 293 | return 0; 294 | else 295 | return compareListUtil(head1->next, head2->next); 296 | } 297 | 298 | int compareList(DLL* list1, DLL* list2) { 299 | return compareListUtil(list1->head, list2->head); 300 | } 301 | 302 | int compareList2(DLL* list1, DLL* list2) { 303 | Node *head1 = list1->head; 304 | Node *head2 = list2->head; 305 | while (head1 != NULL && head2 != NULL) { 306 | if (head1->value != head2->value) 307 | return 0; 308 | head1 = head1->next; 309 | head2 = head2->next; 310 | } 311 | if (head1 == NULL && head2 == NULL) 312 | return 1; 313 | return 0; 314 | } 315 | 316 | int main1() { 317 | DLL* list = createDLL(); 318 | insertAtHead(list, 1); 319 | insertAtHead(list, 2); 320 | insertAtHead(list, 3); 321 | printList(list); 322 | deleteFirstNode(list); 323 | printList(list); 324 | return 0; 325 | } 326 | /* 327 | 3 2 1 328 | 2 1 329 | */ 330 | 331 | int main2() { 332 | DLL* list = createDLL(); 333 | sortedInsert(list, 1); 334 | sortedInsert(list, 3); 335 | sortedInsert(list, 2); 336 | sortedInsert(list, 4); 337 | printList(list); 338 | return 0; 339 | } 340 | /* 341 | 1 2 3 4 342 | */ 343 | int main3() { 344 | DLL* list = createDLL(); 345 | insertAtHead(list, 1); 346 | insertAtHead(list, 2); 347 | insertAtHead(list, 3); 348 | printList(list); 349 | deleteNode(list, 2); 350 | printList(list); 351 | return 0; 352 | } 353 | /* 354 | 3 2 1 355 | 3 1 356 | */ 357 | 358 | int main4() { 359 | DLL* list = createDLL(); 360 | sortedInsert(list, 1); 361 | sortedInsert(list, 2); 362 | sortedInsert(list, 3); 363 | sortedInsert(list, 1); 364 | sortedInsert(list, 2); 365 | sortedInsert(list, 3); 366 | printList(list); 367 | removeDuplicates(list); 368 | printList(list); 369 | return 0; 370 | } 371 | /* 372 | 1 1 2 2 3 3 373 | 1 2 3 374 | */ 375 | 376 | int main5() { 377 | DLL* list = createDLL(); 378 | insertAtHead(list, 1); 379 | insertAtHead(list, 2); 380 | insertAtHead(list, 3); 381 | printList(list); 382 | reverseList(list); 383 | printList(list); 384 | return 0; 385 | } 386 | /* 387 | 3 2 1 388 | 1 2 3 389 | */ 390 | 391 | int main6() { 392 | DLL* list = createDLL(); 393 | insertAtHead(list, 1); 394 | insertAtHead(list, 2); 395 | insertAtHead(list, 3); 396 | printList(list); 397 | DLL* list2 = copyListReversed(list); 398 | printList(list2); 399 | DLL* list3 = copyList(list); 400 | printList(list3); 401 | return 0; 402 | } 403 | /* 404 | 3 2 1 405 | 1 2 3 406 | 3 2 1 407 | */ 408 | 409 | int main() { 410 | main1(); 411 | main2(); 412 | main3(); 413 | main4(); 414 | main5(); 415 | main6(); 416 | return 0; 417 | } --------------------------------------------------------------------------------