├── Data Structures ├── FenwickTree │ └── C++ Implementation │ │ ├── FenwickTree │ │ ├── FenwickTree.o │ │ └── FenwickTree.cpp ├── Trie │ ├── C++ Implementation │ │ └── Trie.cpp │ └── Java Implementation │ │ └── TrieExample.java ├── HashTable │ └── C++ Implementations │ │ ├── seperate_chaining.cpp │ │ └── SortedTreeHashTable.cpp ├── Graph │ └── java implementaion │ │ └── GraphExample.java ├── Stack │ └── Java Implementation │ │ └── Stack.java ├── Disjoint Set │ └── Java Implementations │ │ └── UnionFind.java ├── Singly Linked List │ └── linkedlist.cpp ├── AVLTree │ └── AVLTree.java ├── Segment Tree │ ├── Java Implementation │ │ └── SegmentTreeExample.java │ └── C++ Implementation │ │ └── SegmentTree.cpp ├── Binary Search Tree │ └── C++ Implementation │ │ └── BinarySearchTree.cpp └── PriorityQueue │ └── Java Implementation │ └── PriorityQueueExample.java ├── Algorithms ├── Sorting Algorithms │ ├── C++ Implementations │ │ ├── test.cpp │ │ ├── quicksort.cpp │ │ ├── merge_sort.cpp │ │ ├── randomized_quicksort.cpp │ │ └── heap_sort.cpp │ ├── Python Implementations │ │ ├── selection_sort.py │ │ └── Bubble_Sort.py │ ├── C Implementation │ │ └── mergesort.cpp │ └── Java Implementations │ │ └── HeapSort.java ├── Divide and Conquer │ ├── C++ Implementation │ │ ├── pow.cpp │ │ ├── quicksort.cpp │ │ ├── merge_sort.cpp │ │ ├── MiniMax.cpp │ │ └── randomized_quicksort.cpp │ └── C Implementation │ │ └── mergesort.cpp ├── Dynamic Programming │ ├── C++ Implementations │ │ ├── 01knapsack.cpp │ │ ├── maximumsumsubarray.cpp │ │ ├── knapsack_using_vector.cpp │ │ ├── chainMatrixMultiplication_TopDown.cpp │ │ ├── longestcommonsubstring.cpp │ │ ├── rodcutting.cpp │ │ ├── chainMatrixMultiplication_BottomUp.cpp │ │ ├── coinchange.cpp │ │ ├── FloydWarshall_vector.cpp │ │ └── floydwarshall.cpp │ └── Java Implementations │ │ ├── EditDistance.java │ │ ├── LongestCommonSubstring.java │ │ └── LongestCommonSubsequence.java ├── Greedy Algorithm │ ├── Python Implementations │ │ └── FractionalKnapsack.py │ ├── Java Implementations │ │ ├── CoinChangeINR.java │ │ ├── FractionalKnapSack.java │ │ └── DijkstraShortestPath.java │ ├── C++ Implementations │ │ ├── activity_selection.cpp │ │ ├── graph_coloring.cpp │ │ ├── minimalspanningtree_kruskals.cpp │ │ ├── fractional_knapsack.cpp │ │ ├── prims.cpp │ │ └── JobSequencingWithDeadline.cpp │ └── C Implementation │ │ └── fractional_knapsack.c ├── Permutation and Combinations │ └── C++ Implementation │ │ ├── nextpermutation.cpp │ │ └── all_combinations.cpp ├── Graph Theory │ ├── C Implementations │ │ ├── quicksort.h │ │ └── kruskals.c │ ├── C++ Implementations │ │ ├── bellmanford.cpp │ │ ├── graph_coloring.cpp │ │ ├── graph_coloring_backtracking.cpp │ │ ├── dijkstra_shortrstpath.cpp │ │ ├── TSP_bruteforce.cpp │ │ ├── hamiltonian_cycle.cpp │ │ ├── FloydWarshall_vector.cpp │ │ ├── minimalspanningtree_kruskals.cpp │ │ ├── GraphAdjacencyList.cpp │ │ ├── prims.cpp │ │ ├── DepthFirstSearch.cpp │ │ ├── BreadthFirstSearch.cpp │ │ ├── dijkstra_using_priorityqueue.cpp │ │ ├── topologicalsort.cpp │ │ ├── floydwarshall.cpp │ │ └── DetectCycle.cpp │ └── Java Implementations │ │ ├── GraphAdjacencyList.java │ │ ├── DepthFirstSearch.java │ │ └── BreadthFirstSearch.java ├── String Matching Algorithms │ └── C++ Implementations │ │ └── kmp.cpp └── Back Tracking │ ├── C++ Implementations │ ├── graph_coloring_backtracking.cpp │ ├── hamiltonian_cycle.cpp │ └── nqueen.cpp │ └── Java Implementations │ └── nqueen.java ├── questions └── WordDecode │ ├── WordDecode.py │ ├── soln.java │ ├── WordDecode.cpp │ ├── Problem Statement.md │ └── WordDecode.java └── README.md /Data Structures/FenwickTree/C++ Implementation/FenwickTree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arpanpathak/Data-Structures-and-Algorithm/HEAD/Data Structures/FenwickTree/C++ Implementation/FenwickTree -------------------------------------------------------------------------------- /Data Structures/FenwickTree/C++ Implementation/FenwickTree.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arpanpathak/Data-Structures-and-Algorithm/HEAD/Data Structures/FenwickTree/C++ Implementation/FenwickTree.o -------------------------------------------------------------------------------- /Data Structures/Trie/C++ Implementation/Trie.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Trie { 4 | struct Node { 5 | map m; 6 | bool end=false; 7 | }; 8 | }; 9 | int main() 10 | { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Algorithms/Sorting Algorithms /C++ Implementations/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | srand(time(0)); 5 | ofstream f("input.txt"); 6 | f<<"1000"<l[j+1]): 6 | l[j],l[j+1]=l[j+1],l[j] 7 | l=list(map(int,input("Enter Array Elementes : ").split(" "))) 8 | bubble_sort(l) 9 | print(l) 10 | -------------------------------------------------------------------------------- /questions/WordDecode/WordDecode.py: -------------------------------------------------------------------------------- 1 | ''' @author arpanpathak ''' 2 | dictionary,start=input().split(" "),0 3 | max_length=len( max(dictionary,key=len) ) 4 | enc,dec=input(),"" 5 | for i in range(0,len(enc)): 6 | if(i-start 2 | #define ULL unsigned long long int 3 | using namespace std; 4 | int c=0; 5 | ULL _pow(ULL a,int b) 6 | { 7 | if(b==0) return 1; 8 | c++; 9 | return a*_pow(a,b-1); 10 | } 11 | ULL _pow2(ULL a,int b) 12 | { 13 | if(b==0) return 1; 14 | ULL x=_pow2(a,b/2); 15 | c++; 16 | if(b%2==0) 17 | return x*x; 18 | else 19 | return a*x*x; 20 | } 21 | int main() 22 | { 23 | cout<<_pow(2,63)< map=new TreeMap<>(); 12 | for(int i=0;i-1;j=l.indexOf(dict[i],j+1)) 14 | map.put(j,dict[i]); 15 | 16 | String sen=""; 17 | for(int i:map.keySet()){ 18 | sen=sen+map.get(i)+" "; 19 | } 20 | 21 | System.out.println(sen.trim()); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/C++ Implementations/01knapsack.cpp: -------------------------------------------------------------------------------- 1 | /** 0,1 knapsack problem using 2d array , implemented by Arpan Pathak **/ 2 | #include 3 | using namespace std; 4 | unsigned long long int M[100][100]; 5 | int knapsack(int items[][2],int n,int capacity) 6 | { 7 | for(int i=1;i<=n;i++) 8 | { 9 | for(int j=1;j<=capacity;j++) 10 | { 11 | if(items[i-1][1]<=j) 12 | M[i][j]=max(items[i-1][0]+M[i-1][j-items[i-1][1]] , M[i-1][j] ); 13 | else M[i][j]=M[i-1][j]; 14 | } 15 | } 16 | return M[n][capacity]; 17 | } 18 | int main() 19 | { 20 | int items[][2]={ {22,4},{4,2},{15,3},{30,5},{108,7},{25,8}}; 21 | cout< 2 | using namespace std; 3 | class HashTable 4 | { 5 | list H[10]; 6 | public: 7 | void add(int val) { H[val%10].push_front(val); } 8 | friend ostream& operator<<(ostream &out,HashTable &obj) 9 | { 10 | for(int i=0;i<10;i++) 11 | { 12 | out<<"|"<"; 13 | for(auto j: obj.H[i]) 14 | out< 4 | #define ninf INT_MIN 5 | using namespace std; 6 | int M[1000][1000]; 7 | int maxsum(int *A,int n) 8 | { 9 | int m=ninf; 10 | for(int l=1;l<=n;l++) 11 | { 12 | int i=0; 13 | for(int j=i+l-1;i 4 | using namespace std; 5 | template bool nextpermu(T *arr,int n){ 6 | int pivot=n-1,j=n-1,i; 7 | for(i=n-1;arr[i]<=arr[i-1];i--) pivot=i-1; 8 | pivot--; 9 | if(pivot<0) return false; // this is the last permutation.. no next permutation possible 10 | while(arr[j]<=arr[pivot]) j--; 11 | swap(arr[j],arr[pivot]); 12 | for(i=pivot+1,j=n-1;i=end) return; 20 | int pIndex=partition(A,start,end); 21 | quick_sort(A,start,pIndex-1); quick_sort(A,pIndex+1,end); 22 | } 23 | -------------------------------------------------------------------------------- /Algorithms/Greedy Algorithm/Java Implementations/CoinChangeINR.java: -------------------------------------------------------------------------------- 1 | /** Coin Change Problem implemented by Arpan Pathak using greedy approach 2 | * Greedy approach will not work for all denominations but it will work for indian rupee **/ 3 | public class CoinChangeINR { 4 | static int min(int arr[],int val) 5 | { 6 | int m=0; 7 | for(int i=arr.length-1;i>=0;i--) if(arr[i]<=val) {m=arr[i]; break; } 8 | return m; 9 | } 10 | static int mimimumCoin(int arr[],int amount) 11 | { 12 | int n=0,remaining=amount; 13 | while(remaining>0) 14 | { 15 | int m=min(arr,remaining); 16 | n+=remaining/m; 17 | System.out.println(remaining/m+" No of "+m+" Rupee Coin/Note"); 18 | remaining-=m*(remaining/m); 19 | } 20 | return n; 21 | } 22 | public static void main(String[] args) { 23 | int arr[]={1,5,7,10}; 24 | System.out.println("Minimum Coin required="+mimimumCoin(arr,65)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Algorithms/Permutation and Combinations/C++ Implementation/all_combinations.cpp: -------------------------------------------------------------------------------- 1 | /** Generate Combination of an Array of r elements *= 2 | ** @author: Arpan Pathak **/ 3 | #include 4 | using namespace std; 5 | template void doCombinations(T *arr,T *data,int n,int r,int index,int i){ 6 | if(index==r){ 7 | for(int x=0;x=n) return; 12 | data[index]=arr[i]; 13 | doCombinations(arr,data,n,r,index+1,i+1); 14 | doCombinations(arr,data,n,r,index,i+1); 15 | } 16 | template void combinations(T *arr,int n,int r){ 17 | T data[n]; 18 | doCombinations(arr,data,n,r,0,0); 19 | } 20 | int main(){ 21 | int arr[] = {1, 2, 3, 4, 5}; 22 | combinations(arr,5,3); 23 | char a[]="ABCDEFGHI"; 24 | combinations(a,9,4); 25 | combinations(a,9,1); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Algorithms/Divide and Conquer/C++ Implementation/quicksort.cpp: -------------------------------------------------------------------------------- 1 | /** Normal quick sort implemented by Arpan Pathak 2 | ** Time Complexity for worst cases O(N^2) **/ 3 | #include 4 | using namespace std; 5 | int partition(int *A,int start,int end) 6 | { 7 | int pIndex=start; 8 | for(int i=start;i=end) return; 18 | int pIndex=partition(A,start,end); 19 | quick_sort(A,start,pIndex-1); 20 | quick_sort(A,pIndex+1,end); 21 | } 22 | void seed(){ time_t *t; srand(time(0)); } 23 | main() 24 | { 25 | seed(); 26 | int arr[]={10,9,8,7,6,5,4,3,2,1}; 27 | quick_sort(arr,0,9); 28 | for(int i:arr) cout< 4 | using namespace std; 5 | int partition(int *A,int start,int end) 6 | { 7 | int pIndex=start; 8 | for(int i=start;i=end) return; 18 | int pIndex=partition(A,start,end); 19 | quick_sort(A,start,pIndex-1); 20 | quick_sort(A,pIndex+1,end); 21 | } 22 | void seed(){ time_t *t; srand(time(0)); } 23 | main() 24 | { 25 | seed(); 26 | int arr[]={10,9,8,7,6,5,4,3,2,1}; 27 | quick_sort(arr,0,9); 28 | for(int i:arr) cout< 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | vector split(string &str){ 9 | stringstream ss(str); 10 | string tmp; 11 | vector tokens; 12 | while( getline(ss,tmp,' ') ) 13 | tokens.push_back(tmp); 14 | return tokens; 15 | } 16 | 17 | int main() 18 | { 19 | string s,enc,dec=""; 20 | getline(cin,s); 21 | vector dictionary=split(s); 22 | getline(cin,enc); 23 | map m; 24 | for(int i=0;i::iterator i=m.begin();i!=m.end();i++) 29 | dec+=i->second+" "; 30 | cout< 3 | using namespace std; 4 | void merge(int *A,int *L,int leftCount,int *R,int rightCount ) 5 | { 6 | int i=0,j=0,k=0; 7 | while(i 3 | using namespace std; 4 | int knapsack(vector> items,int capacity) 5 | { 6 | vector> K; 7 | for(int i=0;i<=items.size();i++) 8 | { 9 | vector temp; 10 | for(int j=0;j<=capacity;j++) 11 | { 12 | if(i==0||j==0) temp.push_back(0); 13 | else if(items[i-1][1]<=j) 14 | temp.push_back(max(K[i-1][ j-items[i-1][1] ] + items[i-1][0], K[i-1][j])); 15 | else 16 | temp.push_back(K[i-1][j]); 17 | } 18 | K.push_back(temp); 19 | } 20 | return K[items.size()][capacity]; 21 | } 22 | int main() 23 | { /** {value, weight } **/ 24 | vector> items={ {22,4},{4,2},{15,3},{30,5},{108,7},{25,8}}; 25 | cout< 4 | #define inf INT_MAX 5 | using namespace std; 6 | class Edge{ 7 | public: int u,v,weight; 8 | Edge(int u,int v,int weight): u(u), v(v), weight(weight) { } 9 | }; 10 | int main() 11 | { 12 | vector G; 13 | vector D; 14 | int n,v,e,u,w; 15 | cout<<"Enter number of vertices and edges="; 16 | cin>>n>>e; 17 | D.resize(n,inf); 18 | cout<<"Enter edges with weight u,v,w:\n"; 19 | while(e--) { cin>>u>>v>>w; G.push_back(Edge(u,v,w)); } 20 | cout<<"Enter source vertex="; cin>>u; 21 | D[u]=0; 22 | for(int i=1;i<=n-1;i++) 23 | for(int j=0;j D[G[j].u] + G[j].weight ) 25 | D[G[j].v] = D[G[j].u] + G[j].weight; 26 | for(int i: D) cout< 4 | #define ULL unsigned long long int 5 | #define inf 9223372036854775808 6 | using namespace std; 7 | ULL M[100][100]; 8 | ULL cost(int *A,int i,int j) 9 | { 10 | if(i==j) return 0; // Matrix Multiplication need atleast two matrices 11 | if(M[i][j]!=0) return M[i][j]; // Memorized previous sub problems 12 | M[i][j]=inf; 13 | for(int k=i;k>n; 23 | int arr[n+1]; 24 | cout<<"Enter orders : "; 25 | for(int i=0;i<=n;i++) cin>>arr[i]; 26 | cout<<"Minimum Multiplication Cost : "< 3 | #define ninf INT_MIN 4 | using namespace std; 5 | int M[5000][5000],x,y; 6 | int length_common_substring(string s1,string s2) 7 | { 8 | int max_length=ninf,p,q; 9 | for(int i=1;i<=s1.length();i++) 10 | { 11 | for(int j=1;j<=s2.length();j++) 12 | { 13 | M[i][j]=(s1.at(i-1)==s2.at(j-1))? M[i-1][j-1]+1 : 0; 14 | if(M[i][j]>max_length) { x=i; y=j; } 15 | max_length=max(max_length,M[i][j]); 16 | } 17 | } 18 | return max_length; 19 | } 20 | void print(string s1,string s2,int i,int j) 21 | { 22 | if(M[i][j]==0 ) return; 23 | print(s1,s2,i-1,j-1); 24 | cout< 3 | #include 4 | using namespace std; 5 | void merge(int *A,int *L,int leftCount,int *R,int rightCount ) 6 | { 7 | int i=0,j=0,k=0; 8 | while(i 2 | using namespace std; 3 | struct Data 4 | { 5 | int min,max; 6 | friend ostream& operator <<(ostream &out,Data &obj) 7 | { 8 | out<<"Maximam ="< 4 | #define RND(a,b) rand()%(b-a+1)+a 5 | using namespace std; 6 | int partition(int *A,int start,int end) 7 | { 8 | int pivotIndex=RND(start,end),pIndex=start; 9 | swap(A[pivotIndex],A[end]); 10 | for(int i=start;i=end) return; 20 | int pIndex=partition(A,start,end); 21 | quick_sort(A,start,pIndex-1); 22 | quick_sort(A,pIndex+1,end); 23 | } 24 | void seed(){ time_t *t; srand(time(0)); } 25 | main() 26 | { 27 | seed(); 28 | int arr[]={10,9,8,7,6,5,4,3,2,1}; 29 | quick_sort(arr,0,9); 30 | for(int i:arr) cout< 4 | using namespace std; 5 | template struct Activity{ 6 | T name; int start,finish; 7 | Activity(T name,int start,int finish): name(name),start(start),finish(finish) { } 8 | bool operator <(Activity &o) { return finish> l; // list of activities 12 | int n,s,f; string name; 13 | cout<<"Enter number of activities="; cin>>n; 14 | cout<<"Enter all activities (name,start,finish) :\n"; 15 | while(n--){ 16 | cin>>name>>s>>f; l.push_back(Activity(name,s,f)); cin.ignore(); 17 | } 18 | sort(l.begin(),l.end()); 19 | cout<<"Selected Activities are : "<=l[k].finish){ 22 | cout< 4 | #define RND(a,b) rand()%(b-a+1)+a 5 | using namespace std; 6 | int partition(int *A,int start,int end) 7 | { 8 | int pivotIndex=RND(start,end),pIndex=start; 9 | swap(A[pivotIndex],A[end]); 10 | for(int i=start;i=end) return; 20 | int pIndex=partition(A,start,end); 21 | quick_sort(A,start,pIndex-1); 22 | quick_sort(A,pIndex+1,end); 23 | } 24 | void seed(){ time_t *t; srand(time(0)); } 25 | main() 26 | { 27 | seed(); 28 | int arr[]={10,9,8,7,6,5,4,3,2,1}; 29 | quick_sort(arr,0,9); 30 | for(int i:arr) cout< 4 | using namespace std; 5 | int M[100]; 6 | int cut(int *length,int *price,int l) 7 | { 8 | if(l==0) return 0; 9 | if(l==1) return price[0]; 10 | if(M[l]!=0) return M[l]; 11 | M[l]=0; 12 | for(int i=1;i<=l;i++) 13 | { 14 | M[l]=max(M[l],price[i-1]+cut(length,price,l-i)); 15 | } 16 | return M[l]; 17 | } 18 | int cutBottomUp(int *length,int *price,int l) 19 | { 20 | for(int i=1;i<=l;i++) 21 | { 22 | M[i]=0; 23 | for(int k=1;k<=i;k++) 24 | { 25 | M[i]=max(M[i],price[k-1]+M[i-k]); // I can use max if I'll not have to print the lengths..... 26 | } 27 | } 28 | return M[l]; 29 | } 30 | int main() 31 | { 32 | int length[]={1,2,3,4,5,6,7,8}, price[]={1,5,8,9,10,17,17,20}; 33 | cout<max_length) { x=i; y=j; } 15 | max_length=Math.max(max_length,M[i][j]); 16 | } 17 | } 18 | return max_length; 19 | } 20 | static void print(String s1,String s2,int i,int j) 21 | { 22 | if(M[i][j]==0 ) return; 23 | print(s1,s2,i-1,j-1); 24 | System.out.print(s1.charAt(i-1)); 25 | } 26 | public static void main(String[] args) { 27 | String s1="abcdxyzggmn",s2="cdxytvmty"; 28 | System.out.println(length_common_substring(s1,s2)); 29 | print(s1,s2,x,y); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Algorithms/Graph Theory/C++ Implementations/graph_coloring.cpp: -------------------------------------------------------------------------------- 1 | /** Chromatic Number of a graph...Time Complexity O(V^2) 2 | ** @author: Arpan Pathak **/ 3 | #include 4 | #define addEdge(u,v) G[u][v]=G[v][u]=true 5 | using namespace std; 6 | int assignColors(vector< vector > &G,vector &color){ 7 | int chromatic_no=0; 8 | for(int i=0;i > G; 19 | int n,e,u,v; 20 | cout<<"Enter number of vertices and edges ="; 21 | cin>>n>>e; 22 | G.resize(n,vector(n,false)); 23 | vector color(n); 24 | cout<<"Enter connections : \n"; 25 | while(e--) { cin>>u>>v; addEdge(u,v); } 26 | cout<<"Chromatic Number="< 4 | #define addEdge(u,v) G[u][v]=G[v][u]=true 5 | using namespace std; 6 | int assignColors(vector< vector > &G,vector &color){ 7 | int chromatic_no=0; 8 | for(int i=0;i > G; 19 | int n,e,u,v; 20 | cout<<"Enter number of vertices and edges ="; 21 | cin>>n>>e; 22 | G.resize(n,vector(n,false)); 23 | vector color(n); 24 | cout<<"Enter connections : \n"; 25 | while(e--) { cin>>u>>v; addEdge(u,v); } 26 | cout<<"Chromatic Number="< G[]; 14 | public Graph(int n){ 15 | G=new LinkedList[n]; 16 | for(int i=0;i(); 18 | } 19 | boolean isConnected(int u,int v){ 20 | for(Edge i: G[u]) 21 | if(i.v==v) return true; 22 | return false; 23 | } 24 | void addEdge(int u,int v,int w){ 25 | G[u].add(0,new Edge(v,w)); 26 | } 27 | @Override 28 | public String toString(){ 29 | String result=""; 30 | for(int i=0;i"+G[i]+"\n"; 32 | return result; 33 | } 34 | } 35 | public class GraphExample { 36 | public static void main(String[] args) { 37 | Graph g=new Graph(10); 38 | g.addEdge(0, 2, 10); 39 | g.addEdge(0, 5, 15); 40 | g.addEdge(2, 5, 10); 41 | g.addEdge(9, 3, 16); 42 | 43 | System.out.println(g); 44 | System.out.println(g.isConnected(9,3)); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Algorithms/Graph Theory/Java Implementations/GraphAdjacencyList.java: -------------------------------------------------------------------------------- 1 | /**Generic Graph Data Structure using Adjacency List, implemented by Arpan Pathak **/ 2 | import java.util.*; 3 | class Edge 4 | { 5 | public T v; K w; 6 | public Edge(T vertex,K weight) { v=vertex; w=weight; } 7 | } 8 | class GraphList 9 | { 10 | Map> > G; 11 | GraphList() 12 | { 13 | G=new HashMap> >(); 14 | } 15 | void addEdge(T u,T v,V weight) 16 | { 17 | if(!G.containsKey(u)) 18 | G.put(u, new LinkedList>() ); 19 | G.get(u).add(0, new Edge(v,weight)); 20 | } 21 | void display() 22 | { 23 | for(T vertex: G.keySet()) 24 | { 25 | System.out.print(vertex+"=>"); 26 | for(Edge iterator: G.get(vertex)) 27 | System.out.print("("+iterator.v+","+iterator.w+"),"); 28 | System.out.println(); 29 | } 30 | } 31 | } 32 | public class GraphAdjacencyList { 33 | public static void main(String[] args) { 34 | GraphList g=new GraphList<>(); 35 | g.addEdge("Delhi", "Kolkata", 80); 36 | g.addEdge("Delhi", "Channai", 23); 37 | g.addEdge("Kolkata", "Delhi", 50); 38 | g.display(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/Java Implementations/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | /** Longest Common Subsequence using Dynamic Programming, Time Complexity: O(l1 X l2) 2 | * @author Arpan Pathak */ 3 | public class LongestCommonSubsequence { 4 | static int[][] M; 5 | static int LCS(String str1,String str2){ 6 | M=new int[str1.length()+1][str2.length()+1]; 7 | for(int i=1;i<=str1.length();i++) 8 | for(int j=1;j<=str2.length();j++) 9 | if(str1.charAt(i-1)==str2.charAt(j-1)) 10 | M[i][j]=M[i-1][j-1]+1; 11 | else 12 | M[i][j]=Math.max(M[i-1][j],M[i][j-1]); 13 | 14 | return M[str1.length()][str2.length()]; 15 | } 16 | static void print(String str,int i,int j){ 17 | if(i<=0 || j<=0) return; 18 | if( (M[i][j]!=M[i][j-1] && M[i][j]!=M[i-1][j]) && (M[i][j]==M[i-1][j-1]+1) ){ 19 | System.out.print(str.charAt(j-1)); 20 | i--; j--; 21 | } 22 | else if( M[i][j-1] > M[i-1][j] ) j--; 23 | else i--; 24 | print(str,i,j); 25 | } 26 | public static void main(String[] args) { 27 | System.out.println(LCS("abcxgzggmn","acttvvmnvt")); 28 | print("acttvvmnvt","abcxgzggmn".length(),"acttvvmnvt".length()); // Print in reverse order 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Data Structures/Stack/Java Implementation/Stack.java: -------------------------------------------------------------------------------- 1 | /** Generic Stack implemented by Arpan Pathak. 2 | ** Java already has Stack Class in Collection Framework. So please don't import java.util.* **/ 3 | class Stack 4 | { 5 | Node top=null; 6 | int size=0; 7 | void push(T val) { if(top==null) { top=new Node(val,null); size++; return; } 8 | top=new Node(val,top); size++; 9 | } 10 | T pop(){ 11 | T v=null; 12 | try 13 | { 14 | if(top==null) throw new Exception("Stack Underflow Exception..."); 15 | v=top.val; top=top.next; 16 | 17 | }catch(Exception e) 18 | { 19 | System.out.println(e); 20 | } return v; 21 | } 22 | @Override 23 | public String toString() 24 | { 25 | String result=""; Node ptr=top; 26 | while(ptr!=null) { result+=ptr.val+","; ptr=ptr.next; } 27 | return result; 28 | } 29 | } 30 | class Example { 31 | public static void main(String[] args) { 32 | Stack s=new Stack<>(); 33 | s.push("Delhi"); 34 | s.push("Chennai"); 35 | s.push("Kolkata"); 36 | System.out.println(s); 37 | System.out.println(s.pop()); 38 | System.out.println(s); 39 | s.pop(); 40 | s.pop(); 41 | s.pop(); 42 | System.out.println(s); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Graph Theory/C Implementations/kruskals.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "quicksort.h" 3 | #define makeSet(a) parent[a]=a 4 | int parent[100]={0}; 5 | int find(int a){ return (parent[a]==a? a: find(parent[a]) ); } 6 | int uniion(int a,int b) 7 | { 8 | if(find(a)!=find(b)) { parent[b]=a; return 1; } 9 | else return 0; // tricky.. if union forms a cycle in MST then don't do union 10 | } 11 | int main(){ 12 | Edge edges[100]; // maximum 100 edges are allowed.. Array of edges are used 13 | int n,e,u,v,w,min_cost=0,mst_edges=0; 14 | printf("Enter number of edges and vertices="); 15 | scanf("%d%d",&n,&e); 16 | printf("Enter connections (u,v,weight) :\n"); 17 | for(int i=0;i 4 | using namespace std; 5 | void suffix_prefix(vector &spa,string pattern){ 6 | 7 | for(int i=0,j=1;j &spa,string str,string pattern){ 14 | bool c=false; 15 | for(int i=0,j=0;i spa(pattern.length()); 34 | suffix_prefix(spa,pattern); 35 | kmp(spa,str,pattern); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Algorithms/Back Tracking/C++ Implementations/graph_coloring_backtracking.cpp: -------------------------------------------------------------------------------- 1 | /** Graph Coloring using backtracking. Time Complexity O(k*n^k) 2 | ** @author: Arpan Pathak **/ 3 | #include 4 | #define addEdge(u,v) G[u][v]=G[v][u]=true 5 | using namespace std; 6 | vector< vector > G; 7 | vector color; 8 | bool isSafe(int v,int i){ 9 | for(int p=0;p>u>>v; addEdge(u,v); } 34 | cout<<"Value of k="; cin>>k; 35 | if( kcolor(k,0) ) 36 | for(int i: color) 37 | cout< 4 | #define addEdge(u,v) G[u][v]=G[v][u]=true 5 | using namespace std; 6 | vector< vector > G; 7 | vector color; 8 | bool isSafe(int v,int i){ 9 | for(int p=0;p>u>>v; addEdge(u,v); } 34 | cout<<"Value of k="; cin>>k; 35 | if( kcolor(k,0) ) 36 | for(int i: color) 37 | cout< 4 | #include 5 | void Merge(int *A,int *L,int leftCount,int *R,int rightCount) { 6 | int i,j,k; 7 | i = 0; j = 0; k =0; 8 | while(i 4 | #include 5 | void Merge(int *A,int *L,int leftCount,int *R,int rightCount) { 6 | int i,j,k; 7 | i = 0; j = 0; k =0; 8 | while(i 4 | #define inf INT_MAX 5 | using namespace std; 6 | int main() 7 | { 8 | vector< vector > G; 9 | vector D,parent; vector done; 10 | int n,v,e,u,w,previous,current_min=inf,index; 11 | cout<<"Enter number of vertices and edges="; 12 | cin>>n>>e; 13 | G.resize(n,vector(n,inf)); 14 | D.resize(n,inf); 15 | parent.resize(n,-1); 16 | done.resize(n,false); 17 | cout<<"Enter edges with weight u,v,w:\n"; 18 | while(e--) { cin>>u>>v>>w; G[u][v]=w; } 19 | cout<<"Enter source vertex="; cin>>u; 20 | D[u]=0; done[u]=true; previous=u; 21 | for(int j=1;jD[previous]+G[previous][i]) 25 | { 26 | D[i]=D[previous]+G[previous][i]; 27 | parent[i]=previous; 28 | if(D[i]< current_min){ current_min=D[i]; index=i; } 29 | } 30 | previous=index; done[previous]=true; 31 | } 32 | for(int i: D) cout< 4 | #define inf INT_MAX 5 | using namespace std; 6 | int G[100][100]; 7 | int main(){ 8 | string permutation="",route=""; 9 | int e,n,u,v,w,cost=inf; 10 | cout<<"Enter number of vertices and edges="; 11 | cin>>n>>e; 12 | cout<<"Enter connections(u,v,w) :\n"; 13 | while(e--){ cin>>u>>v>>w; G[u][v]=w; G[v][u]=w; } 14 | cout<<"Enter source vertex="; cin>>u; 15 | permutation+=(u+'0'); 16 | for(int i=0;i 4 | { 5 | public T v; K w; 6 | public Edge(T vertex,K weight) { v=vertex; w=weight; } 7 | } 8 | class GraphAdjacencyList 9 | { 10 | Map> > G; 11 | Map visited=new HashMap<>(); // keep track of all visited vertices 12 | GraphAdjacencyList() 13 | { 14 | G=new HashMap> >(); 15 | } 16 | void addEdge(T u,T v,V weight) 17 | { 18 | if(!G.containsKey(u)) G.put(u, new LinkedList>() ); 19 | G.get(u).add(0, new Edge(v,weight)); 20 | visited.put(u, false); visited.put(v, false); 21 | } 22 | void DFS_Recursive(T start_vertex) 23 | { 24 | System.out.print(start_vertex+","); 25 | visited.put(start_vertex, true); 26 | if(!G.containsKey(start_vertex)) return; // to avoid NullPointerException 27 | for(Edge iterator: G.get(start_vertex)) 28 | if(!visited.get(iterator.v)) DFS_Recursive(iterator.v); 29 | } 30 | } 31 | public class DepthFirstSearch { 32 | public static void main(String[] args) { 33 | GraphAdjacencyList G=new GraphAdjacencyList<>(); 34 | G.addEdge("A", "D", 1); 35 | G.addEdge("A", "B", 1); 36 | G.addEdge("B", "C", 1); 37 | G.addEdge("D", "E", 1); 38 | G.DFS_Recursive("A"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Algorithms/Back Tracking/C++ Implementations/hamiltonian_cycle.cpp: -------------------------------------------------------------------------------- 1 | /** Detect Hamiltonoan Cycle using backtracking. 2 | ** @author: Arpan Pathak **/ 3 | #include 4 | #define addEdge(u,v) G[u][v]=G[v][u]=true 5 | using namespace std; 6 | vector< vector > G; 7 | vector path; 8 | bool isSafe(int pos,int i){ 9 | if(!G[ path[pos-1] ][i] ) return false; 10 | for(int p=0;p>u>>v; addEdge(u,v); } 36 | if( hasHamiltonian(1) ){ 37 | cout<<"Hamiltonian Cycle : "; 38 | for(int i: path) 39 | cout<"; 40 | cout<<"0"; 41 | } 42 | else cout<<"Graph doesn't have any hamiltonian cycle..."; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Graph Theory/C++ Implementations/hamiltonian_cycle.cpp: -------------------------------------------------------------------------------- 1 | /** Detect Hamiltonoan Cycle using backtracking. 2 | ** @author: Arpan Pathak **/ 3 | #include 4 | #define addEdge(u,v) G[u][v]=G[v][u]=true 5 | using namespace std; 6 | vector< vector > G; 7 | vector path; 8 | bool isSafe(int pos,int i){ 9 | if(!G[ path[pos-1] ][i] ) return false; 10 | for(int p=0;p>u>>v; addEdge(u,v); } 36 | if( hasHamiltonian(1) ){ 37 | cout<<"Hamiltonian Cycle : "; 38 | for(int i: path) 39 | cout<"; 40 | cout<<"0"; 41 | } 42 | else cout<<"Graph doesn't have any hamiltonian cycle..."; 43 | } 44 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/C++ Implementations/chainMatrixMultiplication_BottomUp.cpp: -------------------------------------------------------------------------------- 1 | /** Chain Matrix Multiplication using bottomUp dynamic programming implemented by Arpan Pathak 2 | ** Time Complexity: O(N^3) 3 | **/ 4 | #include 5 | #define ULL unsigned long long int 6 | #define inf 9223372036854775808 7 | using namespace std; 8 | ULL M[100][100]; 9 | int S[100][100]; 10 | ULL getMinimumCost(int *arr,int n) 11 | { 12 | for(int l=2;l<=n;l++) 13 | { 14 | for(int i=1;i<=n-l+1;i++) 15 | { 16 | int j=i+l-1; 17 | M[i][j]=inf; 18 | for(int k=i;k>n; 47 | int arr[n+1]; 48 | cout<<"Enter orders : "; 49 | for(int i=0;i<=n;i++) cin>>arr[i]; 50 | cout<<"Minimum Multiplication Cost : "< 3 | using namespace std; 4 | void downHeapify(int *H,int N) 5 | { 6 | int i=0,j=0; 7 | while(2*i+1H[j] && H[i]>H[j+1]) || H[i]>H[j] ) break;// No need to heapify if max heap property is satisfied 11 | if((j+1H[j]) j++;// extracting children with max value 12 | swap(H[i],H[j]); 13 | i=j; 14 | } 15 | } 16 | void heapsort(int *H,int N) 17 | { 18 | int M=N; 19 | /* ** Interchaning leaf node and root, then delete leaf node 20 | and 21 | Keep doing down heapify to restore max heap property **/ 22 | for(int i=0;i0) && (H[(index-1)/2]>H[i]; 47 | upHeapify(H,i); 48 | } 49 | heapsort(H,n); 50 | cout<<"Displaying the sorted Array : "; 51 | for(int i: H) 52 | cout< 3 | #define inf 9223372036854775808 4 | #define ULL unsigned long long int 5 | using namespace std; 6 | ULL M[50000]; 7 | ULL S[50000]; 8 | ULL change_coin(int *d,int n,ULL amount) 9 | { 10 | if(amount==0) return 0; 11 | if(M[amount]!=0) return M[amount]; 12 | ULL q=inf; 13 | for(int i=0;i0) 45 | { 46 | cout< 4 | using namespace std; 5 | int placed[100]; 6 | void print(int n) 7 | { 8 | for(int i=0;i=n ) return; 36 | for(int j=initial;j"; return; } 18 | print_path(PATH,start,end,i,PATH[i][j]); 19 | cout<"; 20 | if(j==end) cout<> G,PATH; int n,e,u,v,w; 25 | cout<<"Enter number of vertices and edges : "; cin>>n>>e; 26 | G.resize(n,vector(n,INF)); PATH.resize(n,vector(n,-1)); 27 | cout<<"Enter edges and their weights (u,v,w) : "; 28 | while(e--) { cin>>u>>v>>w; G[u][v]=w; PATH[u][v]=u; } 29 | floyed_warshahh(G,PATH); 30 | cout<<"Enter the pair of vertices that you want to see shortest path : "; 31 | cin>>u>>v; 32 | SHORTEST(u,v); 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Dynamic Programming/C++ Implementations/FloydWarshall_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define INF INT_MAX 3 | #define SHORTEST(u,v) print_path(PATH,u,v,u,v) 4 | using namespace std; 5 | void floyed_warshahh(vector> &arr,vector> &PATH) 6 | { 7 | for(int k=0;k> &PATH,int start,int end,int i,int j) 15 | { 16 | if(i<0 || j<0 || PATH[i][j]<0 ) return; 17 | if(PATH[i][j]==start) { cout<"; return; } 18 | print_path(PATH,start,end,i,PATH[i][j]); 19 | cout<"; 20 | if(j==end) cout<> G,PATH; int n,e,u,v,w; 25 | cout<<"Enter number of vertices and edges : "; cin>>n>>e; 26 | G.resize(n,vector(n,INF)); PATH.resize(n,vector(n,-1)); 27 | cout<<"Enter edges and their weights (u,v,w) : "; 28 | while(e--) { cin>>u>>v>>w; G[u][v]=w; PATH[u][v]=u; } 29 | floyed_warshahh(G,PATH); 30 | cout<<"Enter the pair of vertices that you want to see shortest path : "; 31 | cin>>u>>v; 32 | SHORTEST(u,v); 33 | } 34 | -------------------------------------------------------------------------------- /Algorithms/Graph Theory/C++ Implementations/minimalspanningtree_kruskals.cpp: -------------------------------------------------------------------------------- 1 | /** Kruskal's Minimal Spanning Tree Algorithm, time complexity O(VlogV) 2 | ** @author: Arpan Pathak **/ 3 | #include 4 | using namespace std; 5 | template struct Edge{ 6 | T u,v; int w; 7 | Edge(T u,T v,int w): u(u),v(v),w(w) { } 8 | bool operator < (Edge &obj) { return w class DisjointSets{ 11 | map disjoint; 12 | public: 13 | void makeSet(T a) { disjoint[a]=a; } 14 | T find(T a) { T parent=disjoint[a]; return (parent==a?a:find(parent) ); } 15 | bool unionn(T u,T v){ 16 | T p1=find(u),p2=find(v); 17 | return p1!=p2? (disjoint[p2]=p1) : false; 18 | } 19 | }; 20 | int main(){ 21 | vector< Edge > edges; 22 | DisjointSets s; 23 | int n,e,min_cost=0,mst_edges=0; 24 | cout<<"Enter number of vertices and edges : "; cin>>n>>e; 25 | for(int i=0;i>u>>v>>w; s.makeSet(u); s.makeSet(v); edges.push_back(Edge(u,v,w)); 28 | } 29 | sort(edges.begin(),edges.end()); 30 | for(int i=0; i>n>>e; 25 | for(int i=0;i>u>>v>>w; s.makeSet(u); s.makeSet(v); edges.push_back(Edge(u,v,w)); 28 | } 29 | sort(edges.begin(),edges.end()); 30 | for(int i=0; i O(n*log n), 3 | range or prefixSum query --> O(log n), 4 | updating single element --> O(log n) 5 | @author: arpanpathak 6 | ***/ 7 | #include 8 | using namespace std; 9 | template class BIT 10 | { 11 | vector arr,tree; 12 | public: 13 | BIT(vector &arr) 14 | { 15 | tree.resize(arr.size()+1,0); 16 | this->arr=arr; 17 | for(int i=0;i0; sum+=tree[idx],idx-=idx&(-idx) ); 28 | return sum; 29 | } 30 | T rangeSum(int l,int r) 31 | { 32 | return prefixSum(r)-prefixSum(l-1); 33 | } 34 | void rangeUpdate(int l,int r,T val) 35 | { 36 | update(l,val); 37 | update(r+1,-val); 38 | } 39 | }; 40 | int main() 41 | { 42 | vector ar={1,2,3,-4,5,6,7,1}; 43 | BIT bt(ar); 44 | bt.rangeUpdate(1,2,5); 45 | cout< 4 | using namespace std; 5 | class Item 6 | { 7 | public: string name; float value,weight,ratio; 8 | Item(string name,float value,float weight): name(name),value(value),weight(weight), ratio(value/weight) { } 9 | bool operator <(Item &obj) { return ratio>obj.ratio; } 10 | }; 11 | int main() 12 | { 13 | vector arr={ Item("A",10 ,2), 14 | Item("B",5 ,3), 15 | Item("C",15 ,5), 16 | Item("D",7 ,7), 17 | Item("E",6 ,1), 18 | Item("F",18 ,4), 19 | Item("G",3 ,1) }; // Array of items used to test knapsack algorithm 20 | sort(arr.begin(),arr.end()); // sorting in descending order of value/weight ratio 21 | float capacity=15.0f,weight=0.0f,max_profit=0.0f; 22 | for(int i=0;i"<<100<<"%\n"; 29 | } 30 | else 31 | { 32 | max_profit+=(capacity-weight)*arr[i].ratio; 33 | cout<"<<100*(capacity-weight)/arr[i].weight<<"%\n"; 34 | break; 35 | } 36 | } 37 | cout<<"Maximum Profit="< 3 | #define INF LONG_MAX 4 | using namespace std; 5 | template 6 | class Edge 7 | { 8 | public: 9 | K vertex; V weight; 10 | Edge(K vertex,V weight): vertex(vertex),weight(weight) { } 11 | }; 12 | template 13 | class Graph 14 | { 15 | map> > G; 16 | int n; 17 | 18 | public: 19 | Graph(int n): n(n) { } 20 | 21 | void addEdge(K u,K v,V w) { G[u].push_front(Edge(v,w)); } 22 | // typename required for this kind of user defined type object iterator 23 | V getWeight(K u,K v) { 24 | for(typename list>::iterator i=G[u].begin();i!=G[u].end();++i) 25 | if(i->vertex==v) return i->weight; 26 | return INF; 27 | } 28 | void print() 29 | { 30 | for(auto i: G) 31 | { 32 | cout<"; 33 | for(typename list>::iterator j=G[i.first].begin(); j!=G[i.first].end(); ++j) 34 | cout<<"("<vertex<<","<weight<<"), "; 35 | cout< G(5); 42 | G.addEdge("Delhi","Mumbai",15); 43 | G.addEdge("Delhi","Kolkata",20); 44 | G.addEdge("Dhaka","Kolkata",50); 45 | G.print(); 46 | } 47 | 48 | -------------------------------------------------------------------------------- /Algorithms/Graph Theory/C++ Implementations/prims.cpp: -------------------------------------------------------------------------------- 1 | /** Prims Algorithm using priority queue... Time Complexity O(VlogV) 2 | ** @author: Arpan Pathak... **/ 3 | #include 4 | using namespace std; 5 | struct Edge{ 6 | int v,w; 7 | Edge(int v,int w): v(v), w(w) { } 8 | }; 9 | struct Comparator{ bool operator()(Edge &e1,Edge &e2) { return e1.w>e2.w; } }; 10 | class Graph 11 | { 12 | map > G; 13 | int n; // no of vertices 14 | public: 15 | Graph(int n): n(n+1) { } 16 | void addEdge(int u,int v,int w) { G[u].push_front(Edge(v,w)); G[v].push_front(Edge(u,w)); } 17 | int getMSTPrims(int start_vertex){ 18 | int cost=0; 19 | vector visited(n); 20 | priority_queue,Comparator> pque; 21 | 22 | pque.push(Edge(start_vertex,0)); 23 | 24 | while(!pque.empty()) 25 | { 26 | Edge current=pque.top(); pque.pop(); 27 | if(visited[current.v]) continue; 28 | cost+=current.w; 29 | visited[current.v]=true; 30 | for(auto i: G[current.v]) 31 | if(!visited[i.v]) 32 | pque.push(Edge(i.v,i.w)); 33 | } 34 | return cost; 35 | } 36 | }; 37 | int main(){ 38 | int n,e,u,v,w; 39 | cin>>n>>e; 40 | Graph g(n); 41 | while(e--){ 42 | cin>>u>>v>>w; 43 | g.addEdge(u,v,w); 44 | } 45 | cin>>u; 46 | cout< 4 | using namespace std; 5 | struct Edge{ 6 | int v,w; 7 | Edge(int v,int w): v(v), w(w) { } 8 | }; 9 | struct Comparator{ bool operator()(Edge &e1,Edge &e2) { return e1.w>e2.w; } }; 10 | class Graph 11 | { 12 | map > G; 13 | int n; // no of vertices 14 | public: 15 | Graph(int n): n(n+1) { } 16 | void addEdge(int u,int v,int w) { G[u].push_front(Edge(v,w)); G[v].push_front(Edge(u,w)); } 17 | int getMSTPrims(int start_vertex){ 18 | int cost=0; 19 | vector visited(n); 20 | priority_queue,Comparator> pque; 21 | 22 | pque.push(Edge(start_vertex,0)); 23 | 24 | while(!pque.empty()) 25 | { 26 | Edge current=pque.top(); pque.pop(); 27 | if(visited[current.v]) continue; 28 | cost+=current.w; 29 | visited[current.v]=true; 30 | for(auto i: G[current.v]) 31 | if(!visited[i.v]) 32 | pque.push(Edge(i.v,i.w)); 33 | } 34 | return cost; 35 | } 36 | }; 37 | int main(){ 38 | int n,e,u,v,w; 39 | cin>>n>>e; 40 | Graph g(n); 41 | while(e--){ 42 | cin>>u>>v>>w; 43 | g.addEdge(u,v,w); 44 | } 45 | cin>>u; 46 | cout< 6 | { 7 | private class Node 8 | { 9 | public T parent; int rank=0; 10 | Node(T parent) { this.parent=parent; } 11 | } 12 | Map> disjoint; 13 | DisjointSets(){ disjoint=new HashMap<>(); } 14 | void add(T v) { disjoint.put(v,new Node(v)); } 15 | T find(T v) 16 | { 17 | T parent=disjoint.get(v).parent; 18 | return parent==v?v:find(parent); 19 | } 20 | void union(T u,T v) // union by Rank 21 | { 22 | T parent1=find(u),parent2=find(v); 23 | if(disjoint.get(parent1).rank>disjoint.get(parent2).rank){ 24 | disjoint.put(parent2,new Node(parent1)); 25 | disjoint.get(parent1).rank++; 26 | } 27 | else{ 28 | disjoint.put(parent1,new Node(parent2)); 29 | disjoint.get(parent2).rank++; 30 | } 31 | } 32 | @Override 33 | public String toString() 34 | { 35 | String result=""; 36 | for(T key: disjoint.keySet()) 37 | result+=key+"=>"+disjoint.get(key).parent+"("+disjoint.get(key).rank+")\n"; 38 | return result; 39 | } 40 | } 41 | public class UnionFind { 42 | public static void main(String[] args) { 43 | DisjointSets s=new DisjointSets<>(); 44 | s.add("A"); 45 | s.add("B"); 46 | s.add("C"); 47 | s.add("D"); 48 | s.union("A", "B"); 49 | s.union("A", "C"); 50 | s.union("C", "D"); 51 | System.out.println(s); 52 | } 53 | } -------------------------------------------------------------------------------- /Algorithms/Graph Theory/C++ Implementations/DepthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | /** Depth First Search algorithm .. @author: Arpan Pathak 2 | * Time Complexity O(VE) **/ 3 | #include 4 | using namespace std; 5 | /* Edge Class will contain description of edge (end vertex and weight) */ 6 | template 7 | class Edge 8 | { 9 | public: 10 | K vertex; V weight; 11 | Edge(K vertex,V weight): vertex(vertex),weight(weight) { } 12 | }; 13 | /** Graph Template class where K specifies data type of vertex value and V specifies data type of edge weight **/ 14 | template 15 | class Graph 16 | { 17 | map> > G; // map will map each vertex to a linked list which contains all adjacent vertices 18 | set Vertices; // set is used to keep track of all vertices because we are using adjacency list 19 | 20 | public: 21 | void addEdge(K u,K v,V w) { G[u].push_front(Edge(v,w)); Vertices.insert(u); Vertices.insert(v); } 22 | void DFS(K start_vertex) 23 | { 24 | map visited; 25 | for(auto i: Vertices) visited[i]=(i==start_vertex?true:false); 26 | DFS(start_vertex,visited); 27 | } 28 | void DFS(K start_vertex,map &visited) 29 | { 30 | cout< G; 39 | G.addEdge("A", "D", 1); 40 | G.addEdge("A", "B", 1); 41 | G.addEdge("B", "C", 1); 42 | G.addEdge("D", "E", 1); 43 | G.DFS("A"); 44 | } 45 | -------------------------------------------------------------------------------- /Algorithms/Sorting Algorithms /Java Implementations/HeapSort.java: -------------------------------------------------------------------------------- 1 | /** Heap Sort, implemented by Arpan Pathak,... Time Complexity O(N logN) **/ 2 | import java.io.*; 3 | public class HeapSort { 4 | static void swap(int[] H,int i,int j) {int temp=H[i]; H[i]=H[j]; H[j]=temp; } 5 | static void downHeapify(int[] H,int N) 6 | { 7 | int i=0,j=0; 8 | while(2*i+1H[j] && H[i]>H[j+1]) || H[i]>H[j] ) break;// No need to heapify if max heap property is satisfied 12 | if((j+1H[j]) j++;// extracting children with max value 13 | swap(H,i,j); 14 | i=j; 15 | } 16 | } 17 | static void heapsort(int[] H) 18 | { 19 | int M=H.length,N=M; 20 | /* ** Interchaning leaf node and root, then delete leaf node 21 | and 22 | Keep doing down heapify to restore max heap property **/ 23 | for(int i=0;i0) && (H[(index-1)/2] 5 | { 6 | public T v; K w; 7 | public Edge(T vertex,K weight) { v=vertex; w=weight; } 8 | } 9 | class GraphAdjacencyList 10 | { 11 | Map> > G; 12 | Set vertices; // vertices is set of all vertices 13 | GraphAdjacencyList() 14 | { 15 | G=new HashMap> >(); 16 | vertices=new HashSet<>(); 17 | } 18 | void addEdge(T u,T v,V weight) 19 | { 20 | if(!G.containsKey(u)) 21 | G.put(u, new LinkedList>() ); 22 | G.get(u).add(0, new Edge(v,weight)); 23 | vertices.add(u); vertices.add(v); 24 | } 25 | void BFS(T start_vertex) 26 | { 27 | LinkedList queue=new LinkedList<>(); 28 | Map visited=new HashMap<>(); 29 | for(T i: vertices) visited.put(i, (i==start_vertex?true:false)); 30 | queue.add(start_vertex); 31 | while(!queue.isEmpty()) 32 | { 33 | T explore=queue.removeFirst(); 34 | System.out.print(explore+","); 35 | if(!G.containsKey(explore)) continue; // to avoid NullPointerException 36 | for(Edge iterator: G.get(explore)) 37 | { 38 | if(!visited.get(iterator.v)) { 39 | visited.put(iterator.v, true); 40 | queue.add(iterator.v); 41 | } 42 | } 43 | } 44 | } 45 | } 46 | public class BreadthFirstSearch { 47 | public static void main(String[] args) { 48 | GraphAdjacencyList g=new GraphAdjacencyList<>(); 49 | g.addEdge("Goa", "Nagpur", 10); 50 | g.addEdge("Goa", "Kanpur", 15); 51 | g.addEdge("Kanpur", "Kolkata", 11); 52 | g.addEdge("Kolkata", "Delhi", 20); 53 | g.BFS("Goa"); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Algorithms/Greedy Algorithm/C++ Implementations/JobSequencingWithDeadline.cpp: -------------------------------------------------------------------------------- 1 | /** Job Sequencing with deadline using greedy approach, implemented by Arpan Pathak 2 | ** Time Complexity O(N X max_deadline) **/ 3 | #include 4 | using namespace std; 5 | template 6 | class Jobs 7 | { 8 | public: T no; int deadline,profit; 9 | Jobs(T no,int deadline,int profit): no(no),deadline(deadline),profit(profit) { } 10 | bool operator < (Jobs &obj) { return profit>obj.profit; } 11 | friend ostream& operator <<(ostream &out,Jobs &o) { 12 | out<<"\t[Job : "<> jobs,int max_deadline) 17 | { 18 | int feasible[max_deadline+1],max_profit=0; 19 | fill_n(feasible,max_deadline+1,-1); 20 | for(int i=0;i0;j-- ) 23 | if(feasible[j]==-1) { feasible[j]=i; max_profit+=jobs[i].profit; break; } 24 | } 25 | for(auto x: feasible) if(x!=-1) cout<>job_name>>deadline>>profit; cin.ignore(); 36 | max_deadline=max(max_deadline,deadline); 37 | jobs.push_back(Jobs(job_name,deadline,profit)); 38 | } 39 | sort(jobs.begin(),jobs.end()); // sort in desreasing order of profit 40 | jobSequencing(jobs,max_deadline); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Algorithms/Greedy Algorithm/C Implementation/fractional_knapsack.c: -------------------------------------------------------------------------------- 1 | /** Fractional Knapsack using greedy approach, @author: Arpan Pathak 2 | ** Time Complexity O(N log N) **/ 3 | #include 4 | typedef struct Item{ 5 | int no; 6 | float value,weight,ratio; 7 | }Item; 8 | void swap(Item *a,Item *b) { Item temp=*a; *a=*b; *b=temp; } 9 | int partition(Item *A,int start,int end) 10 | { 11 | int pIndex=start,i; 12 | for(i=start;i=end) return; 20 | int pIndex=partition(A,start,end); 21 | quick_sort(A,start,pIndex-1); quick_sort(A,pIndex+1,end); 22 | } 23 | int main() 24 | { 25 | int i,n; float weight=0.0f,capacity,profit=0.0f; 26 | Item arr[100]; // array of items where each element has no,value,weight and value/weight ratio 27 | printf("Enter number of items="); scanf("%d",&n); 28 | printf("Enter elements (profit,weight) :\n"); 29 | for(i=0;i=0; i--) 35 | if(weight+arr[i].weight<=capacity) 36 | { 37 | weight+=arr[i].weight; profit+=arr[i].value; 38 | printf("%d ==>100\%\n",arr[i].no); 39 | } 40 | else 41 | { 42 | profit+=(capacity-weight)*arr[i].ratio; 43 | printf("%d==>%f %\n",arr[i].no,100*(capacity-weight)/arr[i].weight); 44 | break; 45 | } 46 | printf("Maximum profit=%f",profit); 47 | } 48 | -------------------------------------------------------------------------------- /Algorithms/Greedy Algorithm/Java Implementations/FractionalKnapSack.java: -------------------------------------------------------------------------------- 1 | /** Fractional Knapsack Problem 2 | * Implemented By Arpan Pathak 3 | * Greedy Approach 4 | * **/ 5 | import java.util.*; 6 | class Item implements Comparable 7 | { 8 | public int value,weight; 9 | public String name; 10 | public float ratio; // value to weight ratio 11 | Item(String name,int value,int weight) 12 | { 13 | this.name=name; 14 | this.value=value; 15 | this.weight=weight; 16 | this.ratio=(float)value/(float)weight; 17 | } 18 | @Override // Overdiding compareTo method to make the objects of Item comparable 19 | public int compareTo(Item obj) { 20 | if(obj.ratio>this.ratio) return -1; 21 | else if(obj.ratio{ value : "+value+", Weight : "+weight+", Ratio : "+ratio+" }"; 27 | } 28 | 29 | } 30 | class Example { 31 | public static void main(String[] args) { 32 | Item[] arr={new Item("A",10,2), 33 | new Item("B",5,3), 34 | new Item("C",15,5), 35 | new Item("D",7,7), 36 | new Item("E",6,1), 37 | new Item("F",18,4), 38 | new Item("G",3,1)}; // Array of items used to test knapsack algorithm 39 | Arrays.sort(arr,Collections.reverseOrder()); 40 | float capacity=15.0f,weight=0.0f,max_profit=0.0f; 41 | for(int i=0;i<7 && weight<=capacity; i++) 42 | { 43 | if(weight+arr[i].weight<=capacity) 44 | { 45 | weight+=arr[i].weight; 46 | max_profit+=arr[i].value; 47 | System.out.println(arr[i].name+"=>"+100+"%"); 48 | } 49 | else 50 | { 51 | max_profit+=(capacity-weight)*arr[i].ratio; 52 | System.out.println(arr[i].name+"=>"+100*(capacity-weight)/arr[i].weight+"%"); 53 | break; 54 | } 55 | } 56 | System.out.println("Maximum Profit ="+max_profit); 57 | 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Algorithms/Graph Theory/C++ Implementations/BreadthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | /** Breadth First Search algorithm implemented by Arpan Pathak 2 | * Time Complexity O(VE) **/ 3 | #include 4 | using namespace std; 5 | /* Edge Class will contain description of edge (end vertex and weight) */ 6 | template 7 | class Edge 8 | { 9 | public: 10 | K vertex; V weight; 11 | Edge(K vertex,V weight): vertex(vertex),weight(weight) { } 12 | }; 13 | /** Graph Template class where K specifies data type of vertex value and V specifies data type of edge weight **/ 14 | template 15 | class Graph 16 | { 17 | map> > G; // map will map each vertex to a linked list which contains all adjacent vertices 18 | set Vertices; // set is used to keep track of all vertices because we are using adjacency list 19 | 20 | public: 21 | void addEdge(K u,K v,V w) { G[u].push_front(Edge(v,w)); Vertices.insert(u); Vertices.insert(v); } 22 | void BFS(K start_vertex) 23 | { 24 | queue que; map visited; 25 | for(auto i: Vertices) 26 | visited[i]=(i==start_vertex?true:false); 27 | que.push(start_vertex); 28 | while(!que.empty()) 29 | { 30 | K explore=que.front(); que.pop(); cout< g; 43 | g.addEdge("A", "B", 10); 44 | g.addEdge("A", "C", 15); 45 | g.addEdge("A", "D", 11); 46 | g.addEdge("D", "E", 20); 47 | g.BFS("A"); 48 | } 49 | -------------------------------------------------------------------------------- /Algorithms/Graph Theory/C++ Implementations/dijkstra_using_priorityqueue.cpp: -------------------------------------------------------------------------------- 1 | /** Dijkstra's using priority queue... Time Complexity O(ElogV) 2 | ** @author: Arpan Pathak... **/ 3 | #include 4 | #define inf INT_MAX 5 | using namespace std; 6 | struct Edge{ 7 | int v,w; 8 | Edge(int v,int w): v(v), w(w) { } 9 | }; 10 | struct Comparator{ bool operator()(Edge &e1,Edge &e2) { return e1.w>e2.w; } }; 11 | class Graph 12 | { 13 | map > G; 14 | map parent; 15 | int n; // no of vertices 16 | public: 17 | Graph(int n): n(n+1) { } 18 | void addEdge(int u,int v,int w) { G[u].push_front(Edge(v,w)); //G[v].push_front(Edge(u,w)); 19 | } 20 | void dijkstra(vector &d,int source){ 21 | priority_queue,Comparator> pque; 22 | d[source]=0; 23 | pque.push(Edge(source,0)); 24 | while(!pque.empty()) 25 | { 26 | Edge current=pque.top(); pque.pop(); 27 | for(auto i: G[current.v]) 28 | if(d[i.v]>d[current.v]+i.w) 29 | { 30 | d[i.v]=d[current.v]+i.w; 31 | pque.push(Edge(i.v,d[i.v])); 32 | parent[i.v]=current.v; 33 | } 34 | } 35 | cout<<"Vertex=>Parent"<"< m=new HashMap<>(); 11 | boolean end=false; 12 | String meaning=""; 13 | } 14 | Node root=null; // root of trie tree 15 | public Trie(){ 16 | root=new Node(); // create dummy node 17 | } 18 | public void addWord(String word,String meaning) { 19 | Node cur=root; 20 | for(char ch: word.toCharArray()) { 21 | if(!cur.m.containsKey(ch)) 22 | cur.m.put(ch, new Node() ); // if the current node doesn't have 23 | // the character then put that in map 24 | cur=cur.m.get(ch); 25 | } 26 | cur.meaning=meaning; 27 | cur.end=true; 28 | } 29 | public void deleteWord(String word) { 30 | Node cur=root; 31 | for(char ch: word.toCharArray()) { 32 | if(!cur.m.containsKey(ch)) 33 | break; // the current word is not in the TRIE 34 | cur=cur.m.get(ch); 35 | } 36 | cur.meaning=""; 37 | cur.end=false; 38 | } 39 | public String searchWord(String word) throws Exception { 40 | Node cur=root; 41 | for(char ch: word.toCharArray()) { 42 | if(!cur.m.containsKey(ch)) 43 | throw new Exception("Word Not Found!"); // current node doesn't contain the current character 44 | cur=cur.m.get(ch); 45 | } 46 | return cur.meaning; 47 | } 48 | 49 | } 50 | public class TrieExample { 51 | public static void main(String[] args) throws Exception{ 52 | Trie t=new Trie(); 53 | t.addWord("memory","Capacity of storing information"); 54 | t.addWord("memories", "past experiences"); 55 | System.out.println(t.searchWord("memory")); 56 | System.out.println(t.searchWord("memories")); 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /Algorithms/Greedy Algorithm/Java Implementations/DijkstraShortestPath.java: -------------------------------------------------------------------------------- 1 | /** Dijkstra's algorithm implemented by Arpan Pathak **/ 2 | import java.util.Arrays; 3 | 4 | class Graph 5 | { 6 | private long G[][], PATH[][]; // Adjacency Matrix is Used for Graph Representation 7 | final long INF=Long.MAX_VALUE; 8 | int n; 9 | Graph(int no_of_nodes) 10 | { 11 | this.n=no_of_nodes; 12 | G=new long[n][n]; 13 | for(int i=0;i 3 | using namespace std; 4 | template 5 | class Node 6 | { 7 | public: 8 | T data; 9 | Node *next; 10 | }; 11 | template 12 | class LinkedList 13 | { 14 | private: 15 | Node *head; 16 | public: 17 | LinkedList() { head=NULL; } 18 | void push_back(T value) 19 | { 20 | Node *ptr=new Node,*iter=head; 21 | ptr->data=value; 22 | ptr->next=NULL; 23 | if(head==NULL) { head=ptr; return; } 24 | while(iter->next!=NULL && (iter=iter->next)); 25 | iter->next=ptr; 26 | } 27 | void display() 28 | { 29 | Node *iter=head; 30 | while(iter!=NULL && (cout<data<<" ") && (iter=iter->next)); 31 | } 32 | ~LinkedList() // Deleting the created linked list manually using destructor 33 | { 34 | Node *ptr=head,*curr; 35 | while(ptr!=NULL) 36 | { 37 | curr=ptr->next; 38 | delete ptr; 39 | ptr=curr; 40 | } 41 | } 42 | Node* begin(){ return head; } 43 | 44 | }; 45 | template 46 | class iter // iterator for LinkedList . Always pass the type of linked list as template argument 47 | { 48 | public: 49 | Node *current; 50 | iter(Node *pointer): current(pointer){ } 51 | //iterator(LinkedList &obj) { current=obj.head; } 52 | bool end() { return current==NULL? true: false; } 53 | iter operator ++(int){ if(current!=NULL) current=current->next;} 54 | iter operator ++(){ if(current!=NULL) current=current->next;} 55 | T val() { if(current!=NULL) return current->data; } 56 | friend std::ostream& operator<<(ostream& out,iter &obj) 57 | { 58 | out< x; 66 | x.push_back("Delhi"); 67 | x.push_back("Mumbai"); 68 | x.push_back("Kolkata"); 69 | for(iter i=x.begin(); !i.end(); i++) 70 | cout< 3 | #define INF INT_MAX 4 | using namespace std; 5 | 6 | /* Edge Class will contain description of edge (end vertex and weight) */ 7 | template 8 | class Edge 9 | { 10 | public: 11 | K vertex; V weight; 12 | Edge(K vertex,V weight): vertex(vertex),weight(weight) { } 13 | }; 14 | 15 | /** Graph Template class where K specifies data type of vertex value and V specifies data type of edge weight **/ 16 | template 17 | class Graph 18 | { 19 | map> > G; // map will map each vertex to a linked list which contains all adjacent vertices 20 | set Vertices; // set is used to keep track of all vertices because we are using adjacency list 21 | 22 | public: 23 | void addEdge(K u,K v,V w) { G[u].push_front(Edge(v,w)); Vertices.insert(u); Vertices.insert(v); } 24 | vector topologically_sorted_order(K start) 25 | { 26 | stack s; map status; 27 | vector result; 28 | for(auto i: Vertices) 29 | status[i]=(i==start?true:false); // N indicate Not Processed, P indicates Processing and F indicate Finished 30 | s.push(start); 31 | while(!s.empty()) 32 | { 33 | int c=0; 34 | K explore=s.top(); 35 | for(auto i: G[explore]) 36 | { 37 | if(!status[i.vertex]){ 38 | s.push(i.vertex); status[i.vertex]=true; c++; 39 | break; 40 | } 41 | } 42 | if(!c) { result.insert(result.begin(),s.top()); s.pop(); } 43 | } 44 | return result; 45 | } 46 | }; 47 | 48 | int main() 49 | { 50 | Graph G; 51 | G.addEdge("A","G",10); 52 | G.addEdge("B","A",10); 53 | G.addEdge("B","F",10); 54 | G.addEdge("X","B",10); 55 | G.addEdge("B","C",10); 56 | G.addEdge("F","G",10); 57 | G.addEdge("C","F",10); 58 | G.addEdge("D","C",10); 59 | G.addEdge("E","C",10); 60 | G.addEdge("E","D",10); 61 | // start with a vertex which has a in degree of zero 62 | for(string x: G.topologically_sorted_order("A")) 63 | cout<maximum length of word in dictionary ) 18 | * ------- 19 | * In this case, we need to find if is there any word in the dictionary which is 20 | * substring of the String "match" 21 | */ 22 | 23 | public static void main(String[] args) throws Exception{ 24 | BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 25 | 26 | // max_length is used to hold the maximum length of a word in the dictionary 27 | int max_length=0; 28 | String dictionary[]=br.readLine().split(" "),dec=""; 29 | // dec is the decoded message 30 | 31 | // Now I'm counting the maximum length of a word 32 | for(String s: dictionary) 33 | max_length=Math.max(max_length,s.length()); 34 | 35 | String enc=br.readLine(); 36 | int start=0; // start is the starting index from which the substrings will be matched. 37 | // initially start is pointing to the beginning of the string. 38 | 39 | for(int i=0;i 4 | #define INF INT_MAX 5 | using namespace std; 6 | /** Using Adjacency Matrix to implement Directed weighted graph **/ 7 | class Graph 8 | { 9 | int **G,**PATH,n; 10 | public: 11 | Graph(int n){ 12 | this->n=n; 13 | G=new int*[n]; 14 | PATH=new int*[n]; 15 | for(int i=0;i G[i][k] + G[k][j]) 30 | { 31 | G[i][j]=G[i][k]+G[k][j]; PATH[i][j]=PATH[k][j]; 32 | } 33 | } 34 | } 35 | void printPath(int start,int end,int i,int j) 36 | { 37 | if(i<0 || j<0 || PATH[i][j]<0) return; 38 | if(PATH[i][j]==start){ cout<"; return; } 39 | printPath(start,end,i,PATH[i][j]); 40 | cout<"; 41 | if(j==end) cout<>u>>v>>w; G.connect(u,v,w); } 72 | G.generateSortestPath(); // Generate all pair shortest path using floyd Warshall 73 | cout< 4 | #define INF INT_MAX 5 | using namespace std; 6 | /** Using Adjacency Matrix to implement Directed weighted graph **/ 7 | class Graph 8 | { 9 | int **G,**PATH,n; 10 | public: 11 | Graph(int n){ 12 | this->n=n; 13 | G=new int*[n]; 14 | PATH=new int*[n]; 15 | for(int i=0;i G[i][k] + G[k][j]) 30 | { 31 | G[i][j]=G[i][k]+G[k][j]; PATH[i][j]=PATH[k][j]; 32 | } 33 | } 34 | } 35 | void printPath(int start,int end,int i,int j) 36 | { 37 | if(i<0 || j<0 || PATH[i][j]<0) return; 38 | if(PATH[i][j]==start){ cout<"; return; } 39 | printPath(start,end,i,PATH[i][j]); 40 | cout<"; 41 | if(j==end) cout<>u>>v>>w; G.connect(u,v,w); } 72 | G.generateSortestPath(); // Generate all pair shortest path using floyd Warshall 73 | cout< 3 | #define INF INT_MAX 4 | using namespace std; 5 | 6 | /* Edge Class will contain description of edge (end vertex and weight) */ 7 | template 8 | class Edge 9 | { 10 | public: 11 | K vertex; V weight; 12 | Edge(K vertex,V weight): vertex(vertex),weight(weight) { } 13 | }; 14 | 15 | /** Graph Template class where K specifies data type of vertex value and V specifies data type of edge weight **/ 16 | template 17 | class Graph 18 | { 19 | map> > G; // map will map each vertex to a linked list which contains all adjacent vertices 20 | set Vertices; // set is used to keep track of all vertices because we are using adjacency list 21 | 22 | public: 23 | void addEdge(K u,K v,V w) { G[u].push_front(Edge(v,w)); Vertices.insert(u); Vertices.insert(v); } 24 | 25 | V getWeight(K u,K v) { 26 | 27 | for(typename list>::iterator i=G[u].begin();i!=G[u].end();++i) 28 | if(i->vertex==v) return i->weight; 29 | return INF; // if there is no edge between u and v then return infinity 30 | } 31 | 32 | /** following method will print the adjacency list which represents this Graph object **/ 33 | void print() 34 | { 35 | for(auto i: G) 36 | { 37 | cout<"; 38 | for(typename list>::iterator j=G[i.first].begin(); j!=G[i.first].end(); ++j) 39 | cout<<"("<vertex<<","<weight<<"), "; 40 | cout< s; map status; 46 | for(auto i: Vertices) 47 | status[i]=(i==start?'P':'N'); // N indicate Not Processed, P indicates Processing and F indicate Finished 48 | s.push(start); 49 | while(!s.empty()) 50 | { 51 | int c=0; 52 | K explore=s.top(); 53 | for(auto i: G[explore]) 54 | { 55 | if(status[i.vertex]=='N'){ 56 | s.push(i.vertex); status[i.vertex]='P'; c++; 57 | break; 58 | } 59 | else if(status[i.vertex]=='P') { return (cout<<"Graph has cycle") && true; } 60 | } 61 | if(!c) { status[explore]='F'; s.pop(); } 62 | } 63 | return (cout<<"Graph has no Cycle") && false; 64 | } 65 | }; 66 | 67 | int main() 68 | { 69 | Graph G; 70 | G.addEdge("A","B",10); 71 | G.addEdge("A","C",20); 72 | G.addEdge("A","D",12); 73 | G.addEdge("D","E",12); 74 | 75 | //G.addEdge("E","A",13); // addition of this edge will create a cycle in the graph 76 | G.print(); 77 | G.hasCycle("A"); 78 | } 79 | -------------------------------------------------------------------------------- /Data Structures/AVLTree/AVLTree.java: -------------------------------------------------------------------------------- 1 | /*** 2 | * Implementation of AVL Tree 3 | * Time complexity for insertion, deletion, searching is O(log N) 4 | * 5 | * @author Arpan Pathak 6 | */ 7 | 8 | // AVL Tree Node 9 | class Node { 10 | 11 | int key, height = 0; 12 | 13 | Node left =null, right = null; 14 | 15 | public Node(int key) { 16 | this.key = key; 17 | } 18 | 19 | } 20 | 21 | public class AVLTree { 22 | 23 | // Property to store Root of AVL tree 24 | private Node root = null; 25 | 26 | /** 27 | * Insert value to AVL Tree 28 | * @param key 29 | */ 30 | public void insert(int key) { 31 | root = insert(root, key); 32 | } 33 | 34 | /** 35 | * Public method for inorder traversal 36 | */ 37 | public void inorder() { 38 | inorder(root); 39 | } 40 | 41 | /** 42 | * Private method to get the height of the current node 43 | * 44 | * @param t reference to current tree node 45 | * 46 | * @return height of the current node 47 | */ 48 | private int height(Node t) { 49 | if (t == null ) 50 | return 0; 51 | 52 | return t.height; 53 | } 54 | 55 | /** 56 | * Calculate the balance factor of current node 57 | * @param t tree node 58 | * 59 | * @return balance factor 60 | */ 61 | private int balanceFactor(Node t) { 62 | if (t == null) 63 | return 0; 64 | return height(t.left) - height(t.right); 65 | } 66 | 67 | // x y 68 | // / \ / \ 69 | // T1 y Left Rotation x T3 70 | // / \ - - - - - - - > / \ 71 | // T2 T3 T1 T2 72 | private Node leftRotate(Node x) { 73 | 74 | Node y = x.right; 75 | Node T2 = y.left; 76 | y.left = x; 77 | x.right = T2; 78 | x.height = Math.max(height(x.left), height(x.right)) + 1; 79 | y.height = Math.max(height(y.left), height(y.right)) + 1; 80 | return y; 81 | } 82 | 83 | // y x 84 | // / \ Right Rotation / \ 85 | // x T3 - - - - - - - > T1 y 86 | // / \ / \ 87 | //T1 T2 T2 T3 88 | private Node rightRotate(Node y) { 89 | 90 | Node x = y.left; 91 | Node T2 = x.right; 92 | x.right = y; 93 | y.left = T2; 94 | y.height = Math.max(height(y.left), height(y.right)) + 1; 95 | x.height = Math.max(height(x.left), height(x.right)) + 1; 96 | return x; 97 | } 98 | 99 | /** 100 | * Private method to insert key to tree 101 | * 102 | * @param tree root node of the tree 103 | * @param key key to be inserted 104 | * 105 | * @return inserted node 106 | */ 107 | private Node insert(Node tree, int key) { 108 | 109 | if (tree == null) { 110 | return new Node(key); 111 | } 112 | 113 | // Search and insert just like BST then Ajust height using rotation 114 | if (key < tree.key) 115 | tree.left = insert(tree.left, key); 116 | else if(key > tree.key) 117 | tree.right = insert(tree.right, key); 118 | else 119 | return tree; 120 | 121 | // Calculate the new height 122 | tree.height = 1 + Math.max(height(tree.left), height(tree.right)); 123 | 124 | // Get the balance factor for the current node 125 | int balanceFactor = balanceFactor(tree); 126 | 127 | // Left heavy tree 128 | if (balanceFactor > 1) { 129 | if (key < tree.right.key) 130 | return rightRotate(tree); 131 | else if(key > tree.right.key) { // L-R Rotation 132 | tree.left = leftRotate(tree.left); 133 | return rightRotate(tree); 134 | } 135 | } 136 | // Right heavy tree 137 | else if (balanceFactor < -1) { 138 | if ( key > tree.right.key) { 139 | return leftRotate(tree); 140 | } // R-L Rotation 141 | else if(key < tree.right.key) { 142 | tree.right = rightRotate(tree.right); 143 | 144 | return leftRotate(tree); 145 | } 146 | } 147 | 148 | return tree; 149 | } 150 | 151 | /** 152 | * Private method for inorder traversal 153 | * 154 | * @param tree root of the tree 155 | */ 156 | private void inorder(Node tree) { 157 | if ( tree == null ) 158 | return; 159 | 160 | inorder(tree.left); 161 | System.out.print(tree.key + " "); 162 | inorder(tree.right); 163 | 164 | } 165 | 166 | /** 167 | * Driver function to test the code 168 | * 169 | * @param args command line arguments 170 | */ 171 | public static void main(String[] args) { 172 | AVLTree tree = new AVLTree(); 173 | tree.insert(10); 174 | tree.insert(2); 175 | tree.insert(37); 176 | tree.insert(12); 177 | tree.insert(15); 178 | tree.insert(25); 179 | tree.insert(1); 180 | tree.insert(7); 181 | 182 | tree.inorder(); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /Data Structures/Segment Tree/Java Implementation/SegmentTreeExample.java: -------------------------------------------------------------------------------- 1 | /** Segment Tree for range Mini,Max and sum query 2 | * Time Complexity for constructing the tree: O(N) 3 | * Time Complexity for finding minimum within a range : O(log N) 4 | * Time Complexity for finding maximum within a range : O(log N) 5 | * Time Complexity for finding sum within a range : O(log N) 6 | * @author arpanpathak 7 | * 8 | */ 9 | class SegmentTree 10 | { 11 | final long inf=Long.MAX_VALUE, ninf=Long.MIN_VALUE; 12 | MiniMax[] tree; 13 | long[] arr; 14 | int size; 15 | class MiniMax 16 | { 17 | long min,max,sum; 18 | MiniMax(long min,long max,long sum){ this.min=min; this.max=max; this.sum=sum; } 19 | } 20 | SegmentTree(long arr[]) 21 | { 22 | 23 | int x = (int) (Math.ceil(Math.log(arr.length) / Math.log(2))); 24 | size = 2 * (int) Math.pow(2, x) - 1; // 2*size will be next power of two-1 25 | 26 | tree=new MiniMax[size]; // allocating .... 27 | this.arr=arr; 28 | for(int i=0;i=high) // total overlap 48 | return tree[pos].max; 49 | if( qlow>high || qhigh=high) // total overlap 59 | return tree[pos].min; 60 | if( qlow>high || qhigh=high) // total overlap 73 | return tree[pos].sum; 74 | if( qlow>high || qhigh 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | class BST 8 | { 9 | public: int nodecount=0; 10 | private: 11 | class node //Inner Class for creating Nodes 12 | { 13 | public: 14 | int data; 15 | node *left; 16 | node *right; 17 | node(){ left=NULL; right=NULL;} 18 | }; 19 | node *root=NULL; 20 | node *Insert(node *rootptr,int data) 21 | { 22 | if(rootptr==NULL) { 23 | node *newnode=new node; 24 | newnode->data=data; nodecount++; 25 | return newnode; 26 | } 27 | if(data>rootptr->data) 28 | rootptr->right= Insert(rootptr->right,data); 29 | else 30 | rootptr->left=Insert(rootptr->left,data); 31 | return rootptr; 32 | } 33 | void inorder(node *rootptr) 34 | { 35 | if(rootptr==NULL) return; 36 | inorder(rootptr->left); 37 | cout<data<<" "; 38 | inorder(rootptr->right); 39 | } 40 | void postorder(node *rootptr) 41 | { 42 | if(rootptr==NULL) return; 43 | inorder(rootptr->left); 44 | inorder(rootptr->right); 45 | cout<data<<" "; 46 | } 47 | void preorder(node *rootptr) 48 | { 49 | if(rootptr==NULL) return; 50 | cout<data<<" "; 51 | inorder(rootptr->left); 52 | inorder(rootptr->right); 53 | } 54 | int height(node *rootptr) 55 | { 56 | if(rootptr==NULL) return -1; 57 | int leftHeight=height(rootptr->left); int rightHeight=height(rootptr->right); 58 | return std::max(leftHeight,rightHeight)+1; 59 | } 60 | node *findMin(node *ptr) 61 | { 62 | if(ptr==NULL) { return NULL; } 63 | node *temp=ptr; 64 | while(temp->left!=NULL) temp=temp->left; 65 | return temp; 66 | } 67 | node *findMax(node *ptr) 68 | { 69 | if(ptr==NULL) { return NULL; } 70 | node *temp=ptr; 71 | while(temp->right!=NULL) temp=temp->right; 72 | return temp; 73 | } 74 | node *del(node *root1,int val) 75 | { 76 | if(root1==NULL) return NULL; 77 | if(valdata) root1->left=del(root1->left,val); 78 | else if(val>root1->data) root1->right=del(root1->right,val); 79 | else 80 | { 81 | if(root1->left==NULL && root1->right==NULL) 82 | { 83 | delete root1; 84 | root1=NULL; 85 | return root1; 86 | } 87 | else 88 | if(root1->left==NULL) 89 | { 90 | node *temp=root1; 91 | root1=root1->right; 92 | delete temp; 93 | } 94 | else if(root1->right==NULL) 95 | { 96 | node *temp=root1; 97 | root1=root1->left; 98 | delete temp; 99 | } 100 | else 101 | { 102 | node *temp=findMin(root1->right); 103 | root1->data=temp->data; 104 | temp->right=del(root1->right,temp->data); 105 | } 106 | } 107 | return root1; 108 | } 109 | node *destroy(node *ptr) // clearing all the memory from heap section 110 | { 111 | if(ptr==NULL) return NULL; 112 | destroy(ptr->left); 113 | destroy(ptr->right); 114 | delete ptr; 115 | return NULL; 116 | } 117 | public: //call this public method from your object.Don't call any private member 118 | int min(){ node *ptr=findMin(root); return ptr->data;} 119 | int max(){ node *ptr=findMax(root); return ptr->data;} 120 | void insert(int data){ root=Insert(root,data); } 121 | void inorder() { inorder(root); } 122 | void preorder() { preorder(root); } 123 | void postorder() { postorder(root); } 124 | int height(){ height(root); } 125 | void remove(int val) { root=del(root,val); } 126 | void clearTree() { root=destroy(root); } // delete the entire tree 127 | ~BST() { root=destroy(root); } 128 | 129 | }; 130 | int main() 131 | { 132 | BST t; 133 | t.remove(8); 134 | t.insert(5); 135 | t.insert(1); 136 | t.insert(8); 137 | t.insert(5); 138 | t.remove(8); 139 | //t.clearTree(); 140 | t.inorder(); 141 | cout< O(1), Worst Case: O(log N) 7 | * *********List Of All Methods which can be used:********************************* 8 | * ******************************************************************************** 9 | * insert(val,priority); : This method will insert a value in 10 | * queue according to given priority. 11 | * delete() : This method will delete and return element 12 | * with highest priority. 13 | * getHighestPriority() : will return element having maximum priority 14 | * containsValue(val) : this method will return true if the value is 15 | * in the queue. 16 | * decreasePriority(val,new_priority) : this method will decreased priority of the 17 | * given value to desired one. 18 | * size() : This method will return current size of the queue 19 | * capacity() : This method will return current capacity of the queue. 20 | * resize(expand_size) : This method will expand the current capacity of the queue. 21 | * @author: Arpan Pathak **/ 22 | import java.lang.reflect.Array; 23 | import java.util.Map; 24 | import java.util.HashMap; 25 | @SuppressWarnings("unchecked") 26 | class PriorityQueue 27 | { 28 | private class Node{ 29 | T val; int priority; 30 | Node(T val,int priority) { this.val=val; this.priority=priority; } 31 | } 32 | private Node[] que; 33 | private Map ind=new HashMap<>(); // keep track of index of all added items 34 | private int MAX_SIZE,current_size=-1; 35 | 36 | public PriorityQueue(int MAX_SIZE) { this.MAX_SIZE=MAX_SIZE; que=(Node[])Array.newInstance(Node.class, MAX_SIZE); } 37 | // if no initial size is mentioned then default size 10 is created... 38 | public PriorityQueue() { this.MAX_SIZE=10; que=(Node[])Array.newInstance(Node.class, MAX_SIZE); } 39 | 40 | // insert in priority queue.. if queue is full then resize 41 | public void insert(T val,int priority){ 42 | if(current_size==MAX_SIZE-1) 43 | resize(MAX_SIZE*2); 44 | que[++current_size]=new Node(val,priority); 45 | ind.put(val,current_size ); 46 | heapUp(current_size); 47 | } 48 | public void resize(int expand_size){ 49 | MAX_SIZE=expand_size; 50 | Node[] temp=(Node[])Array.newInstance(Node.class, expand_size);; 51 | for(int i=0;i<=current_size;i++) temp[i]=que[i]; 52 | que=temp; 53 | } 54 | public int size() { return current_size+1; } 55 | public int capacity() { return MAX_SIZE; } 56 | public T getHighestPriority() throws Exception { 57 | if(current_size==-1) throw new Exception("Empty Queue Exception"); 58 | return que[0].val; 59 | } 60 | @Override 61 | public String toString(){ 62 | String result=""; 63 | for(int i=0;i<=current_size;i++) result+="("+que[i].val+",priority="+que[i].priority+")\n"; 64 | return result; 65 | } 66 | //Delete element which has highest priority 67 | public T delete() throws Exception{ 68 | if(current_size==-1) throw new Exception("Empty Queue Exception"); 69 | T item=que[0].val; 70 | int i=0,j=0; 71 | swap(0,current_size--); 72 | ind.put(que[0].val, 0); 73 | ind.remove(item); 74 | while(2*i+1<=current_size) 75 | { 76 | j=2*i+1; 77 | if(( (j+1<=current_size) && que[i].priority"+ind.get(i)); 89 | } 90 | public void decreasePriority(T value) throws Exception{ 91 | if(!ind.containsKey(value)) 92 | throw new Exception("Value Not Found!"); 93 | } 94 | public boolean containsValue(T val){ return ind.containsKey(val); } 95 | // All private methods.... 96 | private void swap(int i,int j){ Node temp=que[i]; que[i]=que[j]; que[j]=temp; } 97 | private void heapUp(int index){ 98 | while((index>0) && (que[(index-1)/2].priority>que[index].priority) ) 99 | { 100 | ind.put(que[(index-1)/2].val, index); 101 | ind.put(que[(index)].val, (index-1)/2); 102 | swap(index,(index-1)/2); 103 | index=(index-1)/2; 104 | } 105 | } 106 | } 107 | // Class to test the PriorityQueue 108 | public class PriorityQueueExample { 109 | public static void main(String[] args) throws Exception { 110 | PriorityQueue q=new PriorityQueue<>(); 111 | // q.delete(); // if you uncomment this line then it will throw Empty Queue Exception =D 112 | for(int i=1;i<=10;i++) 113 | q.insert("Job"+i, 11-i); 114 | q.delete(); 115 | //System.out.println(q.delete()); 116 | System.out.println(q); 117 | q.printIndex(); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /Data Structures/HashTable/C++ Implementations/SortedTreeHashTable.cpp: -------------------------------------------------------------------------------- 1 | /** Sorted Tree Hash Table implemented using Binary Search Tree ** 2 | ** Best and Average Case Time complexity for insertion, deletion, searching is O(1) ** 3 | ** Worst case Time Complexity for insertion, deletion, searching is O(log N) ** 4 | ** @author: Arpan Pathak **/ 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | class BST 10 | { 11 | public: int nodecount=0; 12 | vector temp_result; 13 | private: 14 | class node //Inner Class for creating Nodes 15 | { 16 | public: 17 | int data; 18 | node *left,*right; 19 | node(){ left=NULL; right=NULL;} 20 | }; 21 | node *root=NULL; 22 | node *Insert(node *rootptr,int data) 23 | { 24 | if(rootptr==NULL) { 25 | node *newnode=new node; 26 | newnode->data=data; nodecount++; 27 | return newnode; 28 | } 29 | if(data>rootptr->data) 30 | rootptr->right= Insert(rootptr->right,data); 31 | else 32 | rootptr->left=Insert(rootptr->left,data); 33 | return rootptr; 34 | } 35 | bool find(node *ptr,int val) 36 | { 37 | if(ptr==NULL) return false; 38 | if(ptr->data==val) return true; 39 | return (valdata? find(ptr->left,val): find(ptr->right,val)); 40 | } 41 | void inorder(node *rootptr) 42 | { 43 | if(rootptr==NULL) return; 44 | inorder(rootptr->left); 45 | temp_result.push_back(rootptr->data); 46 | inorder(rootptr->right); 47 | } 48 | node *findMin(node *ptr) 49 | { 50 | if(ptr==NULL) { return NULL; } 51 | node *temp=ptr; 52 | while(temp->left!=NULL) temp=temp->left; 53 | return temp; 54 | } 55 | node *findMax(node *ptr) 56 | { 57 | if(ptr==NULL) { return NULL; } 58 | node *temp=ptr; 59 | while(temp->right!=NULL) temp=temp->right; 60 | return temp; 61 | } 62 | node *del(node *root1,int val) 63 | { 64 | if(root1==NULL) return NULL; 65 | if(valdata) root1->left=del(root1->left,val); 66 | else if(val>root1->data) root1->right=del(root1->right,val); 67 | else 68 | { 69 | if(root1->left==NULL && root1->right==NULL) 70 | { 71 | delete root1; 72 | root1=NULL; 73 | return root1; 74 | } 75 | else 76 | if(root1->left==NULL) 77 | { 78 | node *temp=root1; 79 | root1=root1->right; 80 | delete temp; 81 | } 82 | else if(root1->right==NULL) 83 | { 84 | node *temp=root1; 85 | root1=root1->left; 86 | delete temp; 87 | } 88 | else 89 | { 90 | node *temp=findMin(root1->right); 91 | root1->data=temp->data; 92 | temp->right=del(root1->right,temp->data); 93 | } 94 | } 95 | return root1; 96 | } 97 | node *destroy(node *ptr) // clearing all the memory from heap section 98 | { 99 | if(ptr==NULL) return NULL; 100 | destroy(ptr->left); 101 | destroy(ptr->right); 102 | delete ptr; 103 | return NULL; 104 | } 105 | public: //call this public method from your object.Don't call any private member 106 | int min(){ node *ptr=findMin(root); return ptr->data;} 107 | int max(){ node *ptr=findMax(root); return ptr->data;} 108 | void insert(int data){ root=Insert(root,data); } 109 | bool find(int val) { return find(root,val); } 110 | void inorder() { temp_result.clear(); inorder(root); } 111 | void remove(int val) { root=del(root,val); } 112 | void clearTree() { root=destroy(root); } // delete the entire tree 113 | ~BST() { root=destroy(root); } 114 | 115 | }; 116 | class HashTable 117 | { 118 | BST H[10]; // Array of Binary Search Tree is used to represent hash table 119 | public: 120 | void add(int val) { H[val%10].insert(val); } 121 | bool containValue(int val) { return H[val%10].find(val); } 122 | friend ostream& operator<<(ostream &out,HashTable &obj) 123 | { 124 | for(int i=0;i<10;i++) 125 | { 126 | out<<"| "< ("; 127 | obj.H[i].inorder(); 128 | for(auto j: obj.H[i].temp_result) 129 | out< 6 | #define inf INT_MAX 7 | #define ninf INT_MIN 8 | using namespace std; 9 | 10 | template class SegmentTree 11 | { 12 | vector A; 13 | struct Node{ 14 | T mx,mn,sum; 15 | Node(T m,T n,T s): mx(m),mn(n),sum(s) { } 16 | }; 17 | vector tree; 18 | public: 19 | SegmentTree(vector &AR) 20 | { 21 | int s=AR.size(); 22 | if(s&(s-1)==0) 23 | s=2*s-1; 24 | else{ 25 | int bit=0; 26 | while(s!=0){ 27 | s>>=1; bit++; 28 | } 29 | s=1<(tree[2*pos+1].mx,tree[2*pos+2].mx); 49 | tree[pos].mn=min(tree[2*pos+1].mn,tree[2*pos+2].mn); 50 | tree[pos].sum=tree[2*pos+1].sum + tree[2*pos+2].sum; 51 | } 52 | 53 | //Range Min Query 54 | T rangeMinQuery(int qlow,int qhigh,int low,int high,int pos) 55 | { 56 | if(qlow<=low && qhigh>=high) // total overlap 57 | return tree[pos].mn; 58 | if( qlow>high || qhigh=high) // total overlap 68 | return tree[pos].mx; 69 | if( qlow>high || qhigh=high) // total overlap 79 | return tree[pos].sum; 80 | if( qlow>high || qhigh