├── Arrays ├── Kadane's algorithm │ ├── Kadane's algorithm.cpp │ ├── Kadane-csharp.cs │ ├── Kadanes_Algorithm.py │ ├── Kth-smallest-element.cpp │ └── Reverseanarrayingroupsofgivensize.java ├── Second-Largest-Element-in-an-array │ └── secondLargestElement.cpp └── Two Pointer Algorithm │ └── Container-With-Most-Water.cpp ├── Backtracking ├── N-Queen.cpp └── Sudoku Solver.cpp ├── Bit Manipulation ├── Bit_Concept │ ├── Bit_Explaination.txt │ ├── No_Of_Set_Bits.cpp │ └── Power_Of_2.cpp ├── Kernighans-JAVA.java ├── binary string to integer │ ├── README.md │ └── bin_to_int.cpp └── check if k'th bit is set or not │ ├── README.md │ └── main.cpp ├── Disjointset ├── disjointset-cpp.cpp ├── disjointset-explaination.txt ├── disjointset-python.py ├── disjointset-unionrank-python.py └── example.txt ├── Dynamic Programming ├── 0-1 Knapsack (DP) │ └── 0-1Knapsack(DP).cpp ├── Binomial_Coefficient.cpp ├── Coin Change Problem (DP) │ └── coinChange.cpp ├── EditDistance(DP) │ └── EditDistance(DP).cpp ├── Egg Dropping Puzzle(DP) │ ├── Egg Dropping Puzzle C++(dp).cpp │ └── Egg Dropping Puzzle C++(DP).TXT ├── Fibonacci │ ├── fibonacci.js │ └── fibonacci_DP.txt ├── GoldmineProblem.cpp ├── Longest Increasing Subsequence(DP) │ └── LongestIncSubsequence(DP).cpp ├── Longest Palindromic Subsequence │ └── longest_palindromic_subsequence.cpp ├── Matrix Chain DP │ └── Matrix_chain_DP_Memoization.cpp ├── Minimum Count │ └── Minimum Count.cpp └── nthCatalanNumber │ └── nthCatalanNumber.cpp ├── Graphs ├── BFS-Traversal │ ├── BFS-C++.cpp │ ├── BFS-Python │ │ ├── BFS-python3.py │ │ └── Graph_Traversal_BFS_Python3.py │ ├── BFS_javascript.js │ └── GraphTraversal_BFS.java ├── Count Connected Components │ ├── In Directed Graph │ │ ├── Kosaraju's Algorithm │ │ │ ├── connected components dfs-C++.cpp │ │ │ └── connected_component_using_dfs.py │ │ └── Tarjan's Algorithm │ │ │ └── explaination.txt │ └── In Undirected Graph │ │ └── Count_connected_components-C++.cpp ├── DFS-Traversal │ ├── DFSTraversal_Java.java │ ├── DFS_CPP.cpp │ ├── DFS_Traversal_C++.cpp │ ├── DFS_javascript.js │ └── Graph_Traversal_DFS_Python3.py ├── Detect Cycle in a Directed Graph │ ├── Detect Cycle in a Directed Graph-CPP.cpp │ ├── directed_graph_cycle_detection.cpp │ └── explaination.txt ├── Dijkstra │ ├── Algo explanation.txt │ ├── Dijkstra - Java.java │ ├── Dijkstra_Python3.py │ └── dijkstra algorithm.cpp ├── Euler Circuit │ └── euler_circuit.cpp ├── Finding Bridges │ ├── ConnectedComponent │ │ └── Kosaraju's.cpp │ └── Finding_Bridges.cpp ├── Floyd Warshall │ ├── Floyd_Warshall_Rust.rs │ └── floydwarshall.cpp ├── Kruskal’s Minimum Spanning Tree │ ├── Kruskal's Algorithm-c++.cpp │ ├── Kruskal- Java.java │ ├── Kruskal’s Minimum Spanning Tree- Python.py │ └── Kruskal’s Minimum Spanning Tree.md ├── Prims Algorithm │ └── PRIMS.CPP ├── Topological Sort │ ├── Topological_Sorting_Python3.py │ └── topological_sort.cpp └── bellman ford │ ├── Bellman-ford-CPP.cpp │ ├── algorithm explanation.txt │ ├── code.cpp │ └── explaination.txt ├── Greedy_Algorithms ├── Activity Selection │ └── Activity_Selection.cpp ├── Huffman Encoading │ └── Huffman_Encoading.cpp ├── Interval Scheduling Maximization │ ├── intervalSchedulingMaximization.js │ └── ism.txt ├── Knapsack Problem │ └── fractional_knapsack.cpp └── Weighted Job Scheduling │ └── Weighted Job Scheduling.cpp ├── Linked Lists ├── Copy List With Random Pointers │ ├── QUESTION.md │ └── solution.cpp ├── Delete_LL │ ├── delete_linkedlist-C++.cpp │ └── explaination.txt ├── Detect_Loop_linked-list │ ├── Detect-loop-ll-CPP.cpp │ └── explaination.md ├── LL Insertion │ ├── Insert_at_nth+position-java.java │ ├── LL_Insertion_nth_pos.c │ ├── README.md │ └── optimized_Insertion_LL.cpp ├── Max Node │ └── MaxOfLinkedList.c ├── Merge Two Sorted Lists │ ├── Merge Two Lists.cpp │ └── Question.md ├── Reverse LL │ ├── Reversing Linked List.md │ ├── Reversing-Linkedlist-C++.cpp │ └── reverse.c ├── Reverse_a_linked_list_in_group_of_size_k.cpp ├── Search_element_LL │ ├── Search_element-C++.cpp │ └── explaination.txt └── Swap Nodes in Doubly Linked List.cpp ├── Matrices └── Spiral Print │ └── Matrix_SpiralPrint.java ├── Miscellaneous Algorithms ├── Divide and Conquer │ ├── get-majority-element theory.md │ └── get-majority-element.py ├── FibonacciSearch.cpp └── Tower of Hanoi │ ├── towers_of_hanoi-cpp │ └── towers_of_hanoi-python.py ├── Number Theory ├── GCD │ ├── gcd - java.java │ ├── gcd.cpp │ └── greatest-common-divisor.py ├── LCM │ ├── Least Common Multiple - CPP.cpp │ ├── LeastCommonMultiple.js │ └── least-common-multiple.py ├── Modular Inverse │ └── ModularInverse.cpp └── Prime Numbers │ ├── SieveEratostenes.cpp │ └── fermatPrimalityTest.cpp ├── README.md ├── Resource Allocation Algorithm └── Banker's Algorithm │ └── Banker's_Algo.c ├── Scheduling Algorithm ├── FCFS algo c++ │ └── main.cpp └── ShortestJobFirst │ └── ShortestJobFirst.c ├── Searching ├── Binary Search │ ├── Binary Search - JavaScript.js │ ├── Binary Search - Ruby.rb │ ├── Binary Search-CPP.cpp │ ├── Binary Search-CSharp.cs │ ├── Binary Search-Java.java │ ├── Binary Search-Python.py │ ├── BinarySearchPHP.php │ ├── Binary_Search-C.c │ └── Binary_Search-Dart.dart ├── Exponential Search │ ├── Exponential.cpp │ ├── Exponential.py │ └── ExponentialSearch.java ├── Fibonacci-search │ ├── Explaination.txt │ ├── fibonacci_search.cpp │ └── fibonacci_search.py ├── Interpolation-Search │ ├── Interpolation-Search-CPP.cpp │ ├── Interpolation-Search.java │ └── Interpolation-Search.txt ├── Jump Search │ ├── JumpSearch.cs │ ├── JumpSearch.java │ └── jumpSearch.cpp ├── Linear Search │ ├── Linear Search - Ruby.rb │ ├── LinearSearch.cpp │ ├── LinearSearch.py │ ├── Linear_Search- C.c │ ├── Linear_Search-C#.cs │ ├── Linearsearch_adiksha20.java │ └── explanation.txt └── Ternary-Search │ ├── Ternary-Search-CPP.cpp │ ├── Ternary-Search-Java.java │ └── Ternary-Search.txt ├── Stacks ├── Balanced-Braces.cpp ├── Infix_to_Postfix-C.c ├── MatchingParenthesis-C.c ├── NextGreaterElement.py ├── PostFix Evaluation │ └── PostfixEvaluation-C.c ├── Prefix Evaluation │ └── PrefixEvaluation └── ReverseStack │ └── ReverseStack.cpp ├── Strings ├── Check String is Palindrome or not │ ├── String Palindrome - C#.cs │ └── String Palindrome - C++.cpp ├── KMP-substring-match-algo │ ├── algo.cpp │ └── explaination.txt ├── Lexicographically-smallest-largest │ ├── Lexicographically smallest largest substring - CPP.cpp │ ├── Lexicographically-smallest-largest-python.py │ └── Lexicographically-smallest-largest-python.txt ├── Longest-common-subsequence │ └── longest_common_subsequence-C++.cpp ├── Naive-pattern-matching-algorithm │ └── naive_string_matching-C++.cpp └── Robin Karp Algorithm │ ├── Robin Karp - CPP.cpp │ └── Robin-Karp_Python3.py └── Trees ├── Binary search Tree └── insertion in BST.cpp ├── Boundary_Traversal └── boundary_traversal_tree.py ├── Complete binary tree └── complete_bt- java.java ├── Delete Node └── deletingnode.cpp ├── Diagonal Traversal └── Diagonal Traversal-C++.cpp ├── Diameter of Binary Tree └── diameter.java ├── Fenwick_Tree └── Fenwick_Python3.py ├── Inorder_Traversal ├── AVL.c ├── Inorder Traversal-Java.java ├── Inorder Traversal_C++.cpp ├── InorderTraversal_Python3.py ├── inorder.c └── iteratve_inorder.cpp ├── LevelOrderTraversal ├── LevelOrderTraversal.cpp └── LevelOrderTraversal.java ├── Max Height Tree ├── README.md └── maxHeightC++.cpp ├── Postorder Traversal ├── Postorder Traversal - Java.java └── Postorder_Traversal_cpp.cpp ├── Postorder_Traversal ├── Postorder_Traversal_python3.py └── iterative_postorder.cpp └── Preorder_Traversal ├── Preorder_Traversal_python3.py └── iterative_preorder.cpp /Arrays/Kadane's algorithm/Kadane's algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int maxSubArraySum(int a[], int size) 5 | { 6 | int max_so_far = 0, max_ending_here = 0; 7 | 8 | for (int i = 0; i < size; i++) 9 | { 10 | max_ending_here = max_ending_here + a[i]; 11 | if (max_so_far < max_ending_here) 12 | max_so_far = max_ending_here; 13 | 14 | if (max_ending_here < 0) 15 | max_ending_here = 0; 16 | } 17 | return max_so_far; 18 | } 19 | 20 | 21 | int main() 22 | { 23 | int n; 24 | cin>>n; 25 | int a[n]; 26 | for(int i=0;i>a[i]; 29 | } 30 | int max_sum = maxSubArraySum(a, n); 31 | cout << "Maximum contiguous sum is " << max_sum; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Arrays/Kadane's algorithm/Kadane-csharp.cs: -------------------------------------------------------------------------------- 1 | namespace Kadanes 2 | { 3 | internal class Program 4 | { 5 | internal static int MaxSubArraySum(int[] collection) 6 | { 7 | var maxSum = 0; 8 | var currentSum = 0; 9 | 10 | for (int i = 0; i < collection.Length; i++) 11 | { 12 | currentSum = currentSum + collection.ElementAt(i); 13 | if (maxSum < currentSum) 14 | maxSum = currentSum; 15 | 16 | if (currentSum < 0) 17 | currentSum = 0; 18 | } 19 | return maxSum; 20 | } 21 | 22 | static void Main() 23 | { 24 | Console.WriteLine("Write an array using ',' as a delimiter. For example - 1, 2, 3"); 25 | var userInput = Console.ReadLine(); 26 | var collection = userInput.Split(',').Select(x => int.Parse(x)).ToArray(); 27 | var maxSubArraySum = MaxSubArraySum(collection); 28 | Console.WriteLine($"Maximum subarray sum: {maxSubArraySum}"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Arrays/Kadane's algorithm/Kadanes_Algorithm.py: -------------------------------------------------------------------------------- 1 | def maxSubArray(nums): 2 | maximumSum = -1e8 3 | currentSum = 0 4 | for i in range(0, len(nums)): 5 | currentSum = currentSum + nums[i] 6 | if(currentSum > maximumSum): 7 | maximumSum = currentSum 8 | if(currentSum < 0): 9 | currentSum = 0 10 | 11 | return maximumSum 12 | 13 | if __name__ == "__main__": 14 | print(maxSubArray([3, 1, 9, -4, 2, -7, 1])) -------------------------------------------------------------------------------- /Arrays/Kadane's algorithm/Kth-smallest-element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int randomPartition(int arr[], int l, int r); 7 | 8 | int kthSmallest(int arr[], int l, int r, int k) 9 | { 10 | 11 | if (k > 0 && k <= r - l + 1) 12 | { 13 | // find a position for random partition 14 | int pos = randomPartition(arr, l, r); 15 | 16 | // if this pos gives the kth smallest element, then return 17 | if (pos-l == k-1) 18 | return arr[pos]; 19 | 20 | // else recurse for the left and right half accordingly 21 | if (pos-l > k-1) 22 | return kthSmallest(arr, l, pos-1, k); 23 | return kthSmallest(arr, pos+1, r, k-pos+l-1); 24 | } 25 | 26 | return INT_MAX; 27 | } 28 | 29 | void swap(int *a, int *b) 30 | { 31 | int temp = *a; 32 | *a = *b; 33 | *b = temp; 34 | } 35 | 36 | // partitioning the array along the pivot 37 | int partition(int arr[], int l, int r) 38 | { 39 | int x = arr[r], i = l; 40 | for (int j = l; j <= r - 1; j++) 41 | { 42 | if (arr[j] <= x) 43 | { 44 | swap(&arr[i], &arr[j]); 45 | i++; 46 | } 47 | } 48 | swap(&arr[i], &arr[r]); 49 | return i; 50 | } 51 | 52 | // finding the pivot element and partition the array along that 53 | int randomPartition(int arr[], int l, int r) 54 | { 55 | int n = r-l+1; 56 | int pivot = rand() % n; 57 | swap(&arr[l + pivot], &arr[r]); 58 | return partition(arr, l, r); 59 | } 60 | 61 | int main() 62 | { 63 | // ios_base::sync_with_stdio(false); 64 | // cin.tie(NULL); 65 | 66 | int test_case; 67 | cin>>test_case; 68 | while(test_case--) 69 | { 70 | int number_of_elements; 71 | cin>>number_of_elements; 72 | int a[number_of_elements]; 73 | for(int i=0;i>a[i]; 76 | } 77 | int k; 78 | cin>>k; 79 | cout< 2 | using namespace std; 3 | 4 | // time complexity: O(n) 5 | void secondLargest(int arr[], int n){ 6 | int largest=arr[0]; 7 | for(int i=0;ilargest) largest=arr[i]; 9 | } 10 | int count=0; 11 | for(int i=0;i1){ 15 | cout<<"Second largest element: "<>n; 29 | int arr[n]; 30 | 31 | cout<<"Enter array elements :"; 32 | for(int i=0;i>arr[i]; 35 | } 36 | 37 | cout<<"Using iterative method: \n"; 38 | secondLargest(arr,n); 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Arrays/Two Pointer Algorithm/Container-With-Most-Water.cpp: -------------------------------------------------------------------------------- 1 | // C++ code for Max 2 | // Container-with-most-water 3 | 4 | // Problem Statement 5 | 6 | // Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). 7 | // n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). 8 | // Find two lines, which, together with the x-axis forms a container, such that the container contains the most water. 9 | 10 | // Input: height = [1,8,6,2,5,4,8,3,7] 11 | // Output: 49 12 | // Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49. 13 | 14 | // Example 2: 15 | 16 | // Input: height = [1,1] 17 | // Output: 1 18 | 19 | 20 | 21 | // Complexity Analysis: 22 | 23 | // Time Complexity: O(n). 24 | // As only one traversal of the array is required, so time complexity is O(n). 25 | // Space Complexity: O(1). 26 | // No extra space is required, so space complexity is constant. 27 | 28 | 29 | 30 | 31 | #include 32 | using namespace std; 33 | int maxArea(int A[], int len) 34 | { 35 | int l = 0; 36 | int r = len -1; 37 | int area = 0; 38 | 39 | while (l < r) 40 | { 41 | // Calculating the max area 42 | area = max(area, min(A[l],A[r]) * (r - l)); 43 | 44 | if (A[l] < A[r]) 45 | l += 1; 46 | 47 | else 48 | r -= 1; 49 | } 50 | return area; 51 | } 52 | 53 | void takeinput(int arr[],int s) 54 | { 55 | for(int i=0;i>arr[i]; 58 | } 59 | } 60 | 61 | // Driver code 62 | int main() 63 | { 64 | 65 | // Variables used 66 | int s1,s2; 67 | 68 | // Input 1 69 | cout<<"Enter inputs size of 1st Array : "; 70 | cin>>s1; 71 | int a[s1]; 72 | cout<<"\nEnter inputs size for 1st Array : "; 73 | takeinput(a,s1); 74 | 75 | // Input 2 76 | 77 | cout<<"\nEnter inputs size of 2nd Array : "; 78 | cin>>s2; 79 | int b[s2]; 80 | cout<<"\nEnter inputs size for 2nd Array : "; 81 | takeinput(b,s2); 82 | 83 | // Answer 84 | cout<<"\nAnswer\n"; 85 | int len1 = sizeof(a) / sizeof(a[0]); 86 | cout << maxArea(a, len1); 87 | 88 | int len2 = sizeof(b) / sizeof(b[0]); 89 | cout << endl << maxArea(b, len2); 90 | } 91 | 92 | -------------------------------------------------------------------------------- /Backtracking/N-Queen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool isSafe(int board[][10], int row, int col, int n) //This function is to check whether queen can be placed safely or not 4 | { 5 | for(int i=0;i=0 && j>=0;i--,j--) 13 | { 14 | if(board[i][j] ==1) 15 | { 16 | return false; 17 | } 18 | } 19 | for(int i=row,j=col;i=0;i++,j--) 20 | { 21 | if(board[i][j] ==1) 22 | { 23 | return false; 24 | } 25 | } 26 | return true; 27 | } 28 | bool nQueen(int board[][10], int col, int n) 29 | { 30 | if(col>=n) 31 | { 32 | for(int i=0;i>n; 61 | bool check = nQueen(board,0,n); //function calling 62 | if(check == false) 63 | cout<<-1; 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /Bit Manipulation/Bit_Concept/Bit_Explaination.txt: -------------------------------------------------------------------------------- 1 | Bit manipulation 2 | 3 | 1>. counting the number of the set bits in the binary representations : 4 | in binary representation 0 are called -non set bit 5 | 1- set bits 6 | to count the set bit we take bitwise with 1 and with the 0th bit and every time make a right shift to the number untill it become zero 7 | if 0th bit is 1 then on bitwise and will give 1 8 | Time Complexity: since the number of iteration is atmost number of bits(32 or 64) there for the time complexity is O(1) 9 | 10 | 2>.Power of 2: 11 | a number is power of two when number of set bit is 1 12 | time Complexity : O(1) as just counting the number of set Bits 13 | 14 | -------------------------------------------------------------------------------- /Bit Manipulation/Bit_Concept/No_Of_Set_Bits.cpp: -------------------------------------------------------------------------------- 1 | /// no of set bits in a number in cpp 2 | /* This is basically to count the no of set bit(1) in binary representation of the number */ 3 | #include 4 | using namespace std; 5 | int main() 6 | { 7 | int n,count=0,temp; 8 | cout<<"enter the number "; 9 | cin>>n; 10 | /* the idea is if the 0th bit is set then taking and bitwise and with 1 will give 1. to count all set bits we 11 | take bitwise right shift until the number become 0 */ 12 | temp=n; 13 | while(n) 14 | { 15 | if(n&1) 16 | count++; 17 | n=n>>1; 18 | } 19 | cout<<"No of set bits in "< 3 | using namespace std; 4 | int main() 5 | { 6 | int n,count=0,temp; 7 | cout<<"enter the number "; 8 | cin>>n; 9 | temp=n; 10 | while(n) 11 | { 12 | if(n&1) 13 | count++; 14 | n=n>>1; 15 | } 16 | if(count==1) 17 | cout< 8 | Space: ![formula](https://render.githubusercontent.com/render/math?math=O(1)) 9 | 10 | 11 | -------------------------------------------------------------------------------- /Bit Manipulation/binary string to integer/bin_to_int.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int stob(string &s){ 5 | int len = s.length(); 6 | int decimal = 0; 7 | int base = 1; 8 | for(int i=len-1; i>=0; i--){ 9 | if(s[i] == '1') 10 | decimal += base; 11 | base *= 2; 12 | } 13 | return decimal; 14 | } 15 | int main(){ 16 | string s = "101"; 17 | cout< 5 | Unset bit = 0 6 | 7 | ## Implementation 8 | I implemented two methods to check id k'th bit is set or not. 9 |
    10 |
  1. Left shift method
  2. 11 |
  3. Right Shift method
  4. 12 |
13 | 14 | Time and space complexities for both the methods is same :
15 | Time: ![formula](https://render.githubusercontent.com/render/math?math=O(1))
16 | Space: ![formula](https://render.githubusercontent.com/render/math?math=O(1)) 17 | 18 | 19 | -------------------------------------------------------------------------------- /Bit Manipulation/check if k'th bit is set or not/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //To check if kth bit in a binary representation of a number n is SET(1) or RESET(0) 5 | 6 | //Left shift method 7 | bool isSet1(int n, int k){ 8 | if((1 << (k-1)) & n ) 9 | return true; 10 | return false; 11 | } 12 | //Right shift method 13 | bool isSet2(int n, int k){ 14 | if((n >> (k-1)) & 1 ) 15 | return true; 16 | return false; 17 | } 18 | 19 | int main(){ 20 | cout<1->2 // 1 is parent of 0 and 2 is parent of 1 -------------------------------------------------------------------------------- /Dynamic Programming/0-1 Knapsack (DP)/0-1Knapsack(DP).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | int t; 7 | cin>>t; 8 | while(t--) 9 | { 10 | int n; 11 | cin>>n; 12 | int w; 13 | cin>>w; 14 | int p[n+1]; 15 | p[0] = 0; 16 | int wt[n+1]; 17 | wt[0] = 0; 18 | for(int i=1;i>p[i]; 21 | } 22 | for(int i=1;i>wt[i]; 25 | } 26 | /*for(int i=1;i 2 | using namespace std; 3 | int min(int a, int b); 4 | int binomialCoeff(int n, int k) 5 | { 6 | int C[n + 1][k + 1]; 7 | int i, j; 8 | for (i = 0; i <= n; i++) 9 | { 10 | for (j = 0; j <= min(i, k); j++) 11 | { 12 | if (j == 0 || j == i) 13 | C[i][j] = 1; 14 | else 15 | C[i][j] = C[i - 1][j - 1] + 16 | C[i - 1][j]; 17 | } 18 | } 19 | 20 | return C[n][k]; 21 | } 22 | int min(int a, int b) 23 | { 24 | return (a < b) ? a : b; 25 | } 26 | int main() 27 | { 28 | int n,k; 29 | cin>>n>>k; 30 | cout << "Value of C[" << n << "][" 31 | << k << "] is " << binomialCoeff(n, k); 32 | } 33 | -------------------------------------------------------------------------------- /Dynamic Programming/Coin Change Problem (DP)/coinChange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a 'value', we have to find the number of ways to make change for 'value' cents, 3 | if we have infinite supply of each of Si (1<= i<= N) valued coins. 4 | */ 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | int coinChange(vector& arr, int val, int n, vector>& T) 11 | { 12 | if (val == 0) 13 | return T[n][val] = 1; 14 | if (n == 0) 15 | return 0; 16 | if (T[n][val] != -1) 17 | return T[n][val]; 18 | if (arr[n - 1] <= val) { 19 | return T[n][val] = coinChange(arr, val - arr[n - 1], n, T) + coinChange(arr, val, n - 1, T); 20 | } 21 | else 22 | return T[n][val] = coinChange(arr, val, n - 1, T); 23 | } 24 | int main() 25 | { 26 | int n=4; 27 | int value=10; 28 | vector S = { 2, 5, 3, 6 }; 29 | vector> T(n + 1, vector(value + 1, -1)); //2d vector 30 | int result = coinChange(S, value, n, T); 31 | cout< 7 | #include 8 | using namespace std; 9 | int minimum(int a,int b,int c) 10 | { 11 | int result = min(min(a,b),c); 12 | return result; 13 | } 14 | int main() 15 | { 16 | int t; 17 | cin>>t; 18 | while(t--) 19 | { 20 | int p,q; 21 | cin>>p>>q; 22 | char s1[p]; 23 | char s2[q]; 24 | cin>>s1>>s2; 25 | //cout< 2 | using namespace std; 3 | int static dp[51][51]; 4 | int solve(int e,int f) 5 | { 6 | if(e==1) 7 | return f; 8 | if(f==0||f==1) 9 | return f; 10 | if(dp[e][f]!=-1) 11 | return dp[e][f]; 12 | int minimum=INT_MAX; 13 | for(int k=1;k<=f;k++) 14 | { 15 | //max due to worst case 16 | int tempans=1+max(solve(e-1,k-1),solve(e,f-k)); 17 | //minimum attempts 18 | minimum=min(minimum,tempans); 19 | } 20 | return dp[e][f]=minimum; 21 | } 22 | int main() 23 | { 24 | int t; 25 | cin>>t; 26 | while(t--) 27 | { 28 | int e,f; 29 | cin>>e>>f; 30 | memset(dp,-1,sizeof(dp)); 31 | cout< 2 | using namespace std; 3 | 4 | // Gold mine problem using dynamic programming for calculating maximum gold that can be collected 5 | // allowed moves in the 2-D grid are right, right-down, right-up 6 | int goldMine(vector> a, int m, int n) 7 | { 8 | vector> dp(m,vector(n)); 9 | int ma=0; 10 | 11 | for (int i=n-1; i>=0; i--) 12 | { 13 | for (int j=0; j>m>>n; 47 | 48 | vector> a(m,vector (n)); 49 | for(int i=0;i>a[i][j]; 54 | } 55 | } 56 | cout< 7 | #include 8 | using namespace std; 9 | int main() 10 | { 11 | int t; 12 | cin>>t; 13 | while(t--) 14 | { 15 | int n; 16 | cin>>n; 17 | if(n==1) 18 | cout<<1<>arr[i]; 29 | } 30 | int max = INT_MIN; 31 | for(int i=1;i 4 | #include 5 | 6 | int max (int x, int y) { return (x > y)? x : y; } 7 | 8 | int lps(char *str) 9 | { 10 | int n = strlen(str); 11 | int i, j, cl; 12 | int L[n][n]; 13 | 14 | for (i = 0; i < n; i++) 15 | L[i][i] = 1; 16 | 17 | for (cl=2; cl<=n; cl++) 18 | { 19 | for (i=0; i 3 | using namespace std; 4 | int An[4][4]={0}; 5 | int mcm(int R[],int i,int j) 6 | { 7 | int a,b,c=INT_MAX,k; 8 | if(i==j) 9 | return 0; 10 | if(An[i][j]==0) 11 | { 12 | for(k=i;k>n; 28 | int R[n+1]; 29 | //int An[n][n]={0}; 30 | for(i=0;i<=n;i++) 31 | { 32 | cin>>R[i]; 33 | } 34 | i=mcm(R,1,4); 35 | cout< 10 | using namespace std; 11 | 12 | int minCount(int n) 13 | { 14 | int dp[n+1]; 15 | dp[0]=0; 16 | dp[1]=1; 17 | dp[2]=2; 18 | dp[3]=3; 19 | for(int i=4;i<=n;i++) 20 | { 21 | dp[i]=i; 22 | for(int x=1;x<=i;x++) 23 | { 24 | int temp=x*x; 25 | 26 | if(temp>i) 27 | break; 28 | else{ 29 | dp[i]=min(dp[i],1+dp[i-temp]); 30 | 31 | } 32 | } 33 | } 34 | return dp[n]; 35 | 36 | 37 | } 38 | 39 | // Driver code 40 | 41 | int main(){ 42 | int n; 43 | cin>>n; 44 | cout< 2 | using namespace std; 3 | 4 | 5 | unsigned long int catalanDP(unsigned int n) 6 | { 7 | 8 | unsigned long int catalan[n+1]; 9 | 10 | 11 | catalan[0] = catalan[1] = 1; 12 | 13 | 14 | for (int i=2; i<=n; i++) 15 | { 16 | catalan[i] = 0; 17 | for (int j=0; j 12 | #include 13 | #include 14 | 15 | using namespace std; 16 | 17 | void bfs(int start, vector > &graph, vector &vis, vector &lev, vector &parent) 18 | { 19 | vis[start]=true; 20 | lev[start]=0; 21 | 22 | queue q; 23 | q.push(start); 24 | 25 | while(!q.empty()) 26 | { 27 | int u = q.front(); 28 | q.pop(); 29 | 30 | for(auto v: graph[u]) 31 | { 32 | if(!vis[v]) 33 | { 34 | vis[v]=true; 35 | lev[v]=lev[u]+1; 36 | parent[v]=u; 37 | 38 | q.push(v); 39 | } 40 | } 41 | } 42 | } 43 | 44 | int main() 45 | { 46 | int n,m; 47 | cin>>n>>m; 48 | 49 | vector > graph(n); 50 | vector vis(n); 51 | vector lev(n), parent(n,-1); 52 | 53 | for(int i=0;i>u>>v; 57 | u--; 58 | v--; 59 | graph[u].push_back(v); 60 | graph[v].push_back(u); 61 | } 62 | 63 | parent[0]=0; 64 | bfs(0,graph,vis,lev,parent); //start bfs from 0 65 | 66 | for(int i=0;i a, b, c, d, e, f 13 | Edges -> (a,c), (b,c), (b,e), (c,d), (c,e) 14 | """ 15 | graph = { "a" : set(["c"]), 16 | "b" : set(["c","e"]), 17 | "c" : set(["a", "b", "d", "e"]), 18 | "d" : set(["c"]), 19 | "e" : set(["b","c"]), 20 | "f" : set([]) 21 | } 22 | 23 | 24 | """ 25 | The BFS for above can go in following way 26 | 27 | If the start Node is "b" 28 | b c e a d 29 | b e c a d 30 | b c e d a 31 | b e c d a 32 | Notice that all three output are correct 33 | 34 | If the start Node is "f" 35 | Since no other node are connected 36 | only "f" will be printed 37 | """ 38 | 39 | def bfs(graph, start): 40 | """ 41 | Returns a list of nodes visited in 42 | breadth first manner from the start node 43 | """ 44 | path = [] 45 | # Track the visited and unvisited nodes using queue 46 | seen, queue = set([start]), [start] 47 | while queue: 48 | # Take the 1st element in the queue and explore it 49 | vertex = queue.pop(0) 50 | path.append(vertex) 51 | for node in graph[vertex]: 52 | if node not in seen: 53 | seen.add(node) 54 | queue.append(node) 55 | return path 56 | 57 | for node in "abcdef": 58 | print("BFS for Node {} : {}".format(node,bfs(graph, node))) 59 | -------------------------------------------------------------------------------- /Graphs/BFS-Traversal/BFS_javascript.js: -------------------------------------------------------------------------------- 1 | // BFS 2 | 3 | // Graph Implementation 4 | class Graph { 5 | constructor() { 6 | this.adjacencyList = {}; 7 | } 8 | addVertex(vertex) { 9 | if (!this.adjacencyList[vertex]) { 10 | this.adjacencyList[vertex] = []; 11 | } 12 | } 13 | addEdge(source, destination) { 14 | if (!this.adjacencyList[source]) { 15 | this.addVertex(source); 16 | } 17 | if (!this.adjacencyList[destination]) { 18 | this.addVertex(destination); 19 | } 20 | this.adjacencyList[source].push(destination); 21 | this.adjacencyList[destination].push(source); 22 | } 23 | removeEdge(source, destination) { 24 | this.adjacencyList[source] = this.adjacencyList[source].filter(vertex => vertex !== destination); 25 | this.adjacencyList[destination] = this.adjacencyList[destination].filter(vertex => vertex !== source); 26 | } 27 | removeVertex(vertex) { 28 | while (this.adjacencyList[vertex]) { 29 | const adjacentVertex = this.adjacencyList[vertex].pop(); 30 | this.removeEdge(vertex, adjacentVertex); 31 | } 32 | delete this.adjacencyList[vertex]; 33 | } 34 | printGraph(){ 35 | var i 36 | for (i in this.adjacencyList){ 37 | console.log(i , " : " , this.adjacencyList[i]); 38 | } 39 | } 40 | } 41 | 42 | // Adding BFS function to the Graph using Queue 43 | Graph.prototype.bfs = function(start) { 44 | const queue = [start]; 45 | const result = []; 46 | const visited = {}; 47 | visited[start] = true; 48 | let currentVertex; 49 | while (queue.length) { 50 | currentVertex = queue.shift(); 51 | result.push(currentVertex); 52 | this.adjacencyList[currentVertex].forEach(neighbor => { 53 | if (!visited[neighbor]) { 54 | visited[neighbor] = true; 55 | queue.push(neighbor); 56 | } 57 | }); 58 | } 59 | return result; 60 | } 61 | 62 | 63 | // Driver Code 64 | g = new Graph() 65 | g.addVertex(1) 66 | g.addVertex(2) 67 | g.addVertex(3) 68 | g.addVertex(4) 69 | 70 | g.addEdge(1,2) 71 | g.addEdge(2,3) 72 | g.addEdge(1,3) 73 | g.addEdge(3,4) 74 | 75 | console.log("Graph Adjacency List") 76 | g.printGraph() 77 | var node; 78 | for (node = 1; node<=4; node++){ 79 | console.log("BFS from " + node + " => "+ g.bfs(node)) 80 | } 81 | 82 | /* 83 | Output 84 | 85 | Graph Adjacency List 86 | 1 : [ 2, 3 ] 87 | 2 : [ 1, 3 ] 88 | 3 : [ 2, 1, 4 ] 89 | 4 : [ 3 ] 90 | BFS from 1 => 1,2,3,4 91 | BFS from 2 => 2,1,3,4 92 | BFS from 3 => 3,2,1,4 93 | BFS from 4 => 4,3,2,1 94 | */ -------------------------------------------------------------------------------- /Graphs/BFS-Traversal/GraphTraversal_BFS.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | public static void main(String args[] ) throws Exception { 5 | 6 | Scanner scn=new Scanner(System.in); 7 | 8 | int n = scn.nextInt(); // number of nodes 9 | int e = scn.nextInt(); // number of edges 10 | 11 | HashMap[] graph=new HashMap[n]; 12 | for(int i=0;i(); 25 | graph[a-1].put(b-1,1); 26 | } 27 | 28 | if(graph[b-1]!=null) 29 | { 30 | if(!graph[b-1].containsKey(a-1)) 31 | graph[b-1].put(a-1,1); 32 | } 33 | else 34 | { 35 | graph[b-1]=new HashMap(); 36 | graph[b-1].put(a-1,1); 37 | } 38 | } 39 | 40 | // BFS 41 | HashMap processed =new HashMap<>(); 42 | 43 | LinkedList Queue=new LinkedList<>(); 44 | Queue.add(0); 45 | processed.put(0,true); 46 | 47 | while(!Queue.isEmpty()) 48 | { 49 | int node=Queue.remove(0); 50 | 51 | if(graph[node]!=null) 52 | { 53 | System.out.println(node+1); 54 | for(int key: graph[node].keySet()) 55 | { 56 | if(!processed.containsKey(key)) 57 | { 58 | Queue.add(key); 59 | processed.put(key,true); 60 | } 61 | } 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Graphs/Count Connected Components/In Directed Graph/Kosaraju's Algorithm/connected components dfs-C++.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | DFS algorithm on graphs using adjacency lists 3 | complexity: O(n+m) where n is the number of vertices and m is the number of edges 4 | 5 | This algorithm runs a dfs traversal on a graph and find the number of connected components. It additionally finds the parents and depth of the vertices. 6 | */ 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | void dfs(int start, vector > &graph, vector &vis, vector &lev, vector &parent) 13 | { 14 | vis[start]=true; 15 | 16 | for(auto u: graph[start]) 17 | { 18 | if(!vis[u]) 19 | { 20 | dfs(u, graph, vis,lev, parent); 21 | parent[u]= start; 22 | lev[u]= lev[start]+1; 23 | } 24 | } 25 | } 26 | 27 | int main() 28 | { 29 | int n, m, components=0; 30 | cin>>n>>m; 31 | 32 | vector > graph(n); 33 | vector vis(n); 34 | vector lev(n), parent(n,-1); 35 | 36 | for(int i=0;i>u>>v; 40 | u--; 41 | v--; 42 | graph[u].push_back(v); 43 | graph[v].push_back(u); 44 | } 45 | 46 | for(int i=0;i 6 | using namespace std; 7 | void DFS(int** G, int n, int sv, bool* visited, vector& ans) 8 | { 9 | visited[sv] = true; 10 | ans.push_back(sv); 11 | for(int i = 0; i < n; i++) 12 | { 13 | if( i == sv) 14 | continue; 15 | if(G[sv][i] == 1) 16 | { 17 | if(visited[i] == false) 18 | DFS(G, n, i, visited, ans); 19 | } 20 | } 21 | } 22 | vector > ConnectedComponents(int** G, int V) 23 | { 24 | vector > components; 25 | bool* visited = new bool[V]; 26 | for(int i = 0; i < V; i++) 27 | { 28 | visited[i] = false; 29 | } 30 | 31 | for(int i = 0; i < V; i++) 32 | { 33 | if( visited[i] == false ) 34 | { 35 | vector ans; 36 | DFS(G, V, i, visited, ans); 37 | components.push_back(ans); 38 | } 39 | } 40 | delete [] visited; 41 | return components; 42 | } 43 | int main() 44 | { 45 | int V, E; 46 | cout<<"Enter the number of vertices and edges:\n"; 47 | cin >> V >> E; 48 | int** G = new int*[V]; 49 | for(int i = 0; i < V; i++) 50 | { 51 | G[i] = new int[V]; 52 | for(int j = 0; j < V; j++) 53 | { 54 | G[i][j] = 0; 55 | } 56 | } 57 | cout<<"Enter the edges:\n"; 58 | int a, b; 59 | for(int i = 0; i < E; i++) 60 | { 61 | cin>>a>>b; 62 | G[a][b] = 1; 63 | G[b][a] = 1; 64 | } 65 | 66 | vector > components = ConnectedComponents(G, V); 67 | vector >::iterator it1 = components.begin(); 68 | cout<<"Total connected components = "< comp = *it1; 73 | vector::iterator it2 = comp.begin(); 74 | while( it2 != comp.end() ) 75 | { 76 | cout<<*it2<<" "; 77 | it2++; 78 | } 79 | if(it1 <= components.end()-2) 80 | cout< 2 | #include 3 | #define MAX 20 4 | typedef struct Q 5 | { 6 | int data[MAX]; 7 | int R, F; 8 | }Q; 9 | 10 | int A[MAX][MAX]; 11 | int visited[MAX]; 12 | int vertices; 13 | 14 | void DFS(int p) 15 | { 16 | 17 | cout <<"\t"<< p; 18 | 19 | visited[p] = 1; 20 | for(int i=0;i>vertices; 38 | 39 | 40 | cout <<"\nEnter no of edges :"; 41 | cin >> no_of_edges; 42 | for (i = 0;i < no_of_edges;i++) 43 | { 44 | cout <<"\nEnter an edge (u,v) :"; 45 | cin >> vi >> vj; 46 | insert(vi, vj); 47 | insert(vj, vi); 48 | } 49 | } 50 | 51 | 52 | int main() 53 | { 54 | int n; 55 | cout <<"ENTER VALUES"<< endl; 56 | readgraph(); 57 | cout <<"\n----DFS----"<< endl; 58 | cout <<"Starting Node No. : "; 59 | cin >> n; 60 | DFS(n); 61 | return 0; 62 | } 63 | 64 | 65 | -------------------------------------------------------------------------------- /Graphs/DFS-Traversal/DFS_Traversal_C++.cpp: -------------------------------------------------------------------------------- 1 | //Depth First Search (a graph traversal algorithm) implementation in C++ 2 | #include 3 | using namespace std; 4 | 5 | void DFS(int** G, int n, int sv, bool* visited) 6 | { 7 | cout<> V >> E; 24 | int** G = new int*[V]; 25 | for(int i = 0; i < V; i++) 26 | { 27 | G[i] = new int[V]; 28 | for(int j = 0; j < V; j++) 29 | { 30 | G[i][j] = 0; 31 | } 32 | } 33 | int a, b; 34 | cout<<"Enter the edges of the directed graph:\n"; 35 | for(int i = 0; i < E; i++) 36 | { 37 | cin>>a>>b; 38 | G[a][b] = 1; 39 | } 40 | bool* visited = new bool[V]; 41 | for(int i = 0; i < V; i++) 42 | { 43 | visited[i] = false; 44 | } 45 | cout<<"Enter the source vertex: "; 46 | cin>>s; 47 | cout<<"Traversal order :"< a, b, c, d, e, f 13 | Edges -> (a,c), (b,c), (b,e), (c,d), (c,e) 14 | """ 15 | graph = { "a" : set(["c"]), 16 | "b" : set(["c","e"]), 17 | "c" : set(["a", "b", "d", "e"]), 18 | "d" : set(["c"]), 19 | "e" : set(["b","c"]), 20 | "f" : set([]) 21 | } 22 | 23 | 24 | """ 25 | The DFS for above can go in following way 26 | 27 | If the start Node is "a" 28 | a c b e d 29 | a c d b e 30 | a c e b d 31 | Notice that all three output are correct 32 | 33 | If the start Node is "f" 34 | Since no other node are connected 35 | only "f" will be printed 36 | """ 37 | 38 | def dfs(graph, start, visited = None, path = None): 39 | """ 40 | Returns a list of nodes visited in 41 | depth first manner from the start node 42 | """ 43 | if visited is None: 44 | visited = set() 45 | if path is None: 46 | path = [] 47 | visited.add(start) 48 | path.append(start) 49 | for next in graph[start] - visited: 50 | dfs(graph, next, visited, path) 51 | return path 52 | 53 | for node in "abcdef": 54 | print("DFS for Node {} : {}".format(node,dfs(graph, node))) 55 | -------------------------------------------------------------------------------- /Graphs/Detect Cycle in a Directed Graph/explaination.txt: -------------------------------------------------------------------------------- 1 | Approach: Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is from a node to itself (self-loop) or one of its ancestors in the tree produced by DFS. In the following graph, there are 3 back edges, marked with a cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph. 2 | 3 | 4 | For a disconnected graph, Get the DFS forest as output. To detect cycle, check for a cycle in individual trees by checking back edges. 5 | Algorithm: 6 | Create the graph using the given number of edges and vertices. 7 | Create a recursive function that initializes the current index or vertex, visited, and recursion stack. 8 | Mark the current node as visited and also mark the index in recursion stack. 9 | Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true. 10 | If the adjacent vertices are already marked in the recursion stack then return true. 11 | Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false. 12 | -------------------------------------------------------------------------------- /Graphs/Dijkstra/Algo explanation.txt: -------------------------------------------------------------------------------- 1 | Algorithm: 2 | Let the node at which we are starting be called the initial node. Let the distance of node Y be the distance from the initial node to Y. Dijkstra's algorithm will assign some initial distance values and will try to improve them step by step. 3 | 1. Mark all nodes unvisited. Create a set of all the unvisited nodes called the unvisited set. 4 | 2. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. Set the initial node as current.[14] 5 | 3. For the current node, consider all of its unvisited neighbours and calculate their tentative distances through the current node. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbour B has length 2, then the distance to B through A will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. Otherwise, the current value will be kept. 6 | 4. When we are done considering all of the unvisited neighbours of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again. 7 | 5. If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished. 8 | 6. Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as the new "current node", and go back to step 3. 9 | -------------------------------------------------------------------------------- /Graphs/Euler Circuit/euler_circuit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem statement 3 | Eulerian Path is a path in graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path which starts and ends on the same vertex. The task is to find that there exists the Euler Path or circuit or none in given undirected graph with V vertices and adjacency list adj. 4 | 5 | Example 1: 6 | 7 | Input: 8 | 9 | Output: 2 10 | Explanation: The graph contains Eulerian circuit 11 | Example 2: 12 | 13 | Input: 14 | 15 | Output: 1 16 | Explanation: The graph contains Eulerian path. 17 | 18 | 19 | Your Task: 20 | You don't need to read or print anything. Your task is to complete the function isEulerCircuilt() which takes number of vertices in the graph denoting as V and adjacency list of graph denoting as adj and returns 1 if graph contains Eulerian Path, 2 if graph contains Eulerian Circuit 0 otherwise. 21 | 22 | 23 | Expected Time Complexity: O(V+E) where E is the number of edges in graph. 24 | Expected Space Complexity: O(V) 25 | 26 | 27 | Constraints: 28 | 1 ≤ V, E ≤ 104 29 | */ 30 | #include 31 | using namespace std; 32 | 33 | // } Driver Code Ends 34 | class Solution { 35 | public: 36 | void dfs(int node, vector adj[], vector& vis){ 37 | vis[node] = true; 38 | for(int& el:adj[node]){ 39 | if(!vis[el]) dfs(el,adj,vis); 40 | } 41 | } 42 | int isEularCircuit(int V, vectoradj[]){ 43 | // Code here 44 | 45 | vector vis(V,false); 46 | vector degree(V,0); 47 | 48 | int oddCount = 0; 49 | int node = -1; 50 | for(int i=0; i 0) return 0; 63 | } 64 | 65 | if(oddCount == 0) return 2; 66 | else if(oddCount == 2) return 1; 67 | else return 0; 68 | 69 | } 70 | }; 71 | 72 | // { Driver Code Starts. 73 | int main(){ 74 | int tc; 75 | cin >> tc; 76 | while(tc--){ 77 | int V, E; 78 | cin >> V >> E; 79 | vectoradj[V]; 80 | for(int i = 0; i < E; i++){ 81 | int u, v; 82 | cin >> u >> v; 83 | adj[u].push_back(v); 84 | adj[v].push_back(u); 85 | } 86 | Solution obj; 87 | int ans = obj.isEularCircuit(V, adj); 88 | cout << ans <<"\n"; } 89 | return 0; 90 | } // } Driver Code Ends -------------------------------------------------------------------------------- /Graphs/Finding Bridges/ConnectedComponent/Kosaraju's.cpp: -------------------------------------------------------------------------------- 1 | //This Algorithm is used for counting strongly connected components in directed graph 2 | #include 3 | using namespace std; 4 | void dfs(vectorarr[],int par, stack&st,bool visited[]) 5 | { 6 | visited[par]=true; 7 | 8 | for(int child : arr[par]) 9 | { 10 | 11 | if(!visited[child]) 12 | { 13 | dfs(arr,child,st,visited); 14 | } 15 | } 16 | st.push(par); //storing parents in stack 17 | } 18 | void dfs_util(int par,vectortranspose[],bool visited[]) 19 | { 20 | 21 | visited[par]=true; 22 | for(int child : transpose[par]) 23 | { 24 | if(!visited[child]) 25 | dfs_util(child,transpose,visited); 26 | } 27 | } 28 | int Kosaraju(int V,vectorarr[]) 29 | { 30 | stackst; 31 | bool visited[V]; 32 | memset(visited,false,sizeof(visited)); 33 | 34 | for(int i=0;itranspose[V]; 48 | for(int i=0;i>n>>m; //Enter number of vertex and number of edges 76 | vectorarr[n]; 77 | 78 | while(m--) 79 | { 80 | 81 | int a,b; 82 | cin>>a>>b; 83 | arr[a].push_back(b); //Creating directed graph 84 | } 85 | 86 | cout<<"Number of Strongly Connected Components\n"; 87 | cout< 9 | using namespace std; 10 | int vis[1001]; 11 | int in[1001],low[10001]; 12 | vectorarr[1001]; 13 | int timer; 14 | 15 | void dfs(int node,int par) 16 | { 17 | vis[node]=1; 18 | in[node]=low[node]=timer; 19 | timer++; 20 | 21 | for(int child : arr[node]) 22 | { 23 | if(child==par) 24 | continue; 25 | 26 | if(vis[child]==1 ) 27 | { 28 | //Back Edge.... 29 | low[node]=min(low[node],in[child]); 30 | 31 | } 32 | 33 | else 34 | { 35 | 36 | dfs(child,node); 37 | 38 | if(low[child]>in[node]) 39 | cout<>n>>m; 55 | // 56 | cout<<"Enter Vertex\n"; 57 | while(m--) 58 | { 59 | int a,b; 60 | cin>>a>>b; 61 | arr[a].push_back(b); 62 | arr[b].push_back(a); 63 | } 64 | 65 | dfs(1,-1); 66 | } 67 | -------------------------------------------------------------------------------- /Graphs/Floyd Warshall/floydwarshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define INF 1e7 4 | void floydwarshall(int m[][100],int n) 5 | { 6 | int dist[n][n]; 7 | 8 | for(int i=0;i>t; 42 | while(t--) 43 | { 44 | int n; 45 | cin>>n; 46 | int m[100][100]; 47 | for(int i=0;i>m[i][j]; 52 | } 53 | } 54 | floydwarshall(m,n); 55 | 56 | /*for(int i=0;i 2 | using namespace std; 3 | 4 | class Edge 5 | { 6 | public: 7 | int src; //source 8 | int dest; //destination 9 | int weight; 10 | }; 11 | bool comp(Edge e1,Edge e2) 12 | { 13 | return e1.weight> V >> E; 55 | Edge* edges=new Edge[E]; 56 | for(int i=0;i>s>>d>>w; 60 | edges[i].src=s; 61 | edges[i].dest=d; 62 | edges[i].weight=w; 63 | 64 | } 65 | Edge* output=krus(edges,V,E); 66 | 67 | for(int i=0;i 2 | #define I 32767 3 | using namespace std; 4 | int main() 5 | {int cost[8][8]={{I,I,I,I,I,I,I,I}, 6 | {I,I,25,I,I,I,5,I}, 7 | {I,25,I,12,I,I,I,10}, 8 | {I,I,12,I,8,I,I,I}, 9 | {I,I,I,8,I,16,I,14}, 10 | {I,I,I,I,16,I,20,18}, 11 | {I,5,I,I,I,20,I,I}, 12 | {I,I,10,I,14,18,I,I}}; 13 | int near[8]={I,I,I,I,I,I,I,I}; 14 | int t[2][6]; 15 | int i,j,u,v,k,n=7,min=I; 16 | for(i=1;i<=n;i++) //finding the minimum weight edge 17 | { 18 | for(j=i;j<=n;j++) 19 | { 20 | if(cost[i][j] 0: 42 | 43 | # add one of those nodes to the ordering 44 | node = nodes_with_no_incoming_edges.pop() 45 | topological_ordering.append(node) 46 | 47 | # decrement the indegree of that node's neighbors 48 | for neighbor in digraph[node]: 49 | indegrees[neighbor] -= 1 50 | if indegrees[neighbor] == 0: 51 | nodes_with_no_incoming_edges.append(neighbor) 52 | 53 | # we've run out of nodes with no incoming edges 54 | # did we add all the nodes or find a cycle? 55 | if len(topological_ordering) == len(digraph): 56 | return topological_ordering # got them all 57 | else: 58 | raise Exception("Graph has a cycle! No topological ordering exists.") 59 | 60 | 61 | # Driver Code 62 | if __name__ == '__main__': 63 | 64 | # No cycle in graph 65 | acyclic_graph = { 66 | 'A' : ['C','D'], 67 | 'B' : ['E','C'], 68 | 'C' : ['D'], 69 | 'D' : [], 70 | 'E' : ['A','C'] 71 | } 72 | 73 | print(topological_sort(acyclic_graph)) # prints ['B', 'E', 'A', 'C', 'D'] 74 | 75 | # A cycle present between nodes (C, D and E) 76 | cyclic_graph = { 77 | 'A' : ['C','D'], 78 | 'B' : ['E','C'], 79 | 'C' : ['D'], 80 | 'D' : ['E'], 81 | 'E' : ['A','C'] 82 | } 83 | 84 | print(topological_sort(cyclic_graph)) # gives exception as cycle is present 85 | -------------------------------------------------------------------------------- /Graphs/bellman ford/algorithm explanation.txt: -------------------------------------------------------------------------------- 1 | The Bellman-Ford algorithm solves the single-source shortest-paths problem in 2 | the general case in which edge weights may be negative. Given a weighted, directed graph G = (V, E) with source s and weight function w : E → R, the 3 | Bellman-Ford algorithm returns a boolean value indicating whether or not there is 4 | a negative-weight cycle that is reachable from the source. If there is such a cycle, the algorithm indicates that no solution exists. If there is no such cycle, the 5 | algorithm produces the shortest paths and their weights. 6 | The algorithm uses relaxation, progressively decreasing an estimate d[v] on the 7 | weight of a shortest path from the source s to each vertex v ∈ V until it achieves 8 | the actual shortest-path weight δ(s, v). The algorithm returns TRUE if and only if 9 | the graph contains no negative-weight cycles that are reachable from the source. 10 | BELLMAN-FORD(G, w,s) 11 | 1 INITIALIZE-SINGLE-SOURCE(G,s) 12 | 2 for i ← 1 to |V[G]| − 1 13 | 3 do for each edge (u, v) ∈ E[G] 14 | 4 do RELAX(u, v, w) 15 | 5 for each edge (u, v) ∈ E[G] 16 | 6 do if d[v] > d[u] + w(u, v) 17 | 7 then return FALSE 18 | 8 return TRUE -------------------------------------------------------------------------------- /Graphs/bellman ford/code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | struct Edge { 3 | int src, dest, weight; 4 | }; 5 | struct Graph { 6 | int V, E; 7 | struct Edge* edge; 8 | }; 9 | struct Graph* createGraph(int V, int E) { 10 | struct Graph* graph = new Graph; 11 | graph->V = V; 12 | graph->E = E; 13 | graph->edge = new Edge[E]; 14 | return graph; 15 | } 16 | void BellmanFord(struct Graph* graph, int src) { 17 | int V = graph->V; 18 | int E = graph->E; 19 | int dist[V]; 20 | for (int i = 0; i < V; i++) 21 | dist[i] = INT_MAX; 22 | dist[src] = 0; 23 | for (int i = 1; i <= V - 1; i++) { 24 | for (int j = 0; j < E; j++) { 25 | int u = graph->edge[j].src; 26 | int v = graph->edge[j].dest; 27 | int weight = graph->edge[j].weight; 28 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) 29 | dist[v] = dist[u] + weight; 30 | } 31 | } 32 | for (int i = 0; i < E; i++) { 33 | int u = graph->edge[i].src; 34 | int v = graph->edge[i].dest; 35 | int weight = graph->edge[i].weight; 36 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { 37 | printf("Graph contains negative weight cycle"); 38 | return; 39 | } 40 | } 41 | printf("Vertex :\t\t\t "); 42 | for (int i = 0; i < V; ++i) 43 | printf("%d \t", i); 44 | printf("\nDistance From Source : "); 45 | for (int i = 0; i < V; ++i) 46 | printf("%d \t",dist[i]); 47 | return; 48 | } 49 | int main() { 50 | int V = 5; 51 | int E = 8; 52 | struct Graph* graph = createGraph(V, E); 53 | graph->edge[0].src = 0; 54 | graph->edge[0].dest = 1; 55 | graph->edge[0].weight = -1; 56 | graph->edge[1].src = 0; 57 | graph->edge[1].dest = 2; 58 | graph->edge[1].weight = 4; 59 | graph->edge[2].src = 1; 60 | graph->edge[2].dest = 2; 61 | graph->edge[2].weight = 3; 62 | graph->edge[3].src = 1; 63 | graph->edge[3].dest = 3; 64 | graph->edge[3].weight = 2; 65 | graph->edge[4].src = 1; 66 | graph->edge[4].dest = 4; 67 | graph->edge[4].weight = 2; 68 | graph->edge[5].src = 3; 69 | graph->edge[5].dest = 2; 70 | graph->edge[5].weight = 5; 71 | graph->edge[6].src = 3; 72 | graph->edge[6].dest = 1; 73 | graph->edge[6].weight = 1; 74 | graph->edge[7].src = 4; 75 | graph->edge[7].dest = 3; 76 | graph->edge[7].weight = -3; 77 | BellmanFord(graph, 0); 78 | return 0; 79 | } -------------------------------------------------------------------------------- /Graphs/bellman ford/explaination.txt: -------------------------------------------------------------------------------- 1 | Algorithm 2 | Following are the detailed steps. 3 | 4 | Input: Graph and a source vertex src 5 | Output: Shortest distance to all vertices from src. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported. 6 | 7 | 1) This step initializes distances from the source to all vertices as infinite and distance to the source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex. 8 | 9 | 2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given graph. 10 | …..a) Do following for each edge u-v 11 | ………………If dist[v] > dist[u] + weight of edge uv, then update dist[v] 12 | ………………….dist[v] = dist[u] + weight of edge uv 13 | 14 | 3) This step reports if there is a negative weight cycle in graph. Do following for each edge u-v 15 | ……If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle” 16 | The idea of step 3 is, step 2 guarantees the shortest distances if the graph doesn’t contain a negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle 17 | 18 | Notes 19 | 1) Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path. 20 | 21 | 2) Bellman-Ford works better (better than Dijksra’s) for distributed systems. Unlike Dijkstra’s where we need to find the minimum value of all vertices, in Bellman-Ford, edges are considered one by one. 22 | -------------------------------------------------------------------------------- /Greedy_Algorithms/Activity Selection/Activity_Selection.cpp: -------------------------------------------------------------------------------- 1 | #include < bits / stdc++.h & gt; 2 | using namespace std; 3 | 4 | struct process 5 | { 6 | int start; 7 | int finish; 8 | }; 9 | 10 | bool compare(process p1, process p2) 11 | { 12 | if (p1.finish > p2.finish) 13 | return true; 14 | return false; 15 | } 16 | 17 | int solve(int n, process p[]) 18 | { 19 | sort(p, p + n, compare); //sort the process according to finish 20 | time int ans = 1; 21 | process curr = p[0]; 22 | for (int i = 1; i < n; i++) 23 | { 24 | if (p[i].start > curr.finish) 25 | { 26 | curr = p[i]; 27 | ans++; 28 | } 29 | } 30 | return ans; 31 | } 32 | int main() 33 | { 34 | int n; 35 | cin >> n; 36 | process p[n]; 37 | for (int i = 0; i < n; i++) 38 | cin >> p[i].start >> p[i].finish; 39 | int temp = solve(n, p); 40 | cout << "Max Process Performed by a Processor " << temp << endl; 41 | } -------------------------------------------------------------------------------- /Greedy_Algorithms/Huffman Encoading/Huffman_Encoading.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | char c; 8 | int data; 9 | Node *left; 10 | Node *right; 11 | Node(char temp, int d, Node *L = NULL, Node *R = NULL) 12 | { 13 | c = temp; 14 | data = d; 15 | left = L; 16 | right = R; 17 | } 18 | }; 19 | 20 | struct compare 21 | { 22 | bool operator()(Node *a, Node *b) 23 | { 24 | if (a->data > b->data) 25 | return true; 26 | return false; 27 | } 28 | }; 29 | void print_codes(Node *top, string ans) 30 | { 31 | if (top == NULL) 32 | return; 33 | if (top->c != '*') 34 | cout << top->c << " : " << ans << endl; 35 | print_codes(top->left, ans + "0"); 36 | print_codes(top->right, ans + "1"); 37 | } 38 | void Huffman_Encoding(char arr[], int freq[], int n) 39 | { 40 | Node *left, *right, *top; 41 | priority_queue, compare> pq; 42 | for (int i = 0; i < n; i++) 43 | { 44 | pq.push(new Node(arr[i], freq[i])); 45 | } 46 | for (int i = 1; i < n; i++) 47 | { 48 | left = pq.top(); 49 | pq.pop(); 50 | right = pq.top(); 51 | pq.pop(); 52 | int data = left->data + right->data; 53 | top = new Node('*', data, left, right); 54 | pq.push(top); 55 | } 56 | print_codes(pq.top(), ""); 57 | } 58 | 59 | int main() 60 | { 61 | 62 | char arr[] = {'a', 'b', 'c', 'd', 'e', 'f'}; 63 | int freq[] = {5, 9, 12, 13, 16, 45}; 64 | Huffman_Encoding(arr, freq, 6); 65 | } -------------------------------------------------------------------------------- /Greedy_Algorithms/Interval Scheduling Maximization/intervalSchedulingMaximization.js: -------------------------------------------------------------------------------- 1 | const intervalSchedulingMaximization = (schedules) => { 2 | schedules.sort((s1, s2) => s1.f > s2.f ? 1 : -1); 3 | let count = 1; 4 | let ind = 0; 5 | for (let i = 1; i < schedules.length; i++) { 6 | if (!overlap(schedules[ind], schedules[i])) { 7 | ind = i; 8 | count++; 9 | } 10 | } 11 | return count; 12 | } 13 | 14 | const overlap = (s1, s2) => (s2.s >= s1.s && s2.s < s1.f) || 15 | (s2.f >= s1.s && s2.f < s1.f) || 16 | (s2.s <= s1.s && s2.f >= s1.f) -------------------------------------------------------------------------------- /Greedy_Algorithms/Interval Scheduling Maximization/ism.txt: -------------------------------------------------------------------------------- 1 | Description: Given an array of schedules, which schedule has a start(s) and an end(f) value. And we want the maximum of compatible schedules, that is, their period don't overlap, exemple: 2 | schedules = [ 3 | {s: 2; f: 5}, 4 | {s: 1; f: 3}, 5 | {s: 4; f: 6}, 6 | {s: 5; f: 7}, 7 | ] 8 | In this case, schedules[0] overlaps schedules[1] and [2], and is compatible only with [3]. 9 | 10 | Solution: the greedy way to solve this is, by each step, choose the one that end's first and exclude the ones which overlap it. 11 | 12 | Time complexity: O( n*log(n) ) -------------------------------------------------------------------------------- /Greedy_Algorithms/Knapsack Problem/fractional_knapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct Item { 6 | int value, weight; 7 | 8 | 9 | Item(int value, int weight) 10 | : value(value), weight(weight) 11 | { 12 | } 13 | }; 14 | 15 | bool cmp(struct Item a, struct Item b) 16 | { 17 | double r1 = (double)a.value / a.weight; 18 | double r2 = (double)b.value / b.weight; 19 | return r1 > r2; 20 | } 21 | 22 | double fractionalKnapsack(struct Item arr[], 23 | int N, int size) 24 | { 25 | sort(arr, arr + size, cmp); 26 | 27 | int curWeight = 0; 28 | 29 | double finalvalue = 0.0; 30 | 31 | for (int i = 0; i < size; i++) { 32 | 33 | if (curWeight + arr[i].weight <= N) { 34 | curWeight += arr[i].weight; 35 | finalvalue += arr[i].value; 36 | } 37 | 38 | else { 39 | int remain = N - curWeight; 40 | finalvalue += arr[i].value 41 | * ((double)remain 42 | / arr[i].weight); 43 | 44 | break; 45 | } 46 | } 47 | 48 | return finalvalue; 49 | } 50 | 51 | int main() 52 | { 53 | int N = 60; 54 | 55 | Item arr[] = { { 100, 10 }, 56 | { 280, 40 }, 57 | { 120, 20 }, 58 | { 120, 24 } }; 59 | 60 | int size = sizeof(arr) / sizeof(arr[0]); 61 | 62 | cout << "Maximum profit earned = " 63 | << fractionalKnapsack(arr, N, size); 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /Greedy_Algorithms/Weighted Job Scheduling/Weighted Job Scheduling.cpp: -------------------------------------------------------------------------------- 1 | /* Question: You are given N jobs where every job is represented as: 2 | 1.Start Time 3 | 2.Finish Time 4 | 3.Profit Associated 5 | Find the maximum profit subset of jobs such that no two jobs in the subset overlap. 6 | */ 7 | 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | 13 | struct Job 14 | { 15 | int start, finish, profit; 16 | }; 17 | 18 | 19 | bool jobComparataor(Job s1, Job s2) 20 | { 21 | return (s1.finish < s2.finish); 22 | } 23 | 24 | 25 | int latestNonConflict(Job arr[], int index) 26 | { 27 | int lo = 0, hi = index- 1; 28 | 29 | 30 | while (lo <= hi) 31 | { 32 | int mid = (lo + hi) / 2; 33 | if (arr[mid].finish <= arr[index].start) 34 | { 35 | if (arr[mid + 1].finish <= arr[index].start) 36 | lo = mid + 1; 37 | else 38 | return mid; 39 | } 40 | else 41 | hi = mid - 1; 42 | } 43 | return -1; 44 | } 45 | 46 | 47 | 48 | 49 | 50 | long long findMaxProfit(Job arr[], int n) 51 | { 52 | 53 | sort(arr, arr+n, jobComparataor); 54 | 55 | long long *table = new long long[n]; 56 | table[0] = arr[0].profit; 57 | 58 | 59 | for (int i=1; i>n; 81 | Job arr[n]; 82 | for(i=0;i>start>>finish>>profit; 85 | arr[i].start=start; 86 | arr[i].finish=finish; 87 | arr[i].profit=profit; 88 | } 89 | cout<next; 30 | temp->next = new Node(temp->val); 31 | temp->next->next = next; 32 | temp = temp->next->next; 33 | } 34 | Node *temp1 = head; 35 | Node *newHead = head->next; 36 | // MArking the Random Pointers 37 | while (temp1) 38 | { 39 | if (temp1->random) 40 | temp1->next->random = temp1->random->next; 41 | temp1 = temp1->next->next; 42 | } 43 | 44 | temp = newHead; 45 | temp1 = head; 46 | // Separate the old nodes 47 | while (temp->next) 48 | { 49 | temp1->next = temp->next; 50 | temp->next = temp->next->next; 51 | temp = temp->next; 52 | temp1 = temp1->next; 53 | } 54 | temp1->next = NULL; 55 | temp = newHead; 56 | temp1 = head; 57 | return newHead; 58 | } 59 | }; -------------------------------------------------------------------------------- /Linked Lists/Delete_LL/delete_linkedlist-C++.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to delete a linked list 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | class Node 7 | { 8 | public: 9 | int data; 10 | Node* next; 11 | }; 12 | 13 | /* Function to delete the entire linked list */ 14 | void deleteList(Node** head_ref) 15 | { 16 | 17 | /* deref head_ref to get the real head */ 18 | Node* current = *head_ref; 19 | Node* next; 20 | 21 | while (current != NULL) 22 | { 23 | next = current->next; 24 | free(current); 25 | current = next; 26 | } 27 | 28 | /* deref head_ref to affect the real head back 29 | in the caller. */ 30 | *head_ref = NULL; 31 | } 32 | 33 | /* Given a reference (pointer to pointer) to the head 34 | of a list and an int, push a new node on the front 35 | of the list. */ 36 | void push(Node** head_ref, int new_data) 37 | { 38 | /* allocate node */ 39 | Node* new_node = new Node(); 40 | 41 | /* put in the data */ 42 | new_node->data = new_data; 43 | 44 | /* link the old list off the new node */ 45 | new_node->next = (*head_ref); 46 | 47 | /* move the head to point to the new node */ 48 | (*head_ref) = new_node; 49 | } 50 | 51 | /* Driver code*/ 52 | int main() 53 | { 54 | /* Start with the empty list */ 55 | Node* head = NULL; 56 | 57 | /* Use push() to construct below list 58 | 1->12->1->4->1 */ 59 | push(&head, 1); 60 | push(&head, 4); 61 | push(&head, 1); 62 | push(&head, 12); 63 | push(&head, 1); 64 | 65 | cout << "Deleting linked list"; 66 | deleteList(&head); 67 | 68 | cout << "\nLinked list deleted"; 69 | } 70 | -------------------------------------------------------------------------------- /Linked Lists/Delete_LL/explaination.txt: -------------------------------------------------------------------------------- 1 | Algorithm For C/C++: Iterate through the linked list and delete all the nodes one by one. Main point here is not to access next of the current pointer if current pointer is deleted. 2 | 3 | Time Complexity: O(n) 4 | Auxiliary Space: O(1) 5 | 6 | 7 | -------------------------------------------------------------------------------- /Linked Lists/Detect_Loop_linked-list/Detect-loop-ll-CPP.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to detect loop in a linked list 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | struct Node { 7 | int data; 8 | struct Node* next; 9 | }; 10 | 11 | void push(struct Node** head_ref, int new_data) 12 | { 13 | /* allocate node */ 14 | struct Node* new_node = new Node; 15 | 16 | /* put in the data */ 17 | new_node->data = new_data; 18 | 19 | /* link the old list off the new node */ 20 | new_node->next = (*head_ref); 21 | 22 | /* move the head to point to the new node */ 23 | (*head_ref) = new_node; 24 | } 25 | 26 | // Returns true if there is a loop in linked list 27 | // else returns false. 28 | bool detectLoop(struct Node* h) 29 | { 30 | unordered_set s; 31 | while (h != NULL) { 32 | // If this node is already present 33 | // in hashmap it means there is a cycle 34 | // (Because you we encountering the 35 | // node for the second time). 36 | if (s.find(h) != s.end()) 37 | return true; 38 | 39 | // If we are seeing the node for 40 | // the first time, insert it in hash 41 | s.insert(h); 42 | 43 | h = h->next; 44 | } 45 | 46 | return false; 47 | } 48 | 49 | /* Driver program to test above function*/ 50 | int main() 51 | { 52 | /* Start with the empty list */ 53 | struct Node* head = NULL; 54 | 55 | push(&head, 20); 56 | push(&head, 4); 57 | push(&head, 15); 58 | push(&head, 10); 59 | 60 | /* Create a loop for testing */ 61 | head->next->next->next->next = head; 62 | 63 | if (detectLoop(head)) 64 | cout << "Loop found"; 65 | else 66 | cout << "No Loop"; 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Linked Lists/Detect_Loop_linked-list/explaination.md: -------------------------------------------------------------------------------- 1 | Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false and if next of current node points to any of the previously stored nodes in Hash then return true. 2 | 3 | Complexity Analysis: 4 | 5 | 6 | Time complexity: O(n). 7 | Only one traversal of the loop is needed. 8 | Auxiliary Space: O(n). 9 | n is the space required to store the value in hashmap. 10 | -------------------------------------------------------------------------------- /Linked Lists/LL Insertion/LL_Insertion_nth_pos.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | }; 9 | struct Node *head; 10 | void Insert(int data, int n) 11 | { 12 | struct Node *temp1 = (struct Node*)malloc(sizeof(struct Node)); 13 | temp1->data = data; 14 | temp1->next = NULL; 15 | if(n==1) 16 | { 17 | temp1->next = head; 18 | head = temp1; 19 | return; 20 | } 21 | int i; 22 | struct Node *temp2 = head; 23 | for(i=0;inext; 26 | } 27 | temp1->next = temp2->next; 28 | temp2->next = temp1; 29 | 30 | } 31 | void Print() 32 | { 33 | struct Node *temp = head; 34 | while(temp!=NULL) 35 | { 36 | printf("%d ",temp->data); 37 | temp = temp->next; 38 | } 39 | } 40 | int main() 41 | { 42 | head = NULL; 43 | 44 | Insert(2,1); 45 | Insert(3,2); 46 | Insert(4,1); 47 | Insert(5,2); 48 | Insert(1,3); 49 | Print(); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Linked Lists/LL Insertion/README.md: -------------------------------------------------------------------------------- 1 | Insert given data at given position in Linked list 2 | 3 | Algorithm : 4 | 1] If Head is null and position is not 0. Then exit it. 5 | 2] If Head is null and position is 0. Then insert new Node to the Head and exit it. 6 | 3] If Head is not null and position is 0. Then the Head reference set to the new Node. Finally, new Node set to the Head and exit it. 7 | 4] If not, iterate until finding the Nth position or end. -------------------------------------------------------------------------------- /Linked Lists/Max Node/MaxOfLinkedList.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | } *first = NULL; 9 | 10 | void Create(int A[], int n) 11 | { 12 | int i; 13 | struct Node *t, *last; 14 | first = (struct Node *)malloc(sizeof(struct Node)); 15 | first->data = A[0]; 16 | first->next = NULL; 17 | last = first; 18 | 19 | for (i = 1; i < n; i++) 20 | { 21 | t = (struct Node *)malloc(sizeof(struct Node)); 22 | t->data = A[i]; 23 | t->next = NULL; 24 | last->next = t; 25 | last = t; 26 | } 27 | } 28 | 29 | int Max(struct Node *p) 30 | { 31 | int max = INT_MIN; 32 | while (p != NULL) 33 | { 34 | if (p->data > max) 35 | max = p->data; 36 | p = p->next; 37 | } 38 | return max; 39 | } 40 | 41 | int Min(struct Node *p) 42 | { 43 | int min = INT_MAX; 44 | while (p != NULL) 45 | { 46 | if (p->data < min) 47 | min = p->data; 48 | p = p->next; 49 | } 50 | return min; 51 | } 52 | 53 | int RMax(struct Node *p) 54 | { 55 | int x = 0; 56 | if (p == 0) 57 | return INT_MIN; 58 | x = RMax(p->next); 59 | if (x > p->data) 60 | return x; 61 | else 62 | return p->data; 63 | } 64 | int main() 65 | { 66 | int A[] = {3, 5, 7, 10, 15, 8, 12, 2}; 67 | Create(A, 8); 68 | printf("Maximum Number is : %d \n", RMax(first)); 69 | printf("Minimum Number is : %d ", Min(first)); 70 | 71 | return 0; 72 | } 73 | 74 | // Output : 75 | // Maximum Number is : 15 76 | // Minimum Number is : 2 77 | 78 | // Iterative 79 | // Time : O(n), Space O(1) 80 | 81 | // Recursive 82 | // Time : O(n), Space(n) 83 | -------------------------------------------------------------------------------- /Linked Lists/Merge Two Sorted Lists/Merge Two Lists.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Definition for singly-linked list. 4 | typedef struct ListNode { 5 | int val; 6 | ListNode *next; 7 | ListNode() : val(0), next(nullptr) {} 8 | ListNode(int x) : val(x), next(nullptr) {} 9 | ListNode(int x, ListNode *next) : val(x), next(next) {} 10 | }ListNode; 11 | 12 | class Solution { 13 | public: 14 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 15 | if (l1 && l2) { 16 | if (l1 -> val < l2 -> val) { 17 | l1 -> next = mergeTwoLists (l1 -> next, l2); 18 | return l1; 19 | } 20 | else { 21 | l2 -> next = mergeTwoLists (l1, l2 -> next); 22 | return l2; 23 | } 24 | } 25 | else if (l1) return l1; 26 | else if (l2) return l2; 27 | else return NULL; 28 | } 29 | }; -------------------------------------------------------------------------------- /Linked Lists/Merge Two Sorted Lists/Question.md: -------------------------------------------------------------------------------- 1 | # Given Two Linked Lists which are sorted. Merge the two such that the final Linked List is sorted. Return the Merged Linked List. -------------------------------------------------------------------------------- /Linked Lists/Reverse LL/Reversing Linked List.md: -------------------------------------------------------------------------------- 1 | ## Reversing a Linked List 2 | 3 | ### Iterative Method 4 | 5 | 1. Initialize three pointers as follows. 6 | 7 | // you can complete this. 8 | 9 | -------------------------------------------------------------------------------- /Linked Lists/Reverse LL/Reversing-Linkedlist-C++.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node 5 | { 6 | int num; 7 | node *next; 8 | }*head; //node constructed 9 | 10 | void createlist(int n); 11 | void reverse(node **head); 12 | void display(); 13 | 14 | int main() 15 | { 16 | int n,num,item; 17 | 18 | cout<<"Enter the number of nodes: "; 19 | cin>>n; 20 | createlist(n); 21 | cout<<"\nLinked list data: \n"; 22 | display(); 23 | cout<<"\nAfter reversing\n"; 24 | reverse(&head); 25 | display(); 26 | return 0; 27 | } 28 | void createlist(int n) //function to create linked list. 29 | { 30 | struct node *newnode, *tmp; 31 | int num, i; 32 | 33 | head = (struct node *)malloc(sizeof(struct node)); 34 | if(head == NULL) 35 | { 36 | cout<<" Memory can not be allocated"; 37 | } 38 | else 39 | { 40 | 41 | cout<<"Enter the data for node 1: "; 42 | cin>>num; 43 | head-> num = num; 44 | head-> next = NULL; //Links the address field to NULL 45 | tmp = head; 46 | 47 | for(i=2; i<=n; i++) 48 | { 49 | newnode = (struct node *)malloc(sizeof(struct node)); 50 | 51 | 52 | if(newnode == NULL) //If newnode is null no memory cannot be allotted 53 | { 54 | cout<<"Memory can not be allocated"; 55 | break; 56 | } 57 | else 58 | { 59 | cout<<"Enter the data for node "<>num; 61 | newnode->num = num; 62 | newnode->next = NULL; 63 | tmp->next = newnode; 64 | tmp = tmp->next; 65 | } 66 | } 67 | } 68 | } 69 | 70 | void reverse(node **head) //function to reverse linked list 71 | { 72 | struct node *temp = NULL; 73 | struct node *prev = NULL; 74 | struct node *current = (*head); 75 | while(current != NULL) { 76 | temp = current->next; 77 | current->next = prev; 78 | prev = current; 79 | current = temp; 80 | } 81 | (*head) = prev; 82 | } 83 | void display()//function to display linked list 84 | { 85 | struct node *tmp; 86 | if(head == NULL) 87 | { 88 | cout<<"List is empty"; 89 | } 90 | else 91 | { 92 | tmp = head; 93 | while(tmp != NULL) 94 | { 95 | cout<num<<" "; 96 | tmp = tmp->next; 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Linked Lists/Reverse_a_linked_list_in_group_of_size_k.cpp: -------------------------------------------------------------------------------- 1 | /*.....reverse a liked list in group of size k.*/ 2 | #include 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | struct node *reverse (struct node *head, int k); 7 | 8 | struct node 9 | { 10 | int data; 11 | struct node* next; 12 | 13 | node(int x){ 14 | data = x; 15 | next = NULL; 16 | } 17 | 18 | }; 19 | 20 | /* Function to print linked list */ 21 | void printList(struct node *node) 22 | { 23 | while (node != NULL) 24 | { 25 | printf("%d ", node->data); 26 | node = node->next; 27 | } 28 | printf("\n"); 29 | } 30 | 31 | /* Drier program to test above function*/ 32 | int main(void) 33 | { 34 | int t; 35 | cin>>t; 36 | 37 | while(t--) 38 | { 39 | struct node* head = NULL; 40 | struct node* temp = NULL; 41 | int n; 42 | cin >> n; 43 | 44 | for(int i=0 ; i> value; 48 | if(i == 0) 49 | { 50 | head = new node(value); 51 | temp = head; 52 | } 53 | else 54 | { 55 | temp->next = new node(value); 56 | temp = temp->next; 57 | } 58 | } 59 | 60 | int k; 61 | cin>>k; 62 | 63 | head = reverse(head, k); 64 | printList(head); 65 | } 66 | 67 | return(0); 68 | } 69 | 70 | struct node 71 | { 72 | int data; 73 | struct node* next; 74 | 75 | node(int x){ 76 | data = x; 77 | next = NULL; 78 | } 79 | 80 | }*head; 81 | 82 | 83 | struct node *reverse (struct node *head, int k) 84 | { 85 | 86 | int c=k; 87 | node*curr=head; 88 | node*next=NULL; 89 | node*prev=NULL; 90 | while(c-- && curr!=NULL){ 91 | next=curr->next; 92 | curr->next=prev; 93 | prev=curr; 94 | curr=next; 95 | } 96 | if(head!=NULL) 97 | head->next=reverse(next,k); 98 | return prev; 99 | } 100 | -------------------------------------------------------------------------------- /Linked Lists/Search_element_LL/Search_element-C++.cpp: -------------------------------------------------------------------------------- 1 | // Iterative C++ program to search 2 | // an element in linked list 3 | #include 4 | using namespace std; 5 | 6 | /* Link list node */ 7 | class Node 8 | { 9 | public: 10 | int key; 11 | Node* next; 12 | }; 13 | 14 | /* Given a reference (pointer to pointer) to the head 15 | of a list and an int, push a new node on the front 16 | of the list. */ 17 | void push(Node** head_ref, int new_key) 18 | { 19 | /* allocate node */ 20 | Node* new_node = new Node(); 21 | 22 | /* put in the key */ 23 | new_node->key = new_key; 24 | 25 | /* link the old list off the new node */ 26 | new_node->next = (*head_ref); 27 | 28 | /* move the head to point to the new node */ 29 | (*head_ref) = new_node; 30 | } 31 | 32 | /* Checks whether the value x is present in linked list */ 33 | bool search(Node* head, int x) 34 | { 35 | Node* current = head; // Initialize current 36 | while (current != NULL) 37 | { 38 | if (current->key == x) 39 | return true; 40 | current = current->next; 41 | } 42 | return false; 43 | } 44 | 45 | /* Driver program to test count function*/ 46 | int main() 47 | { 48 | /* Start with the empty list */ 49 | Node* head = NULL; 50 | int x = 21; 51 | 52 | /* Use push() to construct below list 53 | 14->21->11->30->10 */ 54 | push(&head, 10); 55 | push(&head, 30); 56 | push(&head, 11); 57 | push(&head, 21); 58 | push(&head, 14); 59 | 60 | search(head, 21)? cout<<"Yes" : cout<<"No"; 61 | return 0; 62 | } 63 | 64 | -------------------------------------------------------------------------------- /Linked Lists/Search_element_LL/explaination.txt: -------------------------------------------------------------------------------- 1 | Iterative Solution 2 | 3 | 1) Initialize a node pointer, current = head. 4 | 2) Do following while current is not NULL 5 | a) current->key is equal to the key being searched return true. 6 | b) current = current->next 7 | 3) Return false 8 | -------------------------------------------------------------------------------- /Linked Lists/Swap Nodes in Doubly Linked List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std ; 4 | class Node { 5 | public: 6 | int data; 7 | struct Node* next; // Pointer to next node in DLL 8 | struct Node* prev; // Pointer to previous node in DLL 9 | Node(int data) 10 | { 11 | this->data = data ; 12 | next = NULL ; 13 | prev = NULL ; 14 | } 15 | }; 16 | void print(Node* head) 17 | { 18 | Node* temp = head ; 19 | cout<data<<" "; 20 | temp = temp->next ; 21 | while(temp != head) 22 | { 23 | cout<data<<" "; 24 | temp = temp->next ; 25 | } 26 | } 27 | Node* Swap_Nodes(Node* head , int i , int j) 28 | { 29 | if(head == NULL) 30 | return NULL ; 31 | Node* a = head ; 32 | Node* b = head ; 33 | for(int k=0;knext ; 36 | } 37 | for(int k=0;knext ; 40 | } 41 | if(i==j) 42 | return head ; 43 | 44 | 45 | if(abs(i-j) == 1) 46 | { 47 | Node* z = a->prev ; 48 | a->prev->next = b ; 49 | a->next = b->next ; 50 | a->prev = b ; 51 | b->next = a ; 52 | a->next->prev = a ; 53 | b->prev = z ; 54 | } 55 | 56 | else{ 57 | 58 | 59 | 60 | Node* x = a->prev ; 61 | Node* y = a->next ; 62 | a->prev->next = b ; 63 | a->next->prev = b ; 64 | a->prev = b->prev ; 65 | a->next = b->next ; 66 | b->prev->next = a ; 67 | b->next->prev = a ; 68 | b->prev = x ; 69 | b->next = y ; 70 | } 71 | if(i==0) 72 | head = b ; 73 | if(j==0) 74 | head = a ; 75 | return head ; 76 | } 77 | int main() 78 | { 79 | Node *a = new Node(1); 80 | Node *b = new Node(2); 81 | Node *c = new Node(3); 82 | Node *d = new Node(4); 83 | Node *e = new Node(5); 84 | Node *f = new Node(6); 85 | a->next = b ; 86 | b->next = c ; 87 | c->next = d ; 88 | d->next = e ; 89 | e->next = f ; 90 | f->next = a ; 91 | a->prev = f ; 92 | b->prev = a ; 93 | c->prev = b ; 94 | d->prev = c ; 95 | e->prev = d ; 96 | f->prev = e ; 97 | cout<<"Original List : "; 98 | print(a) ; 99 | cout<>x>>y; 103 | a = Swap_Nodes(a,x,y); 104 | cout<<"List After Swapping at Position "<= l; --i) { 26 | System.out.print(a[m - 1][i] + " "); 27 | } 28 | m--; 29 | } 30 | 31 | // Print the first column from the remaining 32 | // columns */ 33 | if (l < n) { 34 | for (i = m - 1; i >= k; --i) { 35 | System.out.print(a[i][l] + " "); 36 | } 37 | l++; 38 | } 39 | } 40 | } 41 | 42 | // Driver code 43 | public static void main (String[] args) 44 | { 45 | Scanner scn = new Scanner(System.in); 46 | int N = scn.nextInt(); 47 | int M = scn.nextInt(); 48 | 49 | int[][] A = new int[N][M]; 50 | for(int i=0; i n / 2: 20 | return 1 21 | 22 | #returning -1 if there is no majority element 23 | if (count == 0): 24 | return -1 25 | 26 | #defining the input function 27 | #taking input from the user in correct format 28 | #refer readme 29 | if __name__ == '__main__': 30 | input = sys.stdin.read() 31 | n, *a = list(map(int, input.split())) 32 | 33 | if get_majority_element(a, n) != -1: 34 | print(1) 35 | else: 36 | print(0) 37 | -------------------------------------------------------------------------------- /Miscellaneous Algorithms/FibonacciSearch.cpp: -------------------------------------------------------------------------------- 1 | // Cpp program for Fibonacci Search 2 | 3 | #include 4 | using namespace std ; 5 | 6 | // Utility function to find minimum of two elements 7 | int min(int x, int y) { 8 | return (x<=y)? x : y; 9 | } 10 | 11 | /* Returns index of x if present, else returns -1 */ 12 | int fibMonaccianSearch(int arr[], int x, int n) 13 | { 14 | /* Initialize fibonacci numbers */ 15 | int fibMMm2 = 0; // (m-2)'th Fibonacci No. 16 | int fibMMm1 = 1; // (m-1)'th Fibonacci No. 17 | int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci 18 | 19 | /* fibM is going to store the smallest Fibonacci 20 | Number greater than or equal to n */ 21 | while (fibM < n) 22 | { 23 | fibMMm2 = fibMMm1; 24 | fibMMm1 = fibM; 25 | fibM = fibMMm2 + fibMMm1; 26 | } 27 | 28 | // Marks the eliminated range from front 29 | int offset = -1; 30 | 31 | /* while there are elements to be inspected. Note that 32 | we compare arr[fibMm2] with x. When fibM becomes 1, 33 | fibMm2 becomes 0 */ 34 | while (fibM > 1) 35 | { 36 | // Check if fibMm2 is a valid location 37 | int i = min(offset+fibMMm2, n-1); 38 | 39 | /* If x is greater than the value at index fibMm2, 40 | cut the subarray array from offset to i */ 41 | if (arr[i] < x) 42 | { 43 | fibM = fibMMm1; 44 | fibMMm1 = fibMMm2; 45 | fibMMm2 = fibM - fibMMm1; 46 | offset = i; 47 | } 48 | 49 | /* If x is greater than the value at index fibMm2, 50 | cut the subarray after i+1 */ 51 | else if (arr[i] > x) 52 | { 53 | fibM = fibMMm2; 54 | fibMMm1 = fibMMm1 - fibMMm2; 55 | fibMMm2 = fibM - fibMMm1; 56 | } 57 | 58 | /* element found. return index */ 59 | else 60 | return i; 61 | } 62 | 63 | /* comparing the last element with x */ 64 | if(fibMMm1 && arr[offset+1]==x) 65 | return offset+1; 66 | 67 | /*element not found. return -1 */ 68 | return -1; 69 | } 70 | 71 | /* driver function */ 72 | int main(void) 73 | { 74 | int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100}; 75 | int n = sizeof(arr)/sizeof(arr[0]); 76 | int x = 85; 77 | cout<<"Found at index: "< 2 | using namespace std; 3 | 4 | //tower of HANOI function implementation 5 | void TOH(int n,char Sour, char Aux,char Des) 6 | { 7 | if(n==1) 8 | { 9 | cout<<"Move Disk "<>n; 25 | //calling the TOH 26 | TOH(n,'A','B','C'); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Miscellaneous Algorithms/Tower of Hanoi/towers_of_hanoi-python.py: -------------------------------------------------------------------------------- 1 | # this program solves tower of hanoi Recursively 2 | 3 | def TowerOfHanoi(n , from_rod, to_rod, aux_rod): 4 | if n == 1: 5 | print "Move disk 1 from rod",from_rod,"to rod",to_rod 6 | return 7 | TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) 8 | print "Move disk",n,"from rod",from_rod,"to rod",to_rod 9 | TowerOfHanoi(n-1, aux_rod, to_rod, from_rod) 10 | 11 | 12 | n = 4 # n is the no.of disks 13 | TowerOfHanoi(n, 'A', 'C', 'B') # A,B,C are the rods used 14 | -------------------------------------------------------------------------------- /Number Theory/GCD/gcd - java.java: -------------------------------------------------------------------------------- 1 | 2 | // Question :- Given two integer number and we have to find the GCD of those number. 3 | 4 | // Implementation 5 | 6 | import java.util.Scanner; 7 | 8 | public class GCD { 9 | 10 | public int gcdFinder(int num1, int num2) { 11 | if (num2 == 0) { 12 | return num1; 13 | } 14 | return gcdFinder(num2, num1 % num2); 15 | } 16 | 17 | public static void main(String [] args) { 18 | GCD obj = new GCD(); 19 | Scanner sc = new Scanner(System.in); 20 | int num1 = sc.nextInt(); 21 | int num2 = sc.nextInt(); 22 | System.out.println(obj.gcdFinder(num1, num2)); 23 | } 24 | } -------------------------------------------------------------------------------- /Number Theory/GCD/gcd.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | GCD 3 | Calculate and return GCD of two given numbers x and y. Numbers are within range of Integer. 4 | */ 5 | 6 | int gcd(int a,int b) 7 | { 8 | if (b == 0) { 9 | return a; 10 | } 11 | 12 | return gcd(b, a % b); 13 | } 14 | 15 | // Driver code 16 | 17 | int main(){ 18 | int a, b; 19 | cin>>a>>b; 20 | cout< current_gcd: 9 | current_gcd = d 10 | 11 | return current_gcd 12 | 13 | if __name__ == "__main__": 14 | input = sys.stdin.read() 15 | a, b = map(int, input.split()) 16 | print(gcd(a, b)) 17 | -------------------------------------------------------------------------------- /Number Theory/LCM/Least Common Multiple - CPP.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tulika-99/DS_Algorithms/439d61f28cfee5f1d672edf16ec51794d6439052/Number Theory/LCM/Least Common Multiple - CPP.cpp -------------------------------------------------------------------------------- /Number Theory/LCM/LeastCommonMultiple.js: -------------------------------------------------------------------------------- 1 | // Let's find the smallest number that could be divided with both numbers. 2 | // Here's the easy way. 3 | 4 | function findLCM (num1, num2) { 5 | let lcm = 1; 6 | 7 | while(true){ 8 | if((lcm % num1 == 0) && (lcm % num2 == 0)){ 9 | break; 10 | } // The first number we find at the end of this process would be the least number. 11 | lcm++; 12 | } 13 | return lcm 14 | } -------------------------------------------------------------------------------- /Number Theory/LCM/least-common-multiple.py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | 4 | def lcm(a, b): 5 | for l in range(1, a*b + 1): 6 | if l % a == 0 and l % b == 0: 7 | return l 8 | 9 | return a*b 10 | 11 | if __name__ == '__main__': 12 | input = sys.stdin.read() 13 | a, b = map(int, input.split()) 14 | print(lcm(a, b)) 15 | -------------------------------------------------------------------------------- /Number Theory/Modular Inverse/ModularInverse.cpp: -------------------------------------------------------------------------------- 1 | //A modular multiplicative inverse of an integer a is an integer x such that 2 | // a.x is congruent to 1 modular some modulus m. To write it in a formal way: 3 | //we want to find an integer x so that 4 | // a⋅x≡1 mod m. 5 | #include 6 | using namespace std; 7 | typedef long long int ll; 8 | 9 | void EEA(ll a,ll b,ll& x,ll& y) 10 | { 11 | 12 | if(a==1) 13 | { 14 | x=1; 15 | y=0; 16 | return; 17 | } 18 | 19 | ll x1,y1; 20 | EEA(b%a,a,x1,y1); 21 | x=y1-(b/a)*x1; 22 | y=x1; 23 | } 24 | ll modInverse(ll a,ll m) 25 | { 26 | 27 | if(__gcd(a,m)!=1) 28 | { 29 | return -1; 30 | } 31 | ll x,y; 32 | EEA(a,m,x,y); 33 | x=(x%m+m)%m; 34 | return x; 35 | } 36 | int main() 37 | { 38 | 39 | ll t; 40 | cin>>t; 41 | while(t--) 42 | { 43 | 44 | ll a,m,x; 45 | cin>>a>>m; 46 | x=modInverse(a,m); 47 | cout< 5 | using namespace std; 6 | int main() 7 | { 8 | int n=100000; 9 | int primeNumber[100000]; 10 | for(int i=0;i<100000;i++) 11 | primeNumber[i]=1; 12 | 13 | primeNumber[0]=0; 14 | primeNumber[1]=0; 15 | 16 | for(int i=2;i<=sqrt(n);i++) 17 | { 18 | if(primeNumber[i]){ 19 | for(int j=i*i ; j<=(n); j+=i) 20 | primeNumber[j]=0; 21 | 22 | } 23 | 24 | 25 | } 26 | for(int i=1;i 14 | 15 | long long binaryPower(long long a, long long b, long long p){ 16 | a %= p; 17 | long long res = 1; 18 | while (b > 0) { 19 | if (b & 1) 20 | res = res * a % p; 21 | a = a * a % p; 22 | b >>= 1; 23 | } 24 | return res; 25 | } 26 | 27 | bool fermatPrimalityTest(long long n){ 28 | unsigned char it = 15; 29 | if(n < 4){ 30 | return n==3 || n==2; 31 | } 32 | for(int i = 0; i < it; i++){ 33 | long long a = 2 + rand() % (n-3); 34 | if(binaryPower(a,n-1,n) != 1){ 35 | return false; 36 | } 37 | } 38 | return true; 39 | } 40 | 41 | int main(){ 42 | long long n; 43 | std::cin >> n; 44 | if(fermatPrimalityTest(n)){ 45 | std::cout << n << " is Prime" << std::endl; 46 | } 47 | else{ 48 | std::cout << n << " is not Prime" << std::endl; 49 | } 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Resource Allocation Algorithm/Banker's Algorithm/Banker's_Algo.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | int **allo,**max,**need,*available,n,r,flag=0,*check; 6 | printf("Enter the number of resource types:\n"); 7 | scanf("%d",&r); 8 | printf("Enter the number of instances:\n"); 9 | scanf("%d",&n); 10 | allo=(int**)malloc(n*sizeof(int*)); 11 | max=(int**)malloc(n*sizeof(int*)); 12 | need=(int**)malloc(n*sizeof(int*)); 13 | for(int i=0;iavailable[j]){ 63 | f=1; 64 | break; 65 | } 66 | } 67 | if(f==1){ 68 | i++; 69 | continue; 70 | } 71 | for(int j=0;j",i); 76 | } 77 | i++; 78 | } 79 | for(i=0;i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct Schedule 8 | { 9 | string pro_id; 10 | int artime,bt,ct,ta,wt; 11 | /* 12 | artime = Arrival time, 13 | bt = Burst time, 14 | ct = Completion time, 15 | ta = Turn around time, 16 | wt = Waiting time 17 | */ 18 | 19 | }; 20 | 21 | bool compare(Schedule p1,Schedule p2) 22 | { 23 | return p1.artime>process[i].pro_id; 47 | scanf("%d",&process[i].artime); 48 | scanf("%d",&process[i].bt); 49 | } 50 | 51 | 52 | sort(process,process+n,compare); 53 | 54 | /*sort is a predefined funcion defined in algorithm.h header file, 55 | it will sort the processes according to their arrival time*/ 56 | 57 | cpunon=process[0].artime-0; 58 | 59 | // initial values 60 | 61 | process[0].ct=process[0].artime+process[0].bt; 62 | process[0].ta=process[0].ct-process[0].artime; 63 | process[0].wt=0; 64 | 65 | for(i=1;i 2 | #include 3 | 4 | int main(){ 5 | int n,i, *bt,*at,*ft,*tat,*wt,st=0,sw=0,min,exe; 6 | printf("Enter the number of process:"); 7 | scanf("%d",&n); 8 | bt=(int*)malloc(n*sizeof(int)); 9 | at=(int*)malloc(n*sizeof(int)); 10 | ft=(int*)calloc(n,sizeof(int)); 11 | tat=(int*)malloc(n*sizeof(int)); 12 | wt=(int*)malloc(n*sizeof(int)); 13 | ft[-1]=0; 14 | printf("Enter the Burst time of the processes:\n"); 15 | for(i=0;ibt[j]){ 26 | min = bt[j]; 27 | exe=j; 28 | } 29 | } 30 | ft[i]=min+ft[i-1]; 31 | tat[exe]=ft[i]-at[exe]; 32 | wt[exe]=tat[exe]-min; 33 | st=st+tat[exe]; 34 | sw=sw+wt[exe]; 35 | printf("P%d\t%d\t%d\t%d\t%d\t%d\n",exe,bt[exe],at[exe],ft[i],tat[exe],wt[exe]); 36 | bt[exe]=INT_MAX; 37 | min=INT_MAX; 38 | } 39 | printf("Average turn around time: %0.3f\n",(float)st/n); 40 | printf("Average waiting time: %0.3f", (float)sw/n); 41 | } 42 | -------------------------------------------------------------------------------- /Searching/Binary Search/Binary Search - JavaScript.js: -------------------------------------------------------------------------------- 1 | function binary_Search(items, value){ 2 | var firstIndex = 0, 3 | lastIndex = items.length - 1, 4 | middleIndex = Math.floor((lastIndex + firstIndex)/2); 5 | 6 | while(items[middleIndex] != value && firstIndex < lastIndex) 7 | { 8 | if (value < items[middleIndex]) 9 | { 10 | lastIndex = middleIndex - 1; 11 | } 12 | else if (value > items[middleIndex]) 13 | { 14 | firstIndex = middleIndex + 1; 15 | } 16 | middleIndex = Math.floor((lastIndex + firstIndex)/2); 17 | } 18 | 19 | return (items[middleIndex] != value) ? -1 : middleIndex; 20 | } 21 | var items = [1, 2, 3, 4, 5, 7, 8, 9]; 22 | console.log(binary_Search(items, 1)); 23 | console.log(binary_Search(items, 5)); -------------------------------------------------------------------------------- /Searching/Binary Search/Binary Search - Ruby.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def binary_search(data, item) 4 | return -1 if data.empty? 5 | 6 | left = 0 7 | right = data.length - 1 8 | mid = 0 9 | 10 | index = -1 11 | 12 | while left <= right 13 | mid = (left + right) / 2 14 | 15 | if data[mid] < item 16 | left = mid + 1 17 | elsif data[mid] > item 18 | right = mid - 1 19 | elsif data[mid] == item 20 | index = mid 21 | break 22 | end 23 | end 24 | 25 | index 26 | end 27 | 28 | sorted_data = [1, 2, 5, 6, 9, 13, 25, 30, 45, 100] 29 | 30 | puts "Data = #{sorted_data}" 31 | puts 32 | puts "Index for Item 1 = #{binary_search(sorted_data, 1)}" 33 | puts "Index for Item 5 = #{binary_search(sorted_data, 5)}" 34 | puts "Index for Item 30 = #{binary_search(sorted_data, 30)}" 35 | puts "Index for Item 100 = #{binary_search(sorted_data, 100)}" 36 | puts "Index for Item 99999 = #{binary_search(sorted_data, 99_999)}" 37 | -------------------------------------------------------------------------------- /Searching/Binary Search/Binary Search-CPP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int count, i, arr[30], num, first, last, middle; 7 | cout<<"how many elements would you like to enter?:"; 8 | cin>>count; 9 | 10 | for (i=0; i>arr[i]; 14 | } 15 | cout<<"Enter the number that you want to search:"; 16 | cin>>num; 17 | first = 0; 18 | last = count-1; 19 | middle = (first+last)/2; 20 | while (first <= last) 21 | { 22 | if(arr[middle] < num) 23 | { 24 | first = middle + 1; 25 | 26 | } 27 | else if(arr[middle] == num) 28 | { 29 | cout< last) 38 | { 39 | cout<= $l) 5 | { 6 | $mid = ceil($l + ($r - $l) / 2); 7 | 8 | if ($arr[$mid] == $x) 9 | return floor($mid); 10 | 11 | 12 | if ($arr[$mid] > $x) 13 | return binarySearch($arr, $l, 14 | $mid - 1, $x); 15 | 16 | 17 | return binarySearch($arr, $mid + 1, 18 | $r, $x); 19 | } 20 | 21 | 22 | return -1; 23 | } 24 | 25 | 26 | $arr = array(25, 323, 43, 10, 4320); 27 | $n = count($arr); 28 | $x = 10; 29 | $result = binarySearch($arr, 0, $n - 1, $x); 30 | if(($result == -1)) 31 | echo "Element is not present in array"; 32 | else 33 | echo "Element is present at index ", 34 | $result; 35 | 36 | 37 | ?> 38 | -------------------------------------------------------------------------------- /Searching/Binary Search/Binary_Search-C.c: -------------------------------------------------------------------------------- 1 | // #include 2 | 3 | // int binary(int a[], int n, int call, int first, int last, int middle) 4 | // { 5 | // first = 0; 6 | // last = n - 1; 7 | // middle = (first + last) / 2; 8 | // while (first <= last) 9 | // { 10 | // if (a[middle] < call) 11 | // first = middle + 1; 12 | // else if (a[middle] == call) 13 | // { 14 | // printf("Element %d is found at location %d \n", call, (middle + 1)); 15 | // break; 16 | // } 17 | // else 18 | // last = middle - 1; 19 | // middle = (first + last) / 2; 20 | // } 21 | // if (first > last) 22 | // printf("%d is not present in the array \n", call); 23 | // } 24 | 25 | // int main() 26 | // { 27 | // int a[100], n, i, call, first, last, middle; 28 | // printf("Binary search is executed\n\n"); 29 | // printf("Enter the number of elements you wish to enter\n"); 30 | // scanf("%d", &n); //Elements should be sorted 31 | // printf("Enter the elements in a sorted order for binary search\n\n"); 32 | // for (i = 0; i < n; i++) //Scanning Elements 33 | // { 34 | // scanf("%d", &a[i]); 35 | // } 36 | // printf("Enter the element to search\n"); 37 | // scanf("%d", &call); //Search element 38 | // binary(a, n, call, first, last, middle); //Call to function 39 | // return 0; 40 | // } 41 | 42 | //another method 43 | #include 44 | using namespace std; 45 | 46 | int binarySearch(int a[],int n,int key){ 47 | int s=0,mid,e = n-1; 48 | 49 | while(s<=e){ 50 | mid = (s+e)/2; 51 | if(a[mid] == key){ 52 | return mid; 53 | break; 54 | } 55 | else if(a[mid]>key){ 56 | e = mid-1; 57 | } 58 | else{ 59 | s = mid+1; 60 | } 61 | } 62 | return -1; 63 | } 64 | 65 | int main() { 66 | int n; 67 | cin>>n; 68 | int a[1024]; 69 | for(int i=0;i>a[i]; 71 | } 72 | int key; 73 | cin>>key; 74 | cout< arr = [0, 1, 3, 4, 5, 8, 9, 22]; 3 | int userValue = 9; 4 | int min = 0; 5 | int max = arr.length - 1; 6 | binarySearch(arr, userValue, min, max); 7 | } 8 | 9 | binarySearch(List arr, int userValue, int min, int max) { 10 | if (max >= min) { 11 | print('min $min'); 12 | print('max $max'); 13 | int mid = ((max + min) / 2).floor(); 14 | if (userValue == arr[mid]) { 15 | print('your item is at index: ${mid}'); 16 | } else if (userValue > arr[mid]) { 17 | binarySearch(arr, userValue, mid + 1, max); 18 | } else { 19 | binarySearch(arr, userValue, min, mid - 1); 20 | } 21 | } 22 | return null; 23 | } 24 | -------------------------------------------------------------------------------- /Searching/Exponential Search/Exponential.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int array[], int start, int end, int key) { 5 | if(start <= end) { 6 | int mid = (start + (end - start) /2); //mid location of the list 7 | if(array[mid] == key) 8 | return mid; 9 | if(array[mid] > key) 10 | return binarySearch(array, start, mid-1, key); 11 | return binarySearch(array, mid+1, end, key); 12 | } 13 | return -1; 14 | } 15 | 16 | int exponentialSearch(int array[], int start, int end, int key){ 17 | if((end - start) <= 0) 18 | return -1; 19 | int i = 1; // as 2^0 = 1 20 | while(i < (end - start)){ 21 | if(array[i] < key) 22 | i *= 2; //i will increase as power of 2 23 | else 24 | break; //when array[i] corsses the key element 25 | } 26 | return binarySearch(array, i/2, i, key); //search item in the smaller range 27 | } 28 | 29 | int main() { 30 | int n, searchKey, loc; 31 | cout << "Enter number of items: "; 32 | cin >> n; 33 | int arr[n]; //create an array of size n 34 | cout << "Enter items: " << endl; 35 | for(int i = 0; i< n; i++) { 36 | cin >> arr[i]; 37 | } 38 | cout << "Enter search key to search in the list: "; 39 | cin >> searchKey; 40 | if((loc = exponentialSearch(arr, 0, n, searchKey)) >= 0) 41 | cout << "Item found at location: " << loc << endl; 42 | else 43 | cout << "Item is not found in the list." << endl; 44 | } 45 | -------------------------------------------------------------------------------- /Searching/Exponential Search/Exponential.py: -------------------------------------------------------------------------------- 1 | #exponential Search function returns the position of number in array or -1 if not found 2 | 3 | 4 | def binarySearch(A, left, right, x): 5 | 6 | if left > right: 7 | return -1 8 | 9 | mid = (left + right) // 2 10 | 11 | if x == A[mid]: 12 | return mid+1 13 | 14 | elif x < A[mid]: 15 | return binarySearch(A, left, mid - 1, x) 16 | else: 17 | return binarySearch(A, mid + 1, right, x) 18 | 19 | 20 | # Returns the position of key `x` in a given list `A` of length `n` 21 | def exponentialSearch(A, x): 22 | 23 | index = 1 24 | while index < len(A) and A[index] < x: 25 | index *= 2 26 | return binarySearch(A, index // 2, min(index, len(A)), x) 27 | 28 | print(exponentialSearch([2, 5, 6, 8, 9, 10],10)) -------------------------------------------------------------------------------- /Searching/Fibonacci-search/Explaination.txt: -------------------------------------------------------------------------------- 1 | Locate the smallest Fibonacci Number greater than or equivalent to n. Call this as 'next'. Let the two Fibonacci numbers going before it be 'second' and 'first'. 2 | 3 | While the exhibit has components to be examined: 4 | 5 | 1. Contrast key and the last element of the range secured by 'first' 6 | 7 | 2. On the off chance that key matches, return the index 8 | 9 | 3. Else If key is not exactly the element, move the three Fibonacci factors two Fibonacci down, showing disposal of around back two-third of the rest of the array. 10 | 11 | 4. Else key is greater than the element, move the three Fibonacci factors one Fibonacci down. Reset balance to file. Together these demonstrate end of around front 33% of the rest of the exhibit. 12 | 13 | 5. Since there may be a solitary component staying for examination, check if 'second' is 1. In the event that Yes, contrast key and that residual element. On the off chance that matches, return the index. 14 | 15 | 16 | 17 | Points to be noted about fibonacci search algorithm: 18 | 19 | 1. Fibonacci Search divides given array in unequal parts. 20 | 21 | 2. Fibonacci Search examines relatively closer elements in subsequent steps. So when input array is big that cannot fit in CPU cache or even in RAM, Fibonacci Search can be useful. 22 | 23 | 3. Works for sorted arrays 24 | 25 | 4. A Divide and Conquer Algorithm. 26 | 27 | 5. Has Log(n) time complexity. 28 | -------------------------------------------------------------------------------- /Searching/Fibonacci-search/fibonacci_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int fibonacciSearch(int a[], int n, int key){ 6 | int first = 0; 7 | int second = 1; 8 | int next = first + second; 9 | 10 | while(next < n){ 11 | first = second; 12 | second = next; 13 | next = first + second; 14 | } 15 | 16 | int offset = -1; 17 | 18 | while(next > 1){ 19 | int val; 20 | val = min(offset+first, n-1); 21 | 22 | if(a[val] < key){ 23 | next = second; 24 | second = first; 25 | first = next - second; 26 | offset = val; 27 | } 28 | else if(a[val] > key){ 29 | next = first; 30 | second = second - first; 31 | first = next - second; 32 | } 33 | else return val; 34 | 35 | } 36 | 37 | if(second && a[offset + 1] == key) return offset+1; 38 | 39 | return -1; 40 | 41 | } 42 | 43 | 44 | int main() 45 | { 46 | int n, i; 47 | cout << "\nEnter the size of array:"; 48 | cin >> n; 49 | int a[n]; 50 | cout << "\nEnter the elements of array:"; 51 | for(i = 0; i < n; i++){ 52 | cin >> a[i]; 53 | } 54 | int key; 55 | cout << "\n enter the value to be searched:"; 56 | cin >> key; 57 | cout << "\nFound at position:" << fibonacciSearch(a, n, key); 58 | 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /Searching/Fibonacci-search/fibonacci_search.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left 2 | 3 | def fibonacciSearch(arr, x, n): 4 | 5 | # Initialize fibonacci numbers 6 | fibonacciNum2 = 0 # (m-2)'th Fibonacci No. 7 | fibonacciNum1 = 1 # (m-1)'th Fibonacci No. 8 | fibonacciNumM = fibonacciNum2 + fibonacciNum1 # m'th Fibonacci 9 | 10 | # fibonacciNumM is going to store the smallest 11 | # Fibonacci Number greater than or equal to n 12 | while (fibonacciNumM < n): 13 | fibonacciNum2 = fibonacciNum1 14 | fibonacciNum1 = fibonacciNumM 15 | fibonacciNumM = fibonacciNum2 + fibonacciNum1 16 | 17 | # Marks the eliminated range from front 18 | offset = -1 19 | 20 | # while there are elements to be inspected. 21 | # Note that we compare arr[fibonacciNumMm2] with x. 22 | # When fibonacciNumM becomes 1, fibonacciNumMm2 becomes 0 23 | while (fibonacciNumM > 1): 24 | 25 | # Check if fibonacciNumMm2 is a valid location 26 | i = min(offset+fibonacciNum2, n-1) 27 | 28 | # If x is greater than the value at 29 | # index fibonacciNum2, cut the subarray array 30 | # from offset to i 31 | if (arr[i] < x): 32 | fibonacciNumM = fibonacciNum1 33 | fibonacciNum1 = fibonacciNum2 34 | fibonacciNum2 = fibonacciNumM - fibonacciNum1 35 | offset = i 36 | 37 | # If x is less than the value at 38 | # index fibonacciNumMm2, cut the subarray 39 | # after i+1 40 | elif (arr[i] > x): 41 | fibonacciNumM = fibonacciNum2 42 | fibonacciNum1 = fibonacciNum1 - fibonacciNum2 43 | fibonacciNum2 = fibonacciNumM - fibonacciNum1 44 | 45 | # element found. return index 46 | else: 47 | return i 48 | 49 | # comparing the last element with x */ 50 | if(fibonacciNum1 and arr[n-1] == x): 51 | return n-1 52 | 53 | # element not found. return -1 54 | return -1 55 | 56 | 57 | # Driver Code 58 | array = [2, 5, 7, 3, 1, 9, 10, 15, 16] 59 | n = len(array) 60 | toFind = 9 61 | index = fibonacciSearch(array, toFind, n) 62 | if index >= 0: 63 | print("Found at:", index) 64 | else: 65 | print(x," not found in the array"); 66 | 67 | -------------------------------------------------------------------------------- /Searching/Interpolation-Search/Interpolation-Search-CPP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | /* 7 | * Function: interpolation_search 8 | * @param[in] len : length of an array 9 | * @param[in] key : Key to be searched 10 | * @param[in] arr : Input array of keys 11 | * Return Value: index of the key or -1 (Key not found) 12 | */ 13 | int interpolation_search(int len, int key, int arr[]) 14 | { 15 | // Find indexes of two corners 16 | int st = 0, end = (len - 1); 17 | 18 | while (st <= end && key >= arr[st] && key <= arr[end]) 19 | { 20 | if (st == end) 21 | { 22 | if (arr[st] == key) return st; 23 | return -1; 24 | } 25 | 26 | int pos = st + (((double)(end - st) / (arr[end] - arr[st])) * (key - arr[st])); 27 | 28 | if (arr[pos] == key) 29 | return pos; 30 | 31 | // If key is larger, key is in upper part 32 | if (arr[pos] < key) 33 | st = pos + 1; 34 | 35 | // If key is smaller, key is in the lower part 36 | else 37 | end = pos - 1; 38 | } 39 | return -1; 40 | } 41 | 42 | 43 | int main() 44 | { 45 | int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 46 | int len = sizeof(arr) / sizeof(arr[0]); 47 | 48 | int key = 6; 49 | int idx = interpolation_search(len, key, arr); 50 | 51 | // If element was found 52 | if (idx != -1) 53 | cout << "Index of " << key << " is " << idx << endl; 54 | else 55 | cout << "Element not found" << endl; 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Searching/Interpolation-Search/Interpolation-Search.java: -------------------------------------------------------------------------------- 1 | public class Interpolation { 2 | 3 | public static void main(String[] args){ 4 | int nums[] = {23,56,212,657,754,987,1112,1535,2513}; 5 | int find = 1535; 6 | int index_result = InterpolationSearch(nums, find); 7 | System.out.println(find + " is found at index " + index_result); 8 | } 9 | 10 | public static int InterpolationSearch(int[] nums, int searched_num) { 11 | int low_num = 0; 12 | int high_num = nums.length - 1; 13 | int mid_num; 14 | while (nums[high_num] != nums[low_num] && nums[low_num] < searched_num && nums[high_num] >= searched_num) { 15 | mid_num = low_num + ((searched_num - nums[low_num]) * (high_num - low_num) / (nums[high_num] - nums[low_num])); 16 | if (searched_num > nums[mid_num]) 17 | low_num = mid_num + 1; 18 | else if (searched_num < nums[mid_num]) 19 | high_num = mid_num - 1; 20 | else 21 | return mid_num; 22 | } 23 | if (nums[low_num] == searched_num) { 24 | return low_num; 25 | } else { 26 | return -1; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Searching/Interpolation-Search/Interpolation-Search.txt: -------------------------------------------------------------------------------- 1 | Interpolation Search 2 | ==================== 3 | 4 | Interpolation Search is an improvement over Binary Search. Interpolation search may go to different 5 | locations according to the value of the key we are searching. For example, if the value of the key 6 | is near to the last element, Interpolation Search Algorithm is likely to start search toward the end side. 7 | 8 | To find the position that we have to search, it uses the following formula: 9 | 10 | pos = st + [ (x – array[st])*(end – st) / (array[end] – array[st]) ] 11 | 12 | array[] : Array where elements need to be searched 13 | x : Element to be searched 14 | st : Starting index in array[] 15 | end : Ending index in array[] 16 | 17 | 18 | Complexities 19 | ============ 20 | Time Complexity : O(log2(log2 n)) for the average case, and O(n) for the worst case (when items are 21 | distributed exponentially) 22 | Space Complexity : O(1) 23 | -------------------------------------------------------------------------------- /Searching/Jump Search/JumpSearch.cs: -------------------------------------------------------------------------------- 1 | // C# program to implement Jump Search. 2 | 3 | /*Time Complexity : O(√n) 4 | Auxiliary Space : O(1) 5 | */ 6 | 7 | 8 | /*Important Points 9 | - Works only sorted arrays. 10 | - The optimal size of a block to be jumped is (√ n). This makes the time complexity of Jump Search O(√ n). 11 | - The time complexity of Jump Search is between Linear Search ( ( O(n) ) and Binary Search ( O (Log n) ). 12 | - Binary Search is better than Jump Search, but Jump search has an advantage that we traverse back only once 13 | (Binary Search may require up to O(Log n) jumps, consider a situation where the element to be searched is 14 | the smallest element or smaller than the smallest). So in a system where binary search is costly, we use Jump Search. 15 | */ 16 | 17 | using System; 18 | public class JumpSearch 19 | { 20 | public static int jumpSearch(int[] arr, int x) 21 | { 22 | int n = arr.Length; 23 | 24 | // Finding block size to be jumped 25 | int step = (int)Math.Floor(Math.Sqrt(n)); 26 | 27 | // Finding the block where element is 28 | // present (if it is present) 29 | int prev = 0; 30 | while (arr[Math.Min(step, n)-1] < x) 31 | { 32 | prev = step; 33 | step += (int)Math.Floor(Math.Sqrt(n)); 34 | if (prev >= n) 35 | return -1; 36 | } 37 | 38 | // Doing a linear search for x in block 39 | // beginning with prev. 40 | while (arr[prev] < x) 41 | { 42 | prev++; 43 | 44 | // If we reached next block or end of 45 | // array, element is not present. 46 | if (prev == Math.Min(step, n)) 47 | return -1; 48 | } 49 | 50 | // If element is found 51 | if (arr[prev] == x) 52 | return prev; 53 | 54 | return -1; 55 | } 56 | 57 | // Driver program to test function 58 | public static void Main() 59 | { 60 | int[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 61 | 34, 55, 89, 144, 233, 377, 610}; 62 | int x = 55; 63 | 64 | // Find the index of 'x' using Jump Search 65 | int index = jumpSearch(arr, x); 66 | 67 | // Print the index where 'x' is located 68 | Console.Write("Number " + x + 69 | " is at index " + index); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /Searching/Jump Search/JumpSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | import java.util.stream.Stream; 3 | 4 | /** 5 | * Like Binary Search, Jump Search is a searching algorithm for sorted arrays. 6 | * The basic idea is to check fewer elements (than linear search) by jumping ahead by 7 | * fixed steps or skipping some elements in place of searching all elements. 8 | *

9 | * Time Complexity : O(√n) 10 | * Auxiliary Space : O(1) 11 | */ 12 | class JumpSearch { 13 | /** 14 | * Linear Search implementation 15 | * 16 | * @param array Integer List to be searched 17 | * @param value Key being searched for 18 | * @return Location of the value 19 | */ 20 | static int find(Integer[] array, Integer value) { 21 | int length = array.length; /* length of array */ 22 | int blockSize = (int) Math.sqrt(length); /* block size to be jumped */ 23 | 24 | int limit = blockSize; 25 | while (value > 0 && limit < array.length - 1) { 26 | limit = Math.min(limit + blockSize, array.length - 1); 27 | } 28 | 29 | for (int i = limit - blockSize; i <= limit; i++) { 30 | if (array[i].equals(value)) { /* execute linear search */ 31 | return i; 32 | } 33 | } 34 | return -1; /* not found */ 35 | } 36 | 37 | public static void main(String[] args) { 38 | //generate data 39 | Random random = new Random(); 40 | int size = 200; 41 | int maxElement = 100; 42 | var integers = Stream.generate(() -> random.nextInt(maxElement)).limit(size).toArray(Integer[]::new); 43 | 44 | //the element that should be found 45 | var searchValue = integers[random.nextInt(size - 1)]; 46 | 47 | int atIndex = find(integers, searchValue); 48 | 49 | if (atIndex == -1) System.out.println("Element not found!"); 50 | else System.out.println("Element found!"); 51 | 52 | System.out.println( 53 | String.format( 54 | "Value to search : %d \n" + 55 | "Found at index : %d \n" + 56 | "An array length : %d", 57 | searchValue, 58 | atIndex, 59 | size)); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Searching/Jump Search/jumpSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int jumpSearch(int arr[], int x, int n) 5 | { 6 | int step = sqrt(n); 7 | 8 | int prev = 0; 9 | while (arr[min(step, n)-1] < x) 10 | { 11 | prev = step; 12 | step += sqrt(n); 13 | if (prev >= n) 14 | return -1; 15 | } 16 | 17 | while (arr[prev] < x) 18 | { 19 | prev++; 20 | 21 | if (prev == min(step, n)) 22 | return -1; 23 | } 24 | 25 | if (arr[prev] == x) 26 | return prev; 27 | 28 | return -1; 29 | } 30 | 31 | int main() 32 | { 33 | int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 | 34, 55, 89, 144, 233, 377, 610 }; 35 | int x = 55; 36 | int n = sizeof(arr) / sizeof(arr[0]); 37 | 38 | int index = jumpSearch(arr, x, n); 39 | 40 | cout << "\nNumber " << x << " is at index " << index; 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Searching/Linear Search/Linear Search - Ruby.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | def linear_search(data, item) 4 | data.each_with_index do |element, index| 5 | return index if element == item 6 | end 7 | 8 | -1 # Element Not Found 9 | end 10 | 11 | data = [10, 2, 5, 16, 9, 13, 25, 30, 45, 100] 12 | 13 | puts "Data = #{data}" 14 | puts 15 | puts "Index for Item 2 = #{linear_search(data, 2)}" 16 | puts "Index for Item 9 = #{linear_search(data, 9)}" 17 | puts "Index for Item 30 = #{linear_search(data, 30)}" 18 | puts "Index for Item 100 = #{linear_search(data, 100)}" 19 | puts "Index for Item 99999 = #{linear_search(data, 99_999)}" 20 | puts "Index for Item 1 in empty data = #{linear_search([], 1)}" 21 | -------------------------------------------------------------------------------- /Searching/Linear Search/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int a[20],n,x,i,flag=0; 8 | cout<<"How many elements?"; 9 | cin>>n; 10 | cout<<"\nEnter elements of the array\n"; 11 | 12 | for(i=0;i>a[i]; 14 | 15 | cout<<"\nEnter element to search:"; 16 | cin>>x; 17 | 18 | for(i=0;i 2 | 3 | int linear(int a[], int n, int call) 4 | { 5 | int i; 6 | for (i = 0; i < n; i++) 7 | { 8 | if (a[i] == call) 9 | { 10 | printf("Element %d found at index %d \n\n\n\n", call, i); 11 | break; 12 | } 13 | } 14 | if (i == n) 15 | printf("Element not found in the array \n\n\n\n"); 16 | } 17 | 18 | int main() 19 | { 20 | int a[100], n, i, call, first, last, middle; 21 | 22 | printf("Linear search is executed\n\n"); 23 | printf("Enter the number of elements you wish to enter\n"); 24 | scanf("%d", &n); //Elements need not be sorted 25 | printf("Enter the elements\n\n"); 26 | for (i = 0; i < n; i++) //Scanning Elements 27 | { 28 | scanf("%d", &a[i]); 29 | } 30 | printf("Enter the element to search\n"); 31 | scanf("%d", &call); 32 | linear(a, n, call); //Call to function 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Searching/Linear Search/Linear_Search-C#.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | class GFG 4 | { 5 | public static int search(int[] arr, int x) 6 | { 7 | int n = arr.Length; 8 | for(int i = 0; i < n; i++) 9 | { 10 | if(arr[i] == x) 11 | return i; 12 | } 13 | return -1; 14 | } 15 | 16 | public static void Main() 17 | { 18 | int[] arr = { 2, 3, 4, 10, 40 }; 19 | int x = 10; 20 | 21 | int result = search(arr, x); 22 | if(result == -1) 23 | Console.WriteLine("Element is not present in array"); 24 | else 25 | Console.WriteLine("Element is present at index "+ result); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Searching/Linear Search/Linearsearch_adiksha20.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class LinearSearch 3 | { 4 | public static void main(String args[]) 5 | { 6 | Scanner sc=new Scanner(System.in); 7 | int n=sc.nextInt();// Enter the size of an array 8 | int a[]=new int[n]; 9 | for(int i=0;i 2 | #include 3 | 4 | using namespace std; 5 | 6 | /* 7 | * Function: ternary_search 8 | * @param[in] l : leftmost element to search from 9 | * @param[in] r : righmostmost element to search from 10 | * @param[in] key : Key to be searched 11 | * @param[in] arr : Input array of keys 12 | * Return Value: index of the key or -1 (Key not found) 13 | */ 14 | int ternary_search(int l, int r, int key, int arr[]) 15 | { 16 | if (r >= l) { 17 | 18 | // Find the mid_first and mid_second 19 | int mid_first = l + (r - l) / 3; 20 | int mid_second = r - (r - l) / 3; 21 | 22 | // Check if key is present at any mids 23 | if (arr[mid_first] == key) { 24 | return mid_first; 25 | } 26 | 27 | if (arr[mid_second] == key) { 28 | return mid_second; 29 | } 30 | 31 | /* Since key is not present at mid, check in which region it is present 32 | * then repeat the Search operation in that region */ 33 | if (key < arr[mid_first]) { 34 | 35 | // The key lies in between l and mid_first 36 | return ternary_search(l, mid_first - 1, key, arr); 37 | } 38 | else if (key > arr[mid_second]) { 39 | 40 | // The key lies in between mid_second and r 41 | return ternary_search(mid_second + 1, r, key, arr); 42 | } 43 | else { 44 | 45 | // The key lies in between mid_first and mid_second 46 | return ternary_search(mid_first + 1, mid_second - 1, key, arr); 47 | } 48 | } 49 | 50 | // Key not found 51 | return -1; 52 | } 53 | 54 | 55 | int main() 56 | { 57 | int key, idx; 58 | 59 | // Get the sorted array 60 | int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 61 | 62 | // length of array 63 | int len = sizeof(arr)/sizeof(arr[0]);; 64 | 65 | /* Case 1: Search a valid key */ 66 | key = 5; 67 | idx = ternary_search(0, len, key, arr); 68 | cout << "Index of " << key << " is " << idx << endl; 69 | 70 | /* Case 2: Search an invalid key */ 71 | key = 50; 72 | idx = ternary_search(0, len, key, arr); 73 | 74 | // Print the result 75 | cout << "Index of " << key << " is " << idx << endl; 76 | } 77 | -------------------------------------------------------------------------------- /Searching/Ternary-Search/Ternary-Search-Java.java: -------------------------------------------------------------------------------- 1 | package com.company; 2 | 3 | public class Main { 4 | 5 | 6 | public static void main(String[] args) { 7 | int l, r, p, key; 8 | 9 | // Get the array 10 | // Sort the array if not sorted 11 | int[] ar; 12 | ar = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 13 | 14 | // Starting index 15 | l = 0; 16 | 17 | // length of array 18 | r = 9; 19 | 20 | // Checking for 5 21 | 22 | // Key to be searched in the array 23 | key = 5; 24 | 25 | // Search the key using ternarySearch 26 | p = ternarySearch(l, r, key, ar); 27 | 28 | // Print the result 29 | System.out.println("Index of " + key + " is " + p); 30 | 31 | // Checking for 50 32 | 33 | // Key to be searched in the array 34 | key = 50; 35 | 36 | // Search the key using ternarySearch 37 | p = ternarySearch(l, r, key, ar); 38 | 39 | // Print the result 40 | System.out.println("Index of " + key + " is " + p); 41 | } 42 | static int ternarySearch(int l, int r, int key, int ar[]) 43 | { 44 | if (r >= l) { 45 | 46 | // Find the mid1 and mid2 47 | int mid1 = l + (r - l) / 3; 48 | int mid2 = r - (r - l) / 3; 49 | 50 | // Check if key is present at any mid 51 | if (ar[mid1] == key) { 52 | return mid1; 53 | } 54 | if (ar[mid2] == key) { 55 | return mid2; 56 | } 57 | 58 | // Since key is not present at mid, 59 | // check in which region it is present 60 | // then repeat the Search operation 61 | // in that region 62 | 63 | if (key < ar[mid1]) { 64 | 65 | // The key lies in between l and mid1 66 | return ternarySearch(l, mid1 - 1, key, ar); 67 | } 68 | else if (key > ar[mid2]) { 69 | 70 | // The key lies in between mid2 and r 71 | return ternarySearch(mid2 + 1, r, key, ar); 72 | } 73 | else { 74 | 75 | // The key lies in between mid1 and mid2 76 | return ternarySearch(mid1 + 1, mid2 - 1, key, ar); 77 | } 78 | } 79 | 80 | // Key not found 81 | return -1; 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /Searching/Ternary-Search/Ternary-Search.txt: -------------------------------------------------------------------------------- 1 | Ternary Search 2 | ============== 3 | 4 | Like the binary search, it also separates the lists into sub-lists. This procedure divides 5 | the list into three parts using two intermediate mid values. As the lists are divided into 6 | more subdivisions, so it reduces the time to search a key value. The complexity of Ternary 7 | Search Technique 8 | 9 | Complexities 10 | ============ 11 | Time Complexity: O(log3 n) 12 | Space Complexity: O(1) 13 | -------------------------------------------------------------------------------- /Stacks/Balanced-Braces.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | int scan(string); 7 | 8 | int main(){ 9 | string st; 10 | cout<<"Enter the code snippet (press'^' to exit):\n"; 11 | getline(cin,st,'^'); 12 | scan(st); 13 | return 0; 14 | } 15 | 16 | int scan(string st){ 17 | stack S; 18 | for(int i=0;i 2 | #include 3 | #include 4 | 5 | #define MAX 50 6 | 7 | typedef struct stack 8 | { 9 | int data[MAX]; 10 | int top; 11 | }stack; 12 | 13 | int precedence(char); 14 | void init(stack *); 15 | int empty(stack *); 16 | int full(stack *); 17 | int pop(stack *); 18 | void push(stack *,int); 19 | int top(stack *); //value of the top element 20 | void infix_to_postfix(char infix[],char postfix[]); 21 | 22 | int main() 23 | { 24 | char infix[30],postfix[30]; 25 | printf("Enter an infix expression(Donot leave space between characters):"); 26 | gets(infix); 27 | infix_to_postfix(infix,postfix); 28 | printf("\nPostfix expression: %s",postfix); 29 | return 0; 30 | } 31 | 32 | void infix_to_postfix(char infix[],char postfix[]) 33 | { 34 | stack s; 35 | char x,token; 36 | int i,j; //i-index of infix,j-index of postfix 37 | init(&s); 38 | j=0; 39 | 40 | for(i=0;infix[i]!='\0';i++) 41 | { 42 | token=infix[i]; 43 | if(isalnum(token)) 44 | postfix[j++]=token; 45 | else 46 | if(token=='(') 47 | push(&s,'('); 48 | else 49 | if(token==')') 50 | while((x=pop(&s))!='(') 51 | postfix[j++]=x; 52 | else 53 | { 54 | while(precedence(token)<=precedence(top(&s))&&!empty(&s)) 55 | { 56 | x=pop(&s); 57 | postfix[j++]=x; 58 | } 59 | push(&s,token); 60 | } 61 | } 62 | 63 | while(!empty(&s)) 64 | { 65 | x=pop(&s); 66 | postfix[j++]=x; 67 | } 68 | 69 | postfix[j]='\0'; 70 | } 71 | 72 | int precedence(char x) 73 | { 74 | if(x=='(') 75 | return(0); 76 | if(x=='+'||x=='-') 77 | return(1); 78 | if(x=='*'||x=='/'||x=='%') 79 | return(2); 80 | 81 | return(3); 82 | } 83 | 84 | void init(stack *s) 85 | { 86 | s->top=-1; 87 | } 88 | 89 | int empty(stack *s) 90 | { 91 | if(s->top==-1) 92 | return(1); 93 | 94 | return(0); 95 | } 96 | 97 | int full(stack *s) 98 | { 99 | if(s->top==MAX-1) 100 | return(1); 101 | 102 | return(0); 103 | } 104 | 105 | void push(stack *s,int x) 106 | { 107 | s->top=s->top+1; 108 | s->data[s->top]=x; 109 | } 110 | 111 | int pop(stack *s) 112 | { 113 | int x; 114 | x=s->data[s->top]; 115 | s->top=s->top-1; 116 | return(x); 117 | } 118 | 119 | int top(stack *p) 120 | { 121 | return (p->data[p->top]); 122 | } 123 | 124 | -------------------------------------------------------------------------------- /Stacks/NextGreaterElement.py: -------------------------------------------------------------------------------- 1 | def createStack(): 2 | stack = [] 3 | return stack 4 | 5 | def isEmpty(stack): 6 | return len(stack) == 0 7 | 8 | def push(stack, x): 9 | stack.append(x) 10 | 11 | def pop(stack): 12 | if isEmpty(stack): 13 | print("Error : stack underflow") 14 | else: 15 | return stack.pop() 16 | 17 | '''prints element and NGE pair for all elements of 18 | arr[] ''' 19 | def printNGE(arr): 20 | s = createStack() 21 | element = 0 22 | next = 0 23 | 24 | # push the first element to stack 25 | push(s, arr[0]) 26 | 27 | # iterate for rest of the elements 28 | for i in range(1, len(arr), 1): 29 | next = arr[i] 30 | 31 | if isEmpty(s) == False: 32 | 33 | # if stack is not empty, then pop an element from stack 34 | element = pop(s) 35 | 36 | '''If the popped element is smaller than next, then 37 | a) print the pair 38 | b) keep popping while elements are smaller and 39 | stack is not empty ''' 40 | while element < next : 41 | print(str(element)+ " -- " + str(next)) 42 | if isEmpty(s) == True : 43 | break 44 | element = pop(s) 45 | 46 | '''If element is greater than next, then push 47 | the element back ''' 48 | if element > next: 49 | push(s, element) 50 | 51 | '''push next to stack so that we can find 52 | next greater for it ''' 53 | push(s, next) 54 | 55 | '''After iterating over the loop, the remaining 56 | elements in stack do not have the next greater 57 | element, so print -1 for them ''' 58 | 59 | while isEmpty(s) == False: 60 | element = pop(s) 61 | next = -1 62 | print(str(element) + " -- " + str(next)) 63 | 64 | # Driver program to test above functions 65 | arr = [11, 13, 21, 3] 66 | printNGE(arr) 67 | -------------------------------------------------------------------------------- /Stacks/Prefix Evaluation/PrefixEvaluation: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | void WriteRPNExpression(char expression[]); 10 | void ReverseArray (char arr []); 11 | bool isNumber(char &exp); 12 | 13 | int main() 14 | { 15 | stack s; 16 | char expression [] = "/2*+435"; 17 | 18 | WriteRPNExpression(expression);//display our rpn expression on the screen 19 | 20 | cout< 4 | using namespace std; 5 | 6 | void insertatbottom (stack &st,int ele){ 7 | 8 | if(st.empty()){ 9 | st.push(ele); 10 | return; 11 | } 12 | int topele=st.top(); 13 | st.pop(); 14 | 15 | insertatbottom(st,ele); 16 | 17 | st.push(topele); 18 | } 19 | 20 | void reverse(stack &st){ 21 | 22 | if(st.empty()){ 23 | return ; 24 | } 25 | int ele=st.top(); 26 | st.pop(); 27 | 28 | reverse(st); 29 | 30 | insertatbottom(st,ele); 31 | } 32 | int main(){ 33 | stack st; 34 | int n; 35 | cin>>n; 36 | for(int i=0;i>x; 39 | st.push(x); 40 | } 41 | reverse(st); 42 | while(!st.empty()){ 43 | cout< 6 | using namespace std; 7 | 8 | bool IsPalindrome( string s ){ 9 | int i = 0; 10 | int j = s.length()-1; 11 | while(i<=j){ 12 | if(s[i]!=s[j]) 13 | return false; 14 | i++; 15 | j--; 16 | } 17 | return true; 18 | } 19 | 20 | int main() 21 | { 22 | string s; 23 | cout<<"\n\tEnter a string : "; 24 | cin>>s; 25 | if(IsPalindrome(s)) 26 | cout<<"\n\t\t"< 11 | using namespace std; 12 | 13 | void getSmallestAndLargest(string str, int k) 14 | { 15 | // Initializing min and max as first substring of size k 16 | string currStr = str.substr(0, k); 17 | string lexMin = currStr; 18 | string lexMax = currStr; 19 | 20 | // Consider all remaining substrings. We consider every substring ending with index i. 21 | for (int itr = k; itr < str.length(); itr++){ 22 | currStr = currStr.substr(1, k) + str[itr]; 23 | if (lexMax < currStr) lexMax = currStr; 24 | if (lexMin >currStr) lexMin = currStr; 25 | } 26 | 27 | // Printing result 28 | cout << lexMin << endl; 29 | cout << lexMax << endl; 30 | } 31 | 32 | 33 | int main(){ 34 | string str = "AkashSahu"; 35 | int k = 3; 36 | getSmallestAndLargest(str, k); 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Strings/Lexicographically-smallest-largest/Lexicographically-smallest-largest-python.py: -------------------------------------------------------------------------------- 1 | def getSmallestLargest(s, k): 2 | curr = s[:k] 3 | lexmin = curr 4 | lexmax = curr 5 | for i in range(k, len(s)): 6 | curr = curr[1:k] + s[i] 7 | if lexmax < curr: 8 | lexmax = curr 9 | if lexmin > curr: 10 | lexmin = curr 11 | 12 | return lexmin, lexmax 13 | 14 | s = "shaonakundu" 15 | k = 3 16 | res = getSmallestLargest(s, k) 17 | print(res) -------------------------------------------------------------------------------- /Strings/Lexicographically-smallest-largest/Lexicographically-smallest-largest-python.txt: -------------------------------------------------------------------------------- 1 | The term lexicographically means Dictionary format, i.e 2 | Given a string here "shaonakundu" in groups of size 3(k=3), we have to find the smallest and largest or greatest substring. 3 | Initially from the beginning the first k letters are chosen as both min and max lexicographically. 4 | Then a for loop is implemented to iterate over entire string for size of k and compare by removing one letter from the beginning and adding (k+1)th letter to form new substring. 5 | 6 | After running this python code we get: ('aku', 'und') as the smallest and largest substring lexicographically. 7 | 8 | Note: one can take user input for both string(s) and k so that one can experiment with different examples. Here I have taken particular string. 9 | 10 | Author - Shaona Kundu -------------------------------------------------------------------------------- /Strings/Longest-common-subsequence/longest_common_subsequence-C++.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Longest Common Subsequence Problem Statement: Given two sequences, find the length of longest 3 | subsequence present in both of them. 4 | * A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. 5 | * Given below is the implementation of the solution to this problem using Dynamic Programming approach. 6 | */ 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int LCS(char* a,char* b,int m,int n) 12 | { 13 | int S[11][11]; 14 | int i,j; 15 | for(i=0;i<=m;i++) 16 | { 17 | for(j=0;j<=n;j++) 18 | { 19 | if(i==0 || j==0) 20 | { 21 | S[i][j]=0; 22 | } 23 | else if(a[i-1]==b[j-1]) 24 | { 25 | S[i][j]= S[i-1][j-1] + 1; 26 | } 27 | else 28 | { 29 | S[i][j]= max(S[i-1][j],S[i][j-1]); 30 | } 31 | } 32 | } 33 | return S[m][n]; 34 | } 35 | int main() 36 | { 37 | char A[30],B[30]; 38 | cout<<"Enter the string 1 : "; 39 | cin>>A; 40 | cout<<"\nEnter the string 2 : "; 41 | cin>>B; 42 | int m=strlen(A); 43 | int n=strlen(B); 44 | int l= LCS(A,B,m,n); 45 | cout<<"\nLength of longest common subsequence : "< 8 | using namespace std; 9 | void patternMatching(string T, string P) 10 | { 11 | int m = T.size(); 12 | int n = P.size(); 13 | for(int i = 0; i <= m-n; i++) 14 | { 15 | int j; 16 | for(j = 0; j < n; j++) 17 | { 18 | if(T[i+j] != P[j]) 19 | { 20 | break; 21 | } 22 | } 23 | if(j == n) 24 | { 25 | cout<<"Pattern found at "< 2 | #include 3 | 4 | struct node 5 | { 6 | int key; 7 | struct node *left, *right; 8 | }; 9 | 10 | // A utility function to create a new BST node 11 | struct node *newNode(int item) 12 | { 13 | struct node *temp = (struct node *)malloc(sizeof(struct node)); 14 | temp->key = item; 15 | temp->left = temp->right = NULL; 16 | return temp; 17 | } 18 | 19 | // A utility function to do inorder traversal of BST 20 | void inorder(struct node *root) 21 | { 22 | if (root != NULL) 23 | { 24 | inorder(root->left); 25 | printf("%d \n", root->key); 26 | inorder(root->right); 27 | } 28 | } 29 | 30 | /* A utility function to insert a new node with given key in BST */ 31 | struct node* insert(struct node* node, int key) 32 | { 33 | /* If the tree is empty, return a new node */ 34 | if (node == NULL) return newNode(key); 35 | 36 | /* Otherwise, recur down the tree */ 37 | if (key < node->key) 38 | node->left = insert(node->left, key); 39 | else if (key > node->key) 40 | node->right = insert(node->right, key); 41 | 42 | /* return the (unchanged) node pointer */ 43 | return node; 44 | } 45 | 46 | // Driver Program to test above functions 47 | int main() 48 | { 49 | /* Let us create following BST 50 | 50 51 | / \ 52 | 30 70 53 | / \ / \ 54 | 20 40 60 80 */ 55 | struct node *root = NULL; 56 | root = insert(root, 50); 57 | insert(root, 30); 58 | insert(root, 20); 59 | insert(root, 40); 60 | insert(root, 70); 61 | insert(root, 60); 62 | insert(root, 80); 63 | 64 | // print inoder traversal of the BST 65 | inorder(root); 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Trees/Complete binary tree/complete_bt- java.java: -------------------------------------------------------------------------------- 1 | 2 | public class TreeNode { 3 | int val; 4 | TreeNode left; 5 | TreeNode right; 6 | TreeNode() {} 7 | TreeNode(int val) { this.val = val; } 8 | TreeNode(int val, TreeNode left, TreeNode right) { 9 | this.val = val; 10 | this.left = left; 11 | this.right = right; 12 | } 13 | } 14 | class Solution { 15 | public boolean isCompleteTree(TreeNode root) { 16 | int prev=root.val; 17 | Queue q=new LinkedList(); 18 | q.add(root); 19 | while(!q.isEmpty()) 20 | { 21 | int s=q.size(); 22 | for(int i=0;ileft) 4 | p=p->left; 5 | return p; 6 | } 7 | 8 | Node *deleteNode(Node *root, int x) 9 | { 10 | if(root==NULL) 11 | return NULL; 12 | else if(xdata) root->left=deleteNode(root->left,x); 13 | else if (x>root->data) root->right=deleteNode(root->right,x); 14 | else 15 | { 16 | if(root->left==NULL && root->right==NULL) 17 | { 18 | delete root; 19 | root=NULL; 20 | } 21 | else if(root->left==NULL) 22 | { 23 | Node *temp=root; 24 | root=root->right; 25 | delete temp; 26 | } 27 | else if(root->right==NULL) 28 | { 29 | Node *temp=root; 30 | root=root->left; 31 | delete temp; 32 | } 33 | else 34 | { 35 | Node *temp=minimum(root->right); 36 | root->data=temp->data; 37 | root->right = deleteNode(root->right,root->data); 38 | } 39 | 40 | } 41 | return root; 42 | 43 | } 44 | 45 | int main() 46 | { 47 | /*create tree on your own 48 | and call the delete node function*/ 49 | return 0; 50 | } -------------------------------------------------------------------------------- /Trees/Diagonal Traversal/Diagonal Traversal-C++.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for diagonal traversal of Binary Tree 2 | 3 | #include 4 | using namespace std; 5 | 6 | struct Node 7 | { 8 | int data; 9 | Node *left, *right; 10 | }; 11 | 12 | void diagonalPrintUtil(Node* root, int d, 13 | map > &diagonalPrint) 14 | { 15 | if (!root) 16 | return; 17 | 18 | diagonalPrint[d].push_back(root->data); 19 | 20 | diagonalPrintUtil(root->left, d + 1, diagonalPrint); 21 | 22 | diagonalPrintUtil(root->right, d, diagonalPrint); 23 | } 24 | 25 | void diagonalPrint(Node* root) 26 | { 27 | map > diagonalPrint; 28 | diagonalPrintUtil(root, 0, diagonalPrint); 29 | 30 | cout << "Diagonal Traversal of binary tree : "<second.begin(); itr != it->second.end(); ++itr) 34 | cout << *itr << ' '; 35 | 36 | cout << endl; 37 | } 38 | } 39 | 40 | Node* newNode(int data) 41 | { 42 | Node* node = new Node; 43 | node->data = data; 44 | node->left = node->right = NULL; 45 | return node; 46 | } 47 | 48 | int main() 49 | { 50 | Node* root = newNode(8); 51 | root->left = newNode(3); 52 | root->right = newNode(10); 53 | root->left->left = newNode(1); 54 | root->left->right = newNode(6); 55 | root->right->right = newNode(14); 56 | root->right->right->left = newNode(13); 57 | root->left->right->left = newNode(4); 58 | root->left->right->right = newNode(7); 59 | 60 | 61 | diagonalPrint(root); 62 | 63 | return 0; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /Trees/Diameter of Binary Tree/diameter.java: -------------------------------------------------------------------------------- 1 | public class Node { 2 | int val; 3 | Node left; 4 | Node right; 5 | Node() {} 6 | Node(int val) { this.val = val; } 7 | Node(int val, Node left, Node right) { 8 | this.val = val; 9 | this.left = left; 10 | this.right = right; 11 | } 12 | } 13 | 14 | class Solution { 15 | public int diameterOfBinaryTree(Node root) { 16 | diameter(root); 17 | return dia; 18 | } 19 | 20 | int dia=0; 21 | public int diameter(Node root){ 22 | if(root==null) 23 | return -1; 24 | int lh=diameter(root.left); 25 | int rh=diameter(root.right); 26 | 27 | dia=Math.max(dia,lh+rh+2); 28 | return Math.max(lh,rh)+1; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Trees/Fenwick_Tree/Fenwick_Python3.py: -------------------------------------------------------------------------------- 1 | #Python - Binary Indexed Tree 2 | 3 | #Returns sum of arr[0..index] 4 | def getsum(BITTree,i): 5 | s = 0 6 | i = i+1 7 | while i > 0: 8 | s += BITTree[i] 9 | i -= i & (-i) 10 | return s 11 | 12 | #Updates a node in BITree at given index 13 | def updatebit(BITTree , n , i ,v): 14 | i += 1 15 | while i <= n: 16 | BITTree[i] += v 17 | i += i & (-i) 18 | 19 | #Rreturns a BITree for given array 20 | def construct(arr, n): 21 | BITTree = [0]*(n+1) 22 | for i in range(n): 23 | updatebit(BITTree, n, i, arr[i]) 24 | return BITTree 25 | -------------------------------------------------------------------------------- /Trees/Inorder_Traversal/Inorder Traversal-Java.java: -------------------------------------------------------------------------------- 1 | /* 2 | Algorithm Inorder(tree) 3 | 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 4 | 2. Visit the root. 5 | 3. Traverse the right subtree, i.e., call Inorder(right-subtree) 6 | */ 7 | 8 | class Node 9 | { 10 | int key; 11 | Node left, right; 12 | 13 | public Node(int item) 14 | { 15 | key = item; 16 | left = right = null; 17 | } 18 | } 19 | 20 | class Solution 21 | { 22 | void printInorder(Node node) 23 | { 24 | if (node == null) 25 | return; 26 | 27 | printInorder(node.left); //recursive call on left child 28 | System.out.print(node.key + " "); 29 | printInorder(node.right); //recursive call on right child 30 | } 31 | 32 | public static void main(String[] args) 33 | { 34 | //creating a binary tree 35 | Node root = new Node(1) 36 | root.left = new Node(2); 37 | root.right = new Node(3); 38 | root.left.left = new Node(4); 39 | root.left.right = new Node(5); 40 | 41 | System.out.println("\nInorder traversal of binary tree is "); 42 | tree.printInorder(); 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Trees/Inorder_Traversal/Inorder Traversal_C++.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | struct Node 6 | { 7 | int data; 8 | struct Node* left, *right; 9 | Node(int data) 10 | { 11 | this->data = data; 12 | left = right = NULL; 13 | } 14 | }; 15 | 16 | void Inorder(struct Node* node) 17 | { 18 | if (node == NULL) 19 | return; 20 | 21 | Inorder(node->left); 22 | 23 | cout << node->data << " "; 24 | 25 | Inorder(node->right); 26 | } 27 | -------------------------------------------------------------------------------- /Trees/Inorder_Traversal/InorderTraversal_Python3.py: -------------------------------------------------------------------------------- 1 | # This code is written in Python3 2 | """ 3 | This is the implementation of the Inorder traversal in Tree. 4 | Algorithm Inorder(tree) 5 | 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 6 | 2. Visit the root. 7 | 3. Traverse the right subtree, i.e., call Inorder(right-subtree) 8 | 9 | Uses of Inorder 10 | In case of binary search trees (BST), 11 | Inorder traversal gives nodes in non-decreasing order. 12 | To get nodes of BST in non-increasing order, 13 | a variation of Inorder traversal where Inorder traversal s reversed can be used. 14 | """ 15 | 16 | 17 | # To create a node 18 | class node: 19 | """docstring for node""" 20 | def __init__(self, data): 21 | self.data = data 22 | self.left = None 23 | self.right = None 24 | 25 | # TO create class of Tree data Structure 26 | class TreeDS: 27 | """docstring for TreeDS""" 28 | def __init__(self): 29 | self.root = None 30 | 31 | # To check if the tree is empty or not 32 | def is_empty(self): 33 | return self.root is None 34 | 35 | # IMP : Code to do inorder traversal of the tree. 36 | def inorder_tree(self, temp): 37 | while temp is not None: 38 | self.inorder_tree(temp.left) 39 | print(temp.data, end="-") 40 | self.inorder_tree(temp.right) 41 | return 42 | 43 | # To push node with a value into the tree based on the data inside it 44 | def push(self, data): 45 | newnode = node(data) 46 | if self.is_empty(): 47 | self.root = newnode 48 | return 49 | temp = self.root 50 | while True: 51 | if newnode.data < temp.data: 52 | if temp.left is None: 53 | temp.left = newnode 54 | return 55 | temp = temp.left 56 | if newnode.data > temp.data: 57 | if temp.right is None: 58 | temp.right = newnode 59 | return 60 | temp = temp.right 61 | 62 | 63 | # Code to declare the Tree 64 | T = TreeDS() 65 | 66 | # Code to push following values into the tree. 67 | T.push(5) 68 | T.push(3) 69 | T.push(4) 70 | T.push(1) 71 | T.push(7) 72 | T.push(6) 73 | 74 | # calling inorder tree and other print functions to make it readable 75 | print("inorder_tree: ") 76 | T.inorder_tree(T.root) 77 | print("end") -------------------------------------------------------------------------------- /Trees/Inorder_Traversal/inorder.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct node { 5 | int data; 6 | struct node *left, *right; 7 | }node; 8 | typedef node *tree; 9 | 10 | void inorder(node* root) { 11 | if (!root) 12 | return; 13 | inorder(root->left); 14 | printf("%d ", root->data); 15 | inorder(root->right); 16 | } 17 | 18 | struct node* newNode(int data) 19 | { 20 | struct node* node = (struct node*)malloc(sizeof(struct node)); 21 | node->data = data; 22 | node->left = NULL; 23 | node->right = NULL; 24 | 25 | return(node); 26 | } 27 | int main() { 28 | struct node* root = newNode(15); 29 | root->left = newNode(10); 30 | root->right = newNode(20); 31 | root->left->right = newNode(12); 32 | inorder(root); 33 | printf("\n"); 34 | return 0; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Trees/Inorder_Traversal/iteratve_inorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node* left; 8 | struct Node* right; 9 | Node (int data) 10 | { 11 | this->data = data; 12 | left = right = NULL; 13 | } 14 | }; 15 | 16 | void inOrder(struct Node *root) 17 | { 18 | stack s; 19 | Node *curr = root; 20 | 21 | while (curr != NULL || s.empty() == false) 22 | { 23 | while (curr != NULL) 24 | { 25 | s.push(curr); 26 | curr = curr->left; 27 | } 28 | curr = s.top(); 29 | s.pop(); 30 | 31 | cout << curr->data << " "; 32 | 33 | curr = curr->right; 34 | 35 | } 36 | } 37 | int main() 38 | { 39 | 40 | struct Node *root = new Node(1); 41 | root->left = new Node(2); 42 | root->right = new Node(3); 43 | root->left->left = new Node(4); 44 | root->left->right = new Node(5); 45 | /* 46 | tree: 47 | 1 48 | / \ 49 | 2 3 50 | / \ 51 | 4 5 52 | */ 53 | inOrder(root); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /Trees/LevelOrderTraversal/LevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *left, *right; 8 | }; 9 | 10 | void printLevelOrder(Node *root) 11 | { 12 | if (root == NULL) return; 13 | 14 | // Create an empty queue for level order traversal 15 | queue q; 16 | 17 | q.push(root); 18 | 19 | while (q.empty() == false) 20 | { 21 | Node *node = q.front(); 22 | cout << node->data << " "; 23 | q.pop(); 24 | 25 | /* Enqueue left child */ 26 | if (node->left != NULL) 27 | q.push(node->left); 28 | 29 | /*Enqueue right child */ 30 | if (node->right != NULL) 31 | q.push(node->right); 32 | } 33 | } 34 | 35 | Node* newNode(int data) 36 | { 37 | Node *temp = new Node; 38 | temp->data = data; 39 | temp->left = temp->right = NULL; 40 | return temp; 41 | } 42 | 43 | int main() 44 | { 45 | Node *root = newNode(1); 46 | root->left = newNode(2); 47 | root->right = newNode(3); 48 | root->left->left = newNode(4); 49 | root->left->right = newNode(5); 50 | 51 | cout << "Level Order traversal of binary tree is \n"; 52 | printLevelOrder(root); 53 | return 0; 54 | } 55 | 56 | -------------------------------------------------------------------------------- /Trees/LevelOrderTraversal/LevelOrderTraversal.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class LevelOrderTraversal{ 3 | public static void main(String[] args){ 4 | 5 | TreeNode root = formSampleTree(); 6 | ArrayList> levelOrderList = getLevelOrderTraversal(root); 7 | 8 | if(levelOrderList!=null){ 9 | int counter = 1; 10 | for(ArrayList eachLevel : levelOrderList){ 11 | System.out.println("Level #"+(counter++)+" "+eachLevel); 12 | } 13 | } 14 | 15 | } 16 | 17 | private static ArrayList> getLevelOrderTraversal(TreeNode root){ 18 | 19 | if(root == null){ 20 | return null; 21 | } 22 | ArrayList> levelOrderTraversal = new ArrayList>(); 23 | Queue queue = new LinkedList(); 24 | 25 | queue.add(root); 26 | while(!queue.isEmpty()){ 27 | 28 | int levelSize = queue.size(); 29 | ArrayList eachLevel = new ArrayList(); 30 | for(int i=0;i left) 11 | 2. Get maximum height from the right subtree of current node recursively 12 | call maxHeight(node -> right) 13 | 3. Calculate maximum height among left and right subtree and add + 1 to it (count the current node) 14 | 4. Return the calculated maximum height from Step 3. 15 | 16 | 17 | 18 | Example Tree used 19 | ``` 20 | 1 21 | / \ 22 | 2 3 23 | / \ 24 | 4 5 25 | / 26 | 6 27 | ``` 28 | 29 | In the above diagram, 30 | - Values at each node defines node number 31 | - Text besides each node explaines maximum heights returned by left and right subtrees in the form of **L** and **H** characters respectively. 32 | - **Ret** defines value returned by the node when recursive function called onto that node 33 | 34 | The maximum height in terms of the nodes is **4** in the above tree. 35 | 36 | To run the above code you need to follow follwing steps in the terminal (gcc must be installed) 37 | 1. `> g++ maxHeightC++.cpp -o maxHeight` 38 | 2. `> ./maxHeight` -------------------------------------------------------------------------------- /Trees/Max Height Tree/maxHeightC++.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | /* class to store all the data about Node of a tree */ 6 | class TreeNode 7 | { 8 | public: 9 | int data; 10 | TreeNode* left; 11 | TreeNode* right; 12 | }; 13 | 14 | /* Recursive function to get maximum depth/Height of a tree based 15 | on the maximum of left or right subtree of every node. */ 16 | int maxHeight(TreeNode* node) 17 | { 18 | if (node == NULL) 19 | return 0; 20 | else 21 | { 22 | /* compute the height of each subtree */ 23 | int leftH = maxHeight(node->left); 24 | int rightH = maxHeight(node->right); 25 | 26 | /* return the larger among left and right */ 27 | return (max(leftH, rightH) + 1); 28 | } 29 | } 30 | 31 | /* Function to create New Node */ 32 | TreeNode* newNode(int data) 33 | { 34 | TreeNode* Node = new TreeNode(); 35 | Node->data = data; 36 | Node->left = NULL; 37 | Node->right = NULL; 38 | 39 | return(Node); 40 | } 41 | 42 | //Main function 43 | 44 | 45 | /* Example Tree used 46 | 47 | 1 48 | / \ 49 | 2 3 50 | / \ 51 | 4 5 52 | / 53 | 6 54 | 55 | */ 56 | int main() 57 | { 58 | TreeNode *root = newNode(1); 59 | 60 | root->left = newNode(2); 61 | root->right = newNode(3); 62 | root->left->left = newNode(4); 63 | root->left->right = newNode(5); 64 | root->left->left->right = newNode(6); 65 | 66 | cout << "Height of the Tree is " << maxHeight(root) << endl; 67 | return 0; 68 | } -------------------------------------------------------------------------------- /Trees/Postorder Traversal/Postorder Traversal - Java.java: -------------------------------------------------------------------------------- 1 | class Node 2 | { 3 | int key; 4 | Node left, right; 5 | 6 | public Node(int item) 7 | { 8 | key = item; 9 | left = right = null; 10 | } 11 | } 12 | 13 | class Solution 14 | { 15 | void printPostorder(Node node) 16 | { 17 | if (node == null) 18 | return; 19 | 20 | printPostorder(node.left); //recursive call on left child 21 | printPostorder(node.right); //recursive call on right child 22 | System.out.print(node.key + " "); 23 | } 24 | 25 | public static void main(String[] args) 26 | { 27 | //creating a binary tree 28 | Node root = new Node(1) 29 | root.left = new Node(2); 30 | root.right = new Node(3); 31 | root.left.left = new Node(4); 32 | root.left.right = new Node(5); 33 | 34 | System.out.println("\nPostorder traversal of binary tree is "); 35 | tree.printPostorder(); 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Trees/Postorder_Traversal/Postorder_Traversal_python3.py: -------------------------------------------------------------------------------- 1 | # This code is written in Python3 2 | 3 | """ 4 | 5 | Uses of Postorder 6 | Postorder traversal is used to delete the tree. 7 | Postorder traversal is also useful to get the postfix expression of an expression tree. 8 | 9 | Algorithm Postorder(tree) 10 | 1. Traverse the left subtree, i.e., call Postorder(left-subtree) 11 | 2. Traverse the right subtree, i.e., call Postorder(right-subtree) 12 | 3. Visit the root. 13 | """ 14 | # To create a node 15 | class node: 16 | """docstring for node""" 17 | def __init__(self, data): 18 | self.data = data 19 | self.left = None 20 | self.right = None 21 | 22 | # TO create class of Tree data Structure 23 | class TreeDS: 24 | """docstring for TreeDS""" 25 | def __init__(self): 26 | self.root = None 27 | # To check if the tree is empty or not 28 | def is_empty(self): 29 | return self.root is None 30 | 31 | # IMP : Code to do Postorder traversal of the tree. 32 | def postorder_tree(self, temp): 33 | while temp: 34 | self.postorder_tree(temp.left) 35 | self.postorder_tree(temp.right) 36 | print(temp.data, end="-") 37 | return 38 | 39 | # To push node with a value into the tree based on the data inside it 40 | def push(self, data): 41 | newnode = node(data) 42 | if self.is_empty(): 43 | self.root = newnode 44 | return 45 | temp = self.root 46 | while True: 47 | if newnode.data < temp.data: 48 | if temp.left is None: 49 | temp.left = newnode 50 | return 51 | temp = temp.left 52 | if newnode.data > temp.data: 53 | if temp.right is None: 54 | temp.right = newnode 55 | return 56 | temp = temp.right 57 | 58 | # Code to declare the Tree 59 | T = TreeDS() 60 | 61 | # Code to push following values into the tree. 62 | 63 | T.push(5) 64 | T.push(3) 65 | T.push(4) 66 | T.push(1) 67 | T.push(7) 68 | T.push(6) 69 | 70 | # calling inorder tree and other print functions to make it readable 71 | print("postorder traversal of Tree: ") 72 | T.postorder_tree(T.root) 73 | print("end") -------------------------------------------------------------------------------- /Trees/Postorder_Traversal/iterative_postorder.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | struct node{ 6 | int data; 7 | node* left; 8 | node* right; 9 | node(int key) 10 | { 11 | data = key; 12 | left = nullptr; 13 | right = nullptr; 14 | } 15 | } 16 | 17 | void postorder(node* root) 18 | { 19 | // create an empty stack and push root node 20 | stack stk; 21 | stk.push(root); 22 | 23 | // create another stack to store post-order traversal 24 | stack out; 25 | 26 | // loop till stack is empty 27 | while (!stk.empty()) 28 | { 29 | node *curr = stk.top(); 30 | stk.pop(); 31 | out.push(curr->data); 32 | if (curr->left) 33 | stk.push(curr->left); 34 | 35 | if (curr->right) 36 | stk.push(curr->right); 37 | } 38 | while (!out.empty()) 39 | { 40 | cout << out.top() << " "; 41 | out.pop(); 42 | } 43 | } 44 | 45 | 46 | int main() 47 | { 48 | struct node *root = new node(1); 49 | root->left = new node(2); 50 | root->right = new node(3); 51 | root->left->left = new node(4); 52 | root->left->right = new node(5); 53 | /* 54 | tree: 55 | 1 56 | / \ 57 | 2 3 58 | / \ 59 | 4 5 60 | */ 61 | postorder(root); 62 | 63 | } 64 | -------------------------------------------------------------------------------- /Trees/Preorder_Traversal/Preorder_Traversal_python3.py: -------------------------------------------------------------------------------- 1 | # This code is written in Python3 2 | 3 | """ 4 | Algorithm Preorder(tree) 5 | 1. Visit the root. 6 | 2. Traverse the left subtree, i.e., call Preorder(left-subtree) 7 | 3. Traverse the right subtree, i.e., call Preorder(right-subtree) 8 | Uses of Preorder 9 | Preorder traversal is used to create a copy of the tree. 10 | Preorder traversal is also used to get prefix expression on of an expression tree. 11 | """ 12 | # To create a node 13 | 14 | class node: 15 | """docstring for node""" 16 | def __init__(self, data): 17 | self.data = data 18 | self.left = None 19 | self.right = None 20 | 21 | # TO create class of Tree data Structure 22 | class TreeDS: 23 | """docstring for TreeDS""" 24 | def __init__(self): 25 | self.root = None 26 | 27 | # To check if the tree is empty or not 28 | def is_empty(self): 29 | return self.root is None 30 | 31 | # IMP : Code to do Preorder traversal of the tree. 32 | def preorder_tree(self, temp): 33 | while temp: 34 | print(temp.data, end="-") 35 | self.preorder_tree(temp.left) 36 | self.preorder_tree(temp.right) 37 | return 38 | 39 | # To push node with a value into the tree based on the data inside it 40 | def push(self, data): 41 | newnode = node(data) 42 | if self.is_empty(): 43 | self.root = newnode 44 | return 45 | temp = self.root 46 | while True: 47 | if newnode.data < temp.data: 48 | if temp.left is None: 49 | temp.left = newnode 50 | return 51 | temp = temp.left 52 | if newnode.data > temp.data: 53 | if temp.right is None: 54 | temp.right = newnode 55 | return 56 | temp = temp.right 57 | 58 | # Code to declare the Tree 59 | T = TreeDS() 60 | # Code to push following values into the tree. 61 | T.push(5) 62 | T.push(3) 63 | T.push(4) 64 | T.push(1) 65 | T.push(7) 66 | T.push(6) 67 | 68 | # calling inorder tree and other print functions to make it readable 69 | print("preorder traversal of Tree: ") 70 | T.preorder_tree(T.root) 71 | print("end") -------------------------------------------------------------------------------- /Trees/Preorder_Traversal/iterative_preorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node{ 5 | int data; 6 | node* left; 7 | node* right; 8 | node(int key) 9 | { 10 | data = key; 11 | left = nullptr; 12 | right = nullptr; 13 | } 14 | } 15 | 16 | void preorder(root){ 17 | stack S; 18 | S.push(root); 19 | node* temp = nullptr; 20 | while(!S.empty()) 21 | { 22 | temp = S.top(); 23 | if(temp->right!=nullptr) S.push(temp->right); 24 | if(temp->left!=nullptr) S.push(temp->left); 25 | S.pop(); 26 | cout<data<<' '; 27 | } 28 | 29 | } 30 | 31 | int main() 32 | { 33 | struct node *root = new node(1); 34 | root->left = new node(2); 35 | root->right = new node(3); 36 | root->left->left = new node(4); 37 | root->left->right = new node(5); 38 | /* 39 | tree: 40 | 1 41 | / \ 42 | 2 3 43 | / \ 44 | 4 5 45 | */ 46 | preorder(root); 47 | 48 | } 49 | --------------------------------------------------------------------------------