diff --git a/Ch-1--[Arrays and Strings]/1.1 Is_Unique.cpp b/Ch-1--[Arrays and Strings]/1.1 Is_Unique.cpp new file mode 100644 index 0000000..5269a68 --- /dev/null +++ b/Ch-1--[Arrays and Strings]/1.1 Is_Unique.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; +bool isUniqueChar(string str){ + if(str.length()>128){ + return false; + } + bool *charset=new bool[128]; + int val; + for(int i=0;i +using namespace std; +//bool Check_permutation(string source,string destination){ +// if(source.length()!=destination.length()){ +// return false; +// } +// sort(source.begin(),source.end()); +// sort(destination.begin(),destination.end()); +// return (source==destination); +// +//} + +bool Check_permutation(string source,string destination){ + if(source.length()!=destination.length()){ + return false; + } + int *charset=new int[128]; + for(int i=0;i +using namespace std; +string URLify(string source,int trueLength){ + int spaces=0,index=0,i=0; + for(i=0;i=0;i--){ + if(source[i]==' '){ + source[index-1]='0'; + source[index-2]='2'; + source[index-3]='%'; + index=index-3; + }else{ + source[index-1]=source[i]; + index--; + + } + + } +return source; +} +int main(){ + string s1="Mr John Smith "; + int trueLength=13; + cout< +using namespace std; + +bool permuatationPalindromeCheck(string str){ + int *charset=new int[128]; + int oddNo=0,temp=0; + + memset(charset,0,128*sizeof(int)); + for(int i=0;i +using namespace std; +//three type of modification can perform on string +// 1. insert -->>other string have one greter length +// 2. delete -->other string less than one length +// 3. replace (modify) -->both string same length than replace + + +//bool oneReplace(string source,string check){ +// bool differanceCheck=false; +// for(int i=0;i1){ + return false; + } + string s1=s1Len +using namespace std; +int compressedLen(string str){ + int len=0; + int countContinue=0; + for(int i=0;i=str.length() || str[i]!=str[i+1]){ + len+=to_string(countContinue).length()+1; + countContinue=0; + } + + + } +return len; +} +string stringComprison(string source){ + + int finalLen=compressedLen(source); + if(finalLen>=source.length()) return source; + + string compress=""; + int conCount=0; + + for(int i=0;i=source.length() || source[i]!=source[i+1]){ + compress.append(1,source[i]); + compress.append(to_string(conCount)); + conCount=0; + } + } +return compress; +} +int main(){ + + string s1="aaacccwweeer"; + cout< +using namespace std; + +bool rotate90(int *mat,int rows,int cols){ + int n=rows; + for(int layer=0;layertop + mat[first*n+i]=mat[(last-offset)*n+first]; + + //bootom->left + mat[(last-offset)*n+first]=mat[last*n+(last-offset)]; + + //right->bottom + mat[last*n+(last-offset)]=mat[i*n+last]; + + //top->right + mat[i*n+last]=top; + + } + + } + + for(int x=0;x +using namespace std; +void nullifyRow(int *mat,int row,int cols,int n){ + for(int i=0;i +using namespace std; +bool isSubstring(string source,string check){ + int s1Len=check.length(); + int s2Len=source.length(); + int j=0; + for(int i=0;i<=s2Len-s1Len;i++){ + for(j=0;j0){ + source=source+source; + return isSubstring(source,check); + } + + return false; +} +int main(){ + string s1="waterbottle"; + string s2="erbottlewat"; + bool flag=rotation(s1,s2); + if(flag){ + cout<<"Yes"< +using namespace std; + +string joinWords(string words[],int n){ + string sentence=""; + for(int i=0;i +using namespace std; + +int* resizeArray(int *arr,int len) +{ + + int *newArray=new int[len*2]; + memcpy(newArray,arr,len*sizeof(int)); + len=len*2; + + delete []arr; + return newArray; +} + +int main(){ + int *arr=new int[5]; + for(int i=0;i<5;i++){ + arr[i]=i*i*i; + } + + arr=resizeArray(arr,5); + for(int i=0;i<10;i++){ + cout< +using namespace std; +class hashTable{ +private: + struct node{ + int val; + struct node *next; + }; + node *a[100]; + + +public: + hashTable(){ + for(int i=0;i<100;i++){ + a[i]=NULL; + } + } + int hashFunction(int data){ + return (data%100); + } + + void add(int data){ + node *ptr,*ptr2; + int index=hashFunction(data); + ptr=(node *)malloc(sizeof(node)); + ptr->val=data; + ptr->next=NULL; + if(a[index]==NULL){ + a[index]=ptr; + }else{ + ptr2=a[index]; + while(ptr2->next!=NULL){ + ptr2=ptr2->next; + } + ptr2->next=ptr; + } + + } + void displayHashTable(){ + node *pass; + for(int i=0;i<100;i++){ + pass=a[i]; + if(a[i]==NULL) + continue; + while(pass!=NULL){ + cout<val<<" "; + pass=pass->next; + } + cout<val!=data){ + if(ptr->next==NULL){ + break; + } + parent=ptr; + ptr=ptr->next; + } + if(ptr->next==NULL && ptr->val==data){ + if(parent==NULL){ + a[index]=NULL; + delete(ptr); + }else{ + parent->next=NULL; + delete(ptr); + } + + }else if(ptr->next==NULL){ + cout<<"Element not found"; + }else{ + parent->next=ptr->next; + delete(ptr); + } + + } + } +}; +int main(){ + + hashTable obj; + obj.add(39); + obj.add(88); + obj.add(90); + obj.add(58); + obj.add(77); + obj.add(66); + obj.add(43); + obj.add(56); + obj.add(166); + obj.add(87); + obj.displayHashTable(); + obj.removeData(77); + obj.removeData(90); + obj.removeData(43); + cout<<"Updated Hash Tables"< +using namespace std; +class Node{ + public: + int data; + Node* next; +}; +void addNode(Node **head,int data){ + Node *newNode=new Node(); + newNode->data=data; + newNode->next=NULL; + if(*head==NULL){ + *head=newNode; + }else{ + Node *currunt=*head; + while(currunt->next!=NULL){ + currunt=currunt->next; + } + currunt->next=newNode; + } + +} +void display(Node *ptr){ + if(ptr==NULL){ + cout<<"NO Element In Linked List"<data<<" "; + ptr=ptr->next; + } + } + +} +//void deleteDups(Node *head){ //complexity 0(N) +// map MyDups; +// Node *prev=NULL; +//// cout<<(**head).data<data]){ +// prev->next=head->next; +// }else{ +// MyDups[head->data]=head->data; +// prev=head; +// +// } +// head=head->next; +// } +//} + +void deleteDups(Node *head){ //complexity 0(N^2) + Node *ptr=head; + while(ptr!=NULL){ + Node *runner=ptr; + while(runner->next!=NULL){ + if(runner->next->data==ptr->data){ + runner->next=runner->next->next; + }else{ + runner=runner->next; + } + } + ptr=ptr->next; + } +} + +int main(){ + Node* head=NULL; + addNode(&head,10); + addNode(&head,20); + addNode(&head,20); + addNode(&head,40); + addNode(&head,40); + addNode(&head,50); + display(head); + cout< +using namespace std; +class node{ +public: + int data; + node *next; +}; +void addNode(node **head,int val){ + node *newNode=new node(); + newNode->data=val; + newNode->next=NULL; + if(*head==NULL){ + *head=newNode; + }else{ + + node *ptr=*head; + while(ptr->next!=NULL){ + ptr=ptr->next; + } + ptr->next=newNode; + } + + +} +void displayList(node *head){ + if(head==NULL){ + cout<<"No element in the List"<data<<" "; + ptr=ptr->next; + } + cout<next,i); +// i=i+1; +// if(i==k){ +// return head; +// } +// cout<next; + } + while(p1!=NULL){ + p1=p1->next; + p2=p2->next; + } + return p2; + + + } + +int main(){ + node *head=NULL; + addNode(&head,12); + addNode(&head,33); + addNode(&head,78); + addNode(&head,98); + displayList(head); + //for recursive approach +// int i=0; +// node *ans=kthTolast(2,head,i); +// cout<data<data< +using namespace std; +class node{ +public: + int data; + node *next; +}; +void push(node **head,int value){ + node *newNode=new node(); + newNode->data=value; + newNode->next=NULL; + if(*head==NULL){ + *head=newNode; + + }else{ + node *ptr=*head; + while(ptr->next!=NULL){ + ptr=ptr->next; + } + ptr->next=newNode; + } +} +void displayList(node *head){ + if(head==NULL){ + cout<<"Empty List"<data<<" "; + head=head->next; + } + } +} +void deleteMiddleNode(node *head){ + if(head==NULL){ + cout<<"Empty List"<next; + } + if(len<=2){ + cout<<"Do Not Delete first and Last Node"<next; + } + p2->next=p1->next; + cout< +using namespace std; +class node{ +public: + int data; + node *next; +}; +void push(node **head,int data){ + node *newNode=new node(); + newNode->data=data; + newNode->next=NULL; + if(*head==NULL){ + *head=newNode; + }else{ + node *ptr=*head; + while(ptr->next!=NULL){ + ptr=ptr->next; + } + ptr->next=newNode; + } + +} +void display(node *head){ + if(head==NULL){ + cout<<"List empty"<data<<" "; + runner=runner->next; + } + cout<next; + if(head->datanext=top; + top=head; + + }else{ + tail->next=head; + tail=head; + } + + head=next; + } + tail->next=NULL; + + return top; +} +int main(){ + node *head=NULL; + push(&head,4); + push(&head,2); + push(&head,1); + push(&head,5); + push(&head,12); + display(head); + head=partitionList(head,5); + display(head); + + return 0; +} diff --git a/Ch-2--[Linked Lists]/2.5 Sum Lists.cpp b/Ch-2--[Linked Lists]/2.5 Sum Lists.cpp new file mode 100644 index 0000000..7f7e916 --- /dev/null +++ b/Ch-2--[Linked Lists]/2.5 Sum Lists.cpp @@ -0,0 +1,114 @@ +#include +using namespace std; + +class node{ +public: + int data; + node *next; +}; +class partialSum{ +public:node *sum=NULL; + int carry=0; +}; +node *insertBefore(node *li,int data){ + node *newNode=new node(); + newNode->data=data; + + if(li!=NULL) + newNode->next=li; + + +return newNode; +} +int length(node *head){ + int len=0; + while(head!=NULL){ + head=head->next; + len++; + } + return len; +} +node *padList(node *ptr,int pedding){ + node *runner=ptr; + for(int i=0;idata=value; + newNode->next=*head; + *head=newNode; +} +void display(node *head){ + if(head==NULL){ + cout<<"Empty List"<data<<" "; + ptr=ptr->next; + } + cout<next,l2->next); + int value=sum->carry+l1->data+l2->data; + + + node *full_result=insertBefore(sum->sum,value%10); + + sum->sum=full_result; + sum->carry=value/10; + return sum; + +} +node *addLists(node *l1,node *l2){ + int len1=length(l1); + int len2=length(l2); + + if(len1carry==0){ + return sum->sum; + }else{ + node *result=insertBefore(sum->sum,sum->carry); + return result; + } +} +int main(){ + node *l1Head=NULL; + node *l2Head=NULL; + + push(&l1Head,2); + push(&l1Head,3); + push(&l1Head,7); + + + push(&l2Head,8); + push(&l2Head,9); + push(&l2Head,5); + + display(l1Head); + display(l2Head); + + node *sum=NULL; + sum=addLists(l1Head,l2Head); + + display(sum); + return 0; +} diff --git a/Ch-2--[Linked Lists]/2.6 Palindrome.cpp b/Ch-2--[Linked Lists]/2.6 Palindrome.cpp new file mode 100644 index 0000000..1ba80ca --- /dev/null +++ b/Ch-2--[Linked Lists]/2.6 Palindrome.cpp @@ -0,0 +1,105 @@ +#include +using namespace std; +class node{ +public: int data; + node *next; +}; +void push(node **head,int data){ + node *newNode=new node(); + newNode->data=data; + newNode->next=NULL; + if(*head==NULL){ + *head=newNode; + }else{ + node *ptr=*head; + while(ptr->next!=NULL){ + ptr=ptr->next; + } + ptr->next=newNode; + } +} +void display(node *head){ + if(head==NULL){ + cout<<"Empty List"; + }else{ + while(head!=NULL){ + cout<data<<" "; + head=head->next; + } + cout<data=check->data; + newNode->next=ptr; + ptr=newNode; + check=check->next; + } + +return ptr; +} +bool isEqual(node *one,node *two){ + while(one!=NULL && two!=NULL){ + if(one->data!=two->data) + return false; + one=one->next; + two=two->next; + } + + +return (one==NULL && two==NULL); +} +bool isPalindrome(node *head){ + node *reversed=reverseAndClone(head); + return isEqual(head,reversed); + +} +bool isPalindromeStack(node *head){ + node *fast=head; + node *slow=head; + + stack palindromeStack; + while(fast!=NULL && fast->next!=NULL){ + palindromeStack.push(slow->data); + slow=slow->next; + fast=fast->next->next; + } + if(fast!=NULL){ + slow=slow->next; + } + + int top; + while(slow!=NULL){ + top=palindromeStack.top(); + palindromeStack.pop(); + if(top!=slow->data){ + return false; + } + slow=slow->next; + } + +return true; +} +int main(){ + node *head=NULL; + + push(&head,0); + push(&head,1); + push(&head,2); + push(&head,1); + push(&head,0); + + display(head); + bool flag; + //reverse and compare +// flag=isPalindrome(head); + flag=isPalindromeStack(head); + if(flag) + cout<<"Yes"< +using namespace std; +class node{ +public: + int data; + node *next; +}; +class Result{ +public: + node *tail; + int size; + Result(node *other,int len){ + tail=other; + size=len; + } +}; +void push(node **head,int data){ + + node *newNode=new node(); + newNode->data=data; + newNode->next=*head; + *head=newNode; + +} +void push(node **head,node **other,int data){ + + node *newNode=new node(); + newNode->data=data; + newNode->next=*head; + *head=newNode; + *other=newNode; + +} +void display(node *head){ + if(head==NULL){ + + cout<<"Empty List"<data<<" "; + ptr=ptr->next; + } + cout<next!=NULL){ + len++; + current=current->next; + } + Result *rs=new Result(current,len); + return rs; +} +node *getKthNode(node *ptr,int k){ + node *current=ptr; + while(k>0 && current!=NULL){ + k--; + current=current->next; + } + return current; +} +node *findIntersection(node *l1,node *l2){ + if(l1==NULL || l2==NULL) + return NULL; + Result *result1=getTailandSize(l1); + Result *result2=getTailandSize(l2); + + if(result1->tail!=result2->tail){ + return NULL; + } + + node *shorter=result1->sizesize?l1:l2; + node *longer=result1->sizesize?l2:l1; + + longer=getKthNode(longer,abs(result1->size - result2->size)); + + while(shorter!=longer){ + shorter=shorter->next; + longer=longer->next; + } + return longer; +} +int main(){ + node *l1Head=NULL; + node *l2Head=NULL; + + + push(&l1Head,&l2Head,1); + push(&l1Head,&l2Head,2); + push(&l1Head,&l2Head,7); + push(&l1Head,9); + push(&l1Head,5); + push(&l1Head,1); + push(&l1Head,3); + + push(&l2Head,6); + push(&l2Head,4); + + display(l1Head); + display(l2Head); + + cout<data< +using namespace std; +class node{ +public: + int data; + node *next; +}; +void push(node **head,int data){ + node *newNode=new node(); + newNode->data=data; + newNode->next=NULL; + if(*head==NULL){ + *head=newNode; + }else{ + node *ptr=*head; + while(ptr->next!=NULL){ + ptr=ptr->next; + } + ptr->next=newNode; + + } + +} +void display(node *head){ + if(head==NULL){ + cout<<"Empty List"<data<<" "; + ptr=ptr->next; + } + cout<next!=NULL){ + slow=slow->next; + fast=fast->next->next; + if(fast==slow){ + break; + } + } + if(fast==NULL || fast->next==NULL){ + return NULL; + } + + slow=head; + while(slow!=fast){ + slow=slow->next; + fast=fast->next; + } + +return fast; +} +int main(){ + node *head=NULL,*save=NULL,*prev=NULL; + push(&head,1); + push(&head,2); + push(&head,3); + push(&head,4); + push(&head,5); + + save=head; + int count=0; + while(save->next!=NULL){ + count++; + if(count==3) + prev=save; + save=save->next; + } + save->next=prev; +// display(head); + cout<data<<-----n---------> +1--->2--->3--->4--->5--->3 + <--k--> + +*/ diff --git a/Ch-3--[Stacks and Queues]/3.1 Three in One.cpp b/Ch-3--[Stacks and Queues]/3.1 Three in One.cpp new file mode 100644 index 0000000..c12752e --- /dev/null +++ b/Ch-3--[Stacks and Queues]/3.1 Three in One.cpp @@ -0,0 +1,111 @@ +#include +using namespace std; + +class FixedMultiStack{ +private: int numberOfStack=3; + int stackCapacity; + int *values; + int *sizes; +public: + FixedMultiStack(int stackSize){ + stackCapacity=stackSize; + values=new int[stackSize * numberOfStack]; + sizes=new int[numberOfStack+1]; + + }; + void push(int stackNum,int data){ + if(isFull(stackNum)){ + cout<<"Stack is Full Completely"<=stackNo*stackCapacity;i--){ + cout< +using namespace std; +//First approach +//class stackNode{ +//public: +// int data; +// int minValue; +//}; +//class MyStack{ +//private: +// int sizeOfStack=10; +// int top=-1; +// stackNode *arr=new stackNode[sizeOfStack]; +//public: +// void push(int val){ +// if(isFull()){ +// cout<<"Stack is Full"< super; + stack minStack; +public: + void push(int val){ + if(val<=mymin()){ + minStack.push(val); + } + super.push(val); + } + int pop(){ + int val=super.top(); + super.pop(); + if(val==mymin()){ + minStack.pop(); + } + return val; + } + int mymin(){ + if(minStack.empty()){ + return INT_MAX; + }else{ + return minStack.top(); + } + + } + + +}; + +//end of code second +int main(){ +//first approach + +// MyStack obj; +// obj.push(10); +// obj.push(20); +// obj.push(30); +// obj.push(40); +// obj.push(50); +// cout< +using namespace std; +class setOfStack{ + private: + vector> stacks; + int capacity; + int curuntIndex=0; + public: + setOfStack(int cap){ + capacity=cap; + stack s; + stacks.push_back(s); + } + void push(int data){ + if(stacks[curuntIndex].size()==capacity){ + stack newStack; + curuntIndex++; + stacks.push_back(newStack); + } + if(stacks[curuntIndex].size()1){ + stacks.pop_back(); + curuntIndex--; + } + + } + int mystacksTop(){ + return stacks[curuntIndex].top(); + } + int popAt(int index){ + int popData=0; + if(curuntIndex+1 +using namespace std; +class MyQueue{ +private: + stack newestStack; + stack oldestStack; +public: + void push(int data){ + newestStack.push(data); + } + + int pop(){ + shiftStacks(); + int popData=oldestStack.top(); + oldestStack.pop(); + return popData; + } + void shiftStacks(){ + if(oldestStack.empty()){ + while(!newestStack.empty()){ + oldestStack.push(newestStack.top()); + newestStack.pop(); + } + } + } + int peek(){ + shiftStacks(); + return oldestStack.top(); + } + +}; +int main(){ + MyQueue obj; + obj.push(10); + obj.push(65); + obj.push(110); + cout< +using namespace std; +class sortStack{ +private: + stack myStack; +public: + void push(int data){ + myStack.push(data); + } + void pop(){ + myStack.pop(); + } + int peek(){ + return myStack.top(); + } + bool isEmpty(){ + return (myStack.empty()); + } + void sorting(){ + stack r; + int tmp; + while(!myStack.empty()){ + tmp=myStack.top(); + myStack.pop(); + while(!r.empty() && r.top()>tmp){ + myStack.push(r.top()); + r.pop(); + } + r.push(tmp); + } + while(!r.empty()){ + myStack.push(r.top()); + r.pop(); + } + } + void printStack(){ + stack print=myStack; + while(!print.empty()){ + cout< +using namespace std; +class Animal{ +public: + string name; + string type; + int time; +}; +class Dog:public Animal{ +public: + Dog(string name){ + this->name=name; + type="dog"; + } + +}; +class Cat:public Animal{ +public: + Cat(string name){ + this->name=name; + type="cat"; + } +}; +class shelter{ +private: + int Time=0; + queue dogs; + queue cats; +public: + void enqueue(Dog d){ + d.time=Time++; + dogs.push(d); + } + void enqueue(Cat c){ + c.time=Time++; + cats.push(c); + } + Animal dequeueAny(){ + if(dogs.size() && cats.size()){ + Dog d=dogs.front(); + Cat c=cats.front(); + Animal ans=d.time<=c.time?(Animal)dequeueDogs():(Animal)dequeueCats(); + return ans; + + } + else if(dogs.size()==0){ + return (Animal)dequeueCats(); + } + else if(cats.size()==0){ + return (Animal)dequeueDogs(); + } + Animal obj; + return obj; + + } + Dog dequeueDogs(){ + if(dogs.size()==0){ + cout<<"Empty Dogs"< +using namespace std; +class graph{ +private: + int noOfVertex; + list *adj; + +public: + graph(int n){ + adj=new list[n]; + noOfVertex=n; + } + + void addEdge(int v,int e){ + adj[v].push_back(e); + } + + bool Bfs(int source,int destination){ + if(source==destination) return true; + + bool *visited=new bool[noOfVertex]; + for(int i=0;i q; + q.push(source); + visited[source]=true; + list::iterator i; + int curruntNode; + while(!q.empty()){ + curruntNode=q.front(); +// cout<Yes"< +using namespace std; +class node{ +public: + int data; + node *left; + node *right; +}; +class checkSubtree{ +public: + node *createBt(node *root,int arr[],int i,int n){ + if(idata=arr[i]; + newNode->left=NULL; + newNode->right=NULL; + root=newNode; + root->left=createBt(root->left,arr,2*i+1,n); + root->right=createBt(root->right,arr,2*i+2,n); + } + return root; + } + void In_order(node *ptr){ + if(ptr!=NULL){ + In_order(ptr->left); + cout<data<<" "; + In_order(ptr->right); + } + } + + void getOrderString(node *ptr,string &str){ + if(ptr==NULL){ + str+="X"; + return; + } + str+=to_string(ptr->data); + getOrderString(ptr->left,str); + getOrderString(ptr->right,str); + + } + bool containsTree(node *t1,node *t2){ + string s1="",s2=""; + getOrderString(t1,s1); + getOrderString(t2,s2); + return(s1.find(s2)!=string::npos); + } + + //second approch + bool matchTree(node *r1,node *r2){ + if(r1==NULL && r2==NULL){ + return true; + }else if(r1==NULL || r2==NULL){ + return false; + }else if(r1->data!=r2->data){ + return false; + }else{ + return matchTree(r1->left,r2->left) && matchTree(r1->right,r2->right); + } + + } + bool subTree(node *r1,node *r2){ + if(r1==NULL){ + return false; + } + else if(r1->data==r2->data && matchTree(r1,r2)){ + return true; + } + return subTree(r1->left,r2) || subTree(r1->right,r2); + } + bool containTree(node *t1,node *t2){ + if(t2==NULL) + return true; + return subTree(t1,t2); + } + //end of second approach + +}; +int main(){ + checkSubtree obj; + int T1_arr[]={1,2,3,4,5,6,7}; + int T2_arr[]={1,2,3}; + node *t1Root=NULL,*t2Root=NULL; + int lenT1=sizeof(T1_arr)/sizeof(T1_arr[0]); + int lenT2=sizeof(T2_arr)/sizeof(T2_arr[0]); + + t1Root=obj.createBt(t1Root,T1_arr,0,lenT1); + t2Root=obj.createBt(t2Root,T2_arr,0,lenT2); + +// obj.In_order(t2Root); + if(obj.containTree(t1Root,t2Root)){ + cout<<"Yes"< +using namespace std; + +class TreeNode{ +private: + int data; + int Size=0; +public: + TreeNode *left; + TreeNode *right; + TreeNode(int d){ + data=d; + Size=1; + left=NULL; + right=NULL; + + } + int size(){ + return Size; + } + int Data(){ + return data; + } + TreeNode* getRandomNode(){ + int leftSize=left==NULL?0:left->size(); + int index=rand()%Size; +// cout<getRandomNode(); + }else if(index==leftSize){ + return this; + }else{ + return right->getRandomNode(); + } + } + void insertInOreder(int d){ + if(d<=data){ + if(left==NULL){ + left=new TreeNode(d); + }else{ + left->insertInOreder(d); + } + }else{ + if(right==NULL){ + right=new TreeNode(d); + }else{ + right->insertInOreder(d); + } + + } + Size++; + } + TreeNode *find(int d){ + if(d==data){ + return this; + }else if(d<=data){ + return left!=NULL?left->find(d):NULL; + }else if(d>data){ + return right!=NULL?right->find(d):NULL; + } + return NULL; + } +}; +int main(){ + TreeNode *obj=new TreeNode(20); + int arr[]={10,30,35,15,17,5,7,3}; + int len=sizeof(arr)/sizeof(arr[0]); + for(int i=0;iinsertInOreder(arr[i]); + } + cout<<"Answer...."<getRandomNode()->Data()<getRandomNode()->Data()<getRandomNode()->Data()<getRandomNode()->Data()<find(35)->Data()< +using namespace std; +class node{ +public: + int data; + node *left; + node *right; +}; +class pathsWithSum{ +public: + node *createBT(node *root,int arr[],int i,int n){ + if(idata=arr[i]; + newNode->left=NULL; + newNode->right=NULL; + root=newNode; + root->left=createBT(root->left,arr,2*i+1,n); + root->right=createBT(root->right,arr,2*i+2,n); + } + return root; + + } + void In_order(node *ptr){ + if(ptr!=NULL){ + In_order(ptr->left); + cout<data<<" "; + In_order(ptr->right); + } + } + void incrementHashTable(map &hashTable,int key,int delta){ + int newCount=hashTable[key]+delta; + if(newCount==0){ + hashTable[key]=0; + }else{ + hashTable[key]=newCount; + } + } + int countPathsWithSum(node *root,int targetSum,int runningSum,map &pathCount){ + if(root==NULL){ + return 0; + } + runningSum+=root->data; + int sum=runningSum-targetSum; + int totalPaths=pathCount[sum]; + + if(runningSum==targetSum){ + totalPaths++; + } + + incrementHashTable(pathCount,runningSum,1); + totalPaths+=countPathsWithSum(root->left,targetSum,runningSum,pathCount); + totalPaths+=countPathsWithSum(root->right,targetSum,runningSum,pathCount); + incrementHashTable(pathCount,runningSum,-1); + + return totalPaths; + } + int countPathsWithSum(node *root,int targetSum){ + map pathsCount; + return countPathsWithSum(root,targetSum,0,pathsCount); + } + +}; +int main() +{ + int arr[]={10,5,-3,3,2,0,11,3,-2,0,1}; + int len=sizeof(arr)/sizeof(arr[0]); + pathsWithSum obj; + node *root=NULL; + root=obj.createBT(root,arr,0,len); + obj.In_order(root); + cout< +using namespace std; +class node{ + public: + int data; + node *left; + node *right; +}; +class CreateBinarySearchTree{ +private: + int noOfNode=0; +public: + CreateBinarySearchTree(int n){ + noOfNode=n; + } + node *createBST(int *arr){ + return createBST(arr,0,noOfNode-1); + } + node *createBST(int *arr,int start,int endNode){ + if(endNodedata=arr[mid]; + n->left=createBST(arr,start,mid-1); + n->right=createBST(arr,mid+1,endNode); + return n; + + } + void in_Order_Traversal(node *ptr){ + if(ptr!=NULL){ + in_Order_Traversal(ptr->left); + cout<data<<" "; + in_Order_Traversal(ptr->right); + } + } + void displayBST(node *root){ + cout<<"Display BST....."< +using namespace std; +class node{ +public: + int data; + node *left; + node *right; +}; +class createLinkedLevelofBST{ +private: + int noOfNode=7; +public: + + node *BST(node *root,int i,int n){ + if(idata=i+1; + newNode->left=NULL; + newNode->right=NULL; + root=newNode; + root->left=BST(root->left,2*i+1,n); + root->right=BST(root->right,2*i+2,n); + } + return root; + } + void in_order(node *ptr){ + if(ptr!=NULL){ + in_order(ptr->left); + cout<data<<" "; + in_order(ptr->right); + } + } +// vector> createLevelDepth(node *root){ +// vector> result; +// list current; +// if(root!=NULL){ +// current.push_back(root); +// } +// while(!current.empty()){ +// +// list next_depth; +// for(node *ptr:current){ +// +// if(ptr->left!=NULL){ +// next_depth.push_back(ptr->left); +// } +// if(ptr->right!=NULL){ +// next_depth.push_back(ptr->right); +// } +// +// } +// result.push_back(current); +// current=next_depth; +// } +// +// return result; +// +// } + void createLevelDepth(node *root,vector> &lists,int level){ + + if(root==NULL) return; + + list li; + li.push_back(root); + if(lists.size()==level){ + lists.push_back(li); + }else{ + lists[level].push_back(root); + } + createLevelDepth(root->left,lists,level+1); + createLevelDepth(root->right,lists,level+1); + } + vector> createLevelDepth(node *root){ + vector> result; + createLevelDepth(root,result,0); + + return result; + } +}; +int main(){ + + node *root=NULL; + createLinkedLevelofBST obj; + root=obj.BST(root,0,7); + obj.in_order(root); + cout<> ans; + ans=obj.createLevelDepth(root); + + + int len=ans.size(); + cout<<"printed Level LinkedList"< >::iterator iter; + for(iter = ans.begin(); iter!= ans.end(); iter++){ + list li = *iter; + list::iterator it; + for(it = li.begin(); it!=li.end(); it++){ + node* ptr = *it; + cout<data<<" "; + } + cout<<'\n'; + } +// int i=0; +// list::iterator it; +// while(i!=len){ +// it=ans[i].begin(); +// for(;it!=ans[i].end();it++){ +// cout<<(*it)->data<<" "; +// } +// cout< +using namespace std; +class node{ +public: + int data; + node *left; + node *right; +}; +class checkBalanced{ +public: + node *createBST(node *ptr,int val,int n){ + if(valdata=val+1; + ptr=newNode; + newNode->left=createBST(ptr->left,2*val+1,n); + newNode->right=createBST(ptr->right,2*val+2,n); + } + return ptr; + } + void in_order(node *ptr){ + if(ptr!=NULL){ + in_order(ptr->left); + cout<data<<" "; + in_order(ptr->right); + } + } +// int getHeight(node *ptr){ +// if(ptr==NULL) return -1; +// return max(getHeight(ptr->left),getHeight(ptr->right))+1; +// } +// bool isBalanced(node *root){ +// if(root==NULL) return true; +// int heightDiff=getHeight(root->left)-getHeight(root->left); +// if(abs(heightDiff)>1){ +// return false; +// }else{ +// return (isBalanced(root->left) && isBalanced(root->right)); +// } +// +// } + int checkHeight(node *ptr){ + if(ptr==NULL) return -1; + + int leftHeight=checkHeight(ptr->left); + if(leftHeight==INT_MIN) return INT_MIN; + + int rightHeight=checkHeight(ptr->right); + if(rightHeight==INT_MIN) return INT_MIN; + + int heightDiff=leftHeight-rightHeight; + if(abs(heightDiff)>1){ + return INT_MIN; + }else{ + cout< +using namespace std; +class node{ +public: + int data; + node *left; + node *right; +}; +class ValidateBST{ +private: + int index=0; + + +public: + node *createBST(node *root,int arr[],int i,int n){ + if(idata=arr[i]; + root=newNode; + root->left=createBST(root->left,arr,2*i+1,n); + root->right=createBST(root->right,arr,2*i+2,n); + } + return root; + } + void in_order(node *ptr){ + if(ptr!=NULL){ + in_order(ptr->left); + cout<data<<" "; + in_order(ptr->right); + } + } + + void copyBST(node *ptr,int *arr){ + if(ptr==NULL){ + return; + } + + copyBST(ptr->left,arr); + arr[index]=ptr->data; + index++; + copyBST(ptr->right,arr); + + } + +// bool checkBST(node *root,int n){ +// int *arr=new int[n]; +// copyBST(root,arr); +// for(int i=1;ileft)){ + return false; + } + + if(index!=0 && root->data<=index){ + return false; + } + index=root->data; + + if(!checkBST(root->right)){ + return false; + } + return true; + + } + + bool checkBST(node *root,int MIN,int MAX){ + if(root==NULL){ + return true; + } + cout<data<data<=MIN)|| (MAX!=NULL && root->data>MAX)){ + return false; + } + + if(!checkBST(root->left,MIN,root->data) || !checkBST(root->right,root->data,MAX)){ + return false; + } + + return true; + } + + + +}; + +int main(){ + node *root=NULL; + ValidateBST obj; + int arr[]={20,10,30,5,15,25,38}; + + int n=sizeof(arr)/sizeof(arr[0]); + root=obj.createBST(root,arr,0,n); + obj.in_order(root); + cout< +using namespace std; +class node{ +public: + int data; + node *left; + node *right; + node *parent; +}; + +class Successor{ +private: + int noOFnode=7; +public: + node* createBST(node *root,int val){ + if(root==NULL){ + node *newNode=new node(); + newNode->data=val; + newNode->left=NULL; + newNode->right=NULL; + newNode->parent=NULL; + return newNode; + }else{ + node *temp; + if(valdata){ + temp=createBST(root->left,val); + root->left=temp; + temp->parent=root; + + }else{ + temp=createBST(root->right,val); + root->right=temp; + temp->parent=root; + } + return root; + } + + } + void in_order(node *ptr){ + if(ptr!=NULL){ + in_order(ptr->left); + cout<data<<" "; + in_order(ptr->right); + } + } + node *minValue(node *ptr){ + node *temp=ptr; + while(temp->left!=NULL){ + temp=temp->left; + } + return temp; + } + + node *in_Successor(node *ptr){ + if(ptr->right!=NULL) + return minValue(ptr->right); + + node *p=ptr->parent; + while(p!=NULL && p->left!=ptr){ + ptr=p; + p=p->parent; + } + return p; + + } +}; +int main(){ + + Successor obj; + node *root=NULL; + int arr[]={20,8,22,4,12,21,28,3,6,10,14}; + int n=sizeof(arr)/sizeof(arr[0]); + for(int i=0;ileft->right->right; + cout<<"find Node Successor -->"<data<data; + + return 0; +} diff --git a/Ch-4--[Trees and Graphs]/4.7 Build Order.cpp b/Ch-4--[Trees and Graphs]/4.7 Build Order.cpp new file mode 100644 index 0000000..52c68c5 --- /dev/null +++ b/Ch-4--[Trees and Graphs]/4.7 Build Order.cpp @@ -0,0 +1,129 @@ +#include +using namespace std; +class Project{ +private: + list children; + map hashMap; + char name; + int state=0; +public: + void setName(char name){ + this->name=name; + } + char getName(){ + return name; + } + void setState(int val){ + state=val; + } + int getState(){ + return state; + } + void addNeighbor(Project *node){ + if(hashMap.find(node->getName())==hashMap.end()){ + children.push_back(node); + hashMap[node->getName()]=node; + } + } + + list getChildren(){ + return children; + } +}; +class Graph{ +private: + list nodes; + map hashMap; +public: + void createNode(char name){ + if(hashMap.find(name)==hashMap.end()){ + Project *node=new Project(); + node->setName(name); + nodes.push_back(node); + hashMap[name]=node; + } + } + Project* getNode(char name){ + return hashMap[name]; + } + + void addEdge(char startName,char endName){ + Project *start=getNode(startName); + Project *End=getNode(endName); + start->addNeighbor(End); + } + list getNodes(){ + return nodes; + } + +} ; + +class findBuildOrder{ +public: + Graph buildGraph(char *proj,char dependency[][2],int dependency_len){ + Graph g; + int i=0,len=strlen(proj); + while(i!=len){ + g.createNode(proj[i]); + i++; + } + + for(int j=0;j &Stack){ + if(project->getState()==1){ + return false; + } + if(project->getState()==0){ + project->setState(1); + list children=project->getChildren(); + list::iterator m=children.begin(); + for(;m!=children.end();m++){ + if(!DFS(*m,Stack)){ + return false; + } + } + project->setState(2); + Stack.push(project); + } + + return true; + } + stack orderProjects(list projects){ + stack Stack; + list::iterator i=projects.begin(); + + while(i!=projects.end()){ + if((*i)->getState()==0){ + if(!DFS(*i,Stack)){ + return Stack; + } + } + i++; + } + return Stack; + + } +}; +int main(){ + char projects[]={'a','b','c','d','e','f','p','\0'}; + char dependency[][2]={{'a','d'},{'f','b'},{'b','d'},{'f','a'},{'d','c'},{'b','p'}}; + findBuildOrder obj; + int len=sizeof(dependency)/sizeof(dependency[0]); + Graph g; + g=obj.buildGraph(projects,dependency,len); + stack Stack=obj.orderProjects(g.getNodes()); + cout<<"Stack final Answer"<getName()<<" "; + Stack.pop(); + } + return 0; +} +//ans: f,e,b,p,a,d,c diff --git a/Ch-4--[Trees and Graphs]/4.8 First Common Ancestor.cpp b/Ch-4--[Trees and Graphs]/4.8 First Common Ancestor.cpp new file mode 100644 index 0000000..1beab9e --- /dev/null +++ b/Ch-4--[Trees and Graphs]/4.8 First Common Ancestor.cpp @@ -0,0 +1,138 @@ +#include +using namespace std; +class node{ +public: + int data; + node *left; + node *right; + node *parent; +}; +//for second approch +class result{ +public: + node *add; + bool isAncestor; + result(node *ptr,bool isAnc){ + isAncestor=isAnc; + add=ptr; + } +}; +//for second approch + +class firstCommonAncestor{ +private: + list temp; +public: + node *createBT(node *ptr,int arr[],int n,int i,node *parent){ + if(idata=arr[i]; + if(arr[i]==78 || arr[i]==96){ + temp.push_back(newNode); + } + newNode->parent=parent; + ptr=newNode; + ptr->left=createBT(ptr->left,arr,n,2*i+1,ptr); + ptr->right=createBT(ptr->right,arr,n,2*i+2,ptr); + + } + return ptr; + } + void in_order(node *ptr){ + if(ptr!=NULL){ + in_order(ptr->left); +// cout<data<<" "<parent->data<data<<" "<parent!=NULL){ + cout<<"Parent data : "<parent->data<<" "<right); + } + + } + list getFindNode(){ + return temp; + } + node * getSibling(node *ptr){ + if(ptr==NULL || ptr->parent==NULL){ + return NULL; + } + node *parent; + parent=ptr->parent; + return (parent->left==ptr?parent->right:parent->left); + + } + bool covers(node *root,node *temp){ + if(root==NULL){ + return false; + } + if(root==temp){ + return true; + } + return (covers(root->left,temp)||covers(root->right,temp)); + + } + + + //second approach + result *commonAncestorHelper(node *root,node *p,node *q){ + if(root==NULL){ + result *rNull=new result(NULL,false); + return rNull; + } + if(root==p && root==q){ + result *rAns=new result(root,true); + return rAns; + } + result *rx=commonAncestorHelper(root->left,p,q); + if(rx->isAncestor){ + return rx; + } + + result *ry=commonAncestorHelper(root->right,p,q); + if(ry->isAncestor){ + return ry; + } + + if(rx->add!=NULL && ry->add!=NULL){ + result *rAns=new result(root,true); + return rAns; + }else if(root==p || root==q){ + bool isAns=rx->add!=NULL || ry->add!=NULL; + result *rAns=new result(root,isAns); + return rAns; + }else{ + result *rAns=new result(rx->add!=NULL?rx->add:ry->add,false); + return rAns; + } + + } + node *commonAncestor(node *root,node *p,node*q){ + result *r=commonAncestorHelper(root,p,q); + if(r->isAncestor){ + return (r->add); + } + return NULL; + + } + //second end + +}; +int main(){ + node *root=NULL; + firstCommonAncestor obj; + int arr[]={12,36,54,78,96,31,45}; + int n=sizeof(arr)/sizeof(arr[0]); + root=obj.createBT(root,arr,n,0,NULL); +// obj.in_order(root); + list nodesPQ; + nodesPQ=obj.getFindNode(); + node *p,*q; + p=nodesPQ.front(); + q=nodesPQ.back(); +// cout<data<<" "<data; + node *ans; + ans=obj.commonAncestor(root,p,q); + cout<data; + return 0; +} diff --git a/Ch-4--[Trees and Graphs]/4.9 BST Sequences.cpp b/Ch-4--[Trees and Graphs]/4.9 BST Sequences.cpp new file mode 100644 index 0000000..f70c3bf --- /dev/null +++ b/Ch-4--[Trees and Graphs]/4.9 BST Sequences.cpp @@ -0,0 +1,134 @@ +#include +using namespace std; +class node{ +public: + int data; + node *left; + node *right; +}; +class BST_sequences{ +public: + node* createBST(node *root,int data){ + + if(root==NULL){ + node *newNode=new node(); + newNode->data=data; + newNode->left=NULL; + newNode->right=NULL; + return newNode; + }else{ + node *tmp; + if(root->data>data){ + tmp=createBST(root->left,data); + root->left=tmp; + + }else{ + tmp=createBST(root->right,data); + root->right=tmp; + } + return root; + } + + } + void in_order(node *ptr){ + if(ptr!=NULL){ + in_order(ptr->left); + cout<data<<" "; + in_order(ptr->right); + } + } + void wevedlist(list first,list second,list> &results,list prefix){ + if(first.size()==0 || second.size()==0){ + list result; + result.assign(prefix.begin(),prefix.end()); + list::iterator i=first.begin(); + for(;i!=first.end();i++){ + result.push_back(*i); + } + i=second.begin(); + for(;i!=second.end();i++){ + result.push_back(*i); + } + results.push_back(result); + return; + } + + int headFirst=first.front(); + first.pop_front(); + prefix.push_back(headFirst); + wevedlist(first,second,results,prefix); + prefix.pop_back(); + first.push_front(headFirst); + + int headSecond=second.front(); + second.pop_front(); + prefix.push_back(headSecond); + wevedlist(first,second,results,prefix); + prefix.pop_back(); + second.push_front(headSecond); + + + } + list> allSequences(node *root){ + list> results; + + if(root==NULL){ + list q; + results.push_back(q); + return results; + } + if (root -> left == NULL && root -> right == NULL) { + list seq; + seq.push_back(root -> data); + results.push_back(seq); + return results; + } + + list prefix; + prefix.push_back(root->data); + + list> leftSeq=allSequences(root->left); + list> rightSeq=allSequences(root->right); + list>::iterator left=leftSeq.begin(); + list>::iterator right=rightSeq.begin(); + + for(;left!=leftSeq.end();left++){ + for(;right!=rightSeq.end();right++){ + list> weaved; + wevedlist(*left,*right,weaved,prefix); +// results.assign(weaved.begin(),weaved.end()); + list>::iterator i=weaved.begin(); + for(;i!=weaved.end();i++){ + results.push_back(*i); + } + } + } + return results; + } + +}; + +int main(){ + node *root=NULL; + BST_sequences obj; + int arr[]={7,5,9,1,6,8,10}; + int n=sizeof(arr)/sizeof(arr[0]); + + for(int i=0;i> ans; + ans=obj.allSequences(root); + cout<<"Main Answer....."<>::iterator i=ans.begin(); + list::iterator j; + for(;i!=ans.end();i++){ + for(j=(*i).begin();j!=(*i).end();j++){ + cout<<*j<<" "; + } + cout< +using namespace std; +//int countWays(int n){ +// if(n<0){ +// return 0; +// }else if(n==0){ +// return 1; +// }else{ +// return countWays(n-1)+countWays(n-2)+countWays(n-3); +// } +//} +int countWays(int n,int *arr){ + if(n<0){ + return 0; + }else if(n==0){ + return 1; + }else if(arr[n]>-1){ + return arr[n]; + }else{ + arr[n]=countWays(n-1,arr)+countWays(n-2,arr)+countWays(n-3,arr); + return arr[n]; + } +} +int countWays(int n){ + int *arr=new int[n+1]; + fill(arr,arr+n+1,-1); + return countWays(n,arr); +} + +int main(){ + cout< +using namespace std; +enum Color{Black,White,Red,Blue,green}; +bool PaintFill(Color screen[4][4],int r,int c,Color oColor,Color nColor){ + if(r<0 || r>=4 || c<0 || c>=4){ + return false; + } + if(screen[r][c]==oColor){ + screen[r][c]=nColor; + PaintFill(screen,r-1,c,oColor,nColor); + PaintFill(screen,r+1,c,oColor,nColor); + PaintFill(screen,r,c-1,oColor,nColor); + PaintFill(screen,r,c+1,oColor,nColor); + } + return true; +} +bool PaintFill(Color screen[4][4],int r,int c,Color nColor){ + if(screen[r][c]==nColor) return false; + return PaintFill(screen,r,c,screen[r][c],nColor); +} + +int main(){ + Color screen[4][4]={{Black,Black,Red,Blue},{Black,White,Red,Blue},{Black,Black,Red,Blue},{green,White,Red,Blue}}; + + if(PaintFill(screen,0,0,Red)){ + cout<<"Yes"< +using namespace std; +int makeChange(int amount,int denoms[],int len,int index,map &memo){ + if(amount==0) return 1; + if(index>=len) return 0; + string key=to_string(amount+index); + if(memo[key]>0){ + return memo[key]; + } + int denomAmount=denoms[index]; + int ways=0; + + for(int i=0;(i*denomAmount)<=amount;i++){ + int remainingAmount=amount-(i*denomAmount); + ways+=makeChange(remainingAmount,denoms,len,index+1,memo); + } + memo[key]=ways; + return ways; +} +int makeChange(int n){ + int denoms[]={25,10,5,1}; + int len=sizeof(denoms)/sizeof(denoms[0]); + map memo; + return makeChange(n,denoms,len,0,memo); +} +int main(){ + int n=100; + cout< +using namespace std; +int GRID_SIZE=8; +bool checkValid(vector &columns,int row1,int column1){ + for(int row2=0;row2 columns,list> &results){ + if(row==GRID_SIZE){ + results.push_back(columns); + }else{ + + for(int col=0;col columns{-1,-1,-1,-1,-1,-1,-1,-1}; + list> results; + placeQueens(0,columns,results); + list>::iterator i=results.begin(); + for(;i!=results.end();i++){ + vector::iterator j=(*i).begin(); + for(;j!=(*i).end();j++){ + cout<<*j<<" "; + } + cout< +using namespace std; +class Box{ + public: + int height; +}; +int createStack(vector &boxes,int bottomIndex,int stackMap[]){ + if(bottomIndex0){ + return stackMap[bottomIndex]; + } + Box *bottom=boxes[bottomIndex]; + int maxHeight=0; + for(int i=bottomIndex+1;iheight)<(boxes[i]->height)){ + int height=createStack(boxes,i,stackMap); + maxHeight=max(maxHeight,height); + } + } + maxHeight+=bottom->height; + stackMap[bottomIndex]=maxHeight; + return maxHeight; + +} +int comapare(Box *x,Box *y){ + return (y->height-x->height); +} +int createStack(vector &boxes){ + sort(boxes.begin(),boxes.end(),comapare); + int stackMap[boxes.size()]={}; + int maxHeight=0; + for(int i=0;i boxes; + for(int j=32;j!=22;j--){ + Box *newBox=new Box(); + newBox->height=j; + boxes.push_back(newBox); + } + cout<::iterator i=boxes.begin(); +// for(;i!=boxes.end();i++){ +// cout<<(*i)->height<<" "; +// } + return 0; +} diff --git a/Ch-8--[Recursion and Dynamic Programming]/8.14 Boolean Evaluation.cpp b/Ch-8--[Recursion and Dynamic Programming]/8.14 Boolean Evaluation.cpp new file mode 100644 index 0000000..7875d88 --- /dev/null +++ b/Ch-8--[Recursion and Dynamic Programming]/8.14 Boolean Evaluation.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; +bool stringToBool(string c){ + if(c[0]=='1'){ + return true; + }else{ + return false; + } +} +int countEval(string s,bool result,map &memo){ + if(s.size()==0) return 0; + if(s.size()==1){ + return stringToBool(s)==result?1:0; + } + if(memo.find(to_string(result)+s)!=memo.end()){ + return memo[to_string(result)+s]; + } + + int ways=0; + + for(int i=0;i memo; + cout< +using namespace std; +class Point{ + public: + int row; + int col; + Point(int r,int c){ + row=r; + col=c; + } +}; +int **createMatrix(int rows,int cols){ + int **matrix=new int*[rows]; + for(int i=0;i &path,unordered_set &duplicateVisits){ + if(currRow<0 || currCol<0 || matrix[currRow][currCol]==-1){ + return false; + } + + Point * currPos=new Point(currRow,currCol); + + if(duplicateVisits.find(currPos)!=duplicateVisits.end()){ + return false; + } + + bool atOrigin=currRow==0 && currCol==0; + if(atOrigin || getPath(matrix,currRow-1,currCol,path,duplicateVisits) || getPath(matrix,currRow,currCol-1,path,duplicateVisits)){ + path.push_back(currPos); + return true; + } + duplicateVisits.insert(currPos); + return false; +} +vector getPath(int **matrix,int row,int col){ + vector path; + unordered_set duplicteVisits; + + + if(row!=0 || matrix!=nullptr){ + if(getPath(matrix,row-1,col-1,path,duplicteVisits)){ + return path; + } + } + + return path; +} +int main(){ + int **matrix=createMatrix(5,7); + matrix[1][3] = -1; + matrix[2][5] = -1; + matrix[3][2] = -1; + matrix[0][1] = -1; + + vectorpath=getPath(matrix,5,7); + if(path.size()==0){ + cout<<"Paths Not Exists"<row<<" "<col< +using namespace std; +int magicIndexDistinct(int arr[],int start,int end){ + if(endmid){ + return magicIndexDistinct(arr,start,mid-1); + }else{ + return magicIndexDistinct(arr,mid+1,end); + } + +} +int magicIndexNonDistinct(int arr[],int start,int end){ + if(end0){ + return left; + } + + int rightIndex=max(mid+1,arr[mid]); + int right=magicIndexDistinct(arr,rightIndex,end); + + return right; + + +} +int main(){ + +// int arr[]={-40,-20,-1,1,2,3,5,7,9,12,13}; + int arr[]={-10,-5,2,2,2,3,4,7,9,12,13}; + int len=sizeof(arr)/sizeof(arr[0]); + + cout<<"Magic Index Is : "< +using namespace std; +list> getSubsets(vector &set,int index){ + list> allSubsets; + if(set.size()==index){ + vector emptySet; + allSubsets.push_back(emptySet); + }else{ + allSubsets=getSubsets(set,index+1); + int item=set[index]; + list> mySubsets; + for(auto subset:allSubsets){ + vector newSubset; + newSubset=subset; + newSubset.push_back(item); + mySubsets.push_back(newSubset); + } + list>::iterator i=mySubsets.begin(); + for(;i!=mySubsets.end();i++){ + allSubsets.push_back(*i); + } + } + return allSubsets; +} +vector convertIntToSet(int x,vector &set){ + vector subset; + int index=0; + for(int k=x;k>0;k>>=1){ + if((k&1)==1){ + subset.push_back(set[index]); + } + index++; + } + return subset; +} +list> getSubsetsSeconSolution(vector &set){ + list> allSubsets; + int maxValue=1< set{1,2,3}; + list> ans; +// ans=getSubsets(set,0); + ans=getSubsetsSeconSolution(set); + list>::iterator i=ans.begin(); + for(;i!=ans.end();i++){ + vector::iterator j=(*i).begin(); + for(;j!=(*i).end();j++){ + cout<<*j<<" "; + } + cout< +using namespace std; + +int minProductHelper(int smaller,int bigger){ + if(smaller==0){ + return 0; + }else if(smaller==1){ + return bigger; + } + + int s=smaller>>1; + int side1=minProductHelper(s,bigger); + int side2=side1; + if(smaller%2==1){ + side2=minProductHelper(smaller-s,bigger); + } + return side1+side2; +} + +//int minProduct(int a,int b){ +// int bigger=a>b?a:b; +// int smaller=a>b?b:a; +// return minProductHelper(smaller,bigger); +//} +int minProduct(int smaller,int bigger,int *memo){ + if(smaller==0){ + return 0; + }else if(smaller==1){ + return bigger; + }else if(memo[smaller]>0){ + return memo[smaller]; + } + int s=smaller>>1; + int side=minProduct(s,bigger,memo); + int side2=side; + if(smaller%2==1){ + + side2=minProduct(smaller-s,bigger,memo); + } + + + memo[smaller]=side+side2; + return memo[smaller]; +} +int minProduct(int a,int b){ + int smaller=a>b?b:a; + int bigger=a>b?a:b; + int *memo=new int[smaller+1]; + fill(memo,memo+smaller+1,0); + return minProduct(smaller,bigger,memo); + +} +int main(){ + int a=9,b=7; + cout< +using namespace std; +class Tower{ +public: + stack disks; + int index; + Tower(int i){ + index=i; + } + int Index(){ + return index; + } + void add(int d){ + if(!disks.empty() && disks.top()<=d) + { + cout<<"Error Placing Disks : "<add(top); + } + void moveDisks(int n,Tower *destination,Tower *buffer){ + if(n>0){ + moveDisks(n-1,buffer,destination); + moveTopTo(destination); + moveDisks(n-1,destination,this); + } + } + void printTower(){ + while(!disks.empty()){ + cout<0;i--){ + towers[0]->add(i); + } + towers[0]->moveDisks(n,towers[2],towers[1]); + towers[2]->printTower(); + + return 0; +} diff --git a/Ch-8--[Recursion and Dynamic Programming]/8.7 Permutations Without Dups.cpp b/Ch-8--[Recursion and Dynamic Programming]/8.7 Permutations Without Dups.cpp new file mode 100644 index 0000000..d59abd3 --- /dev/null +++ b/Ch-8--[Recursion and Dynamic Programming]/8.7 Permutations Without Dups.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; +string insertCharAt(string word,char c,int i){ + string start=word.substr(0,i); + string end=word.substr(i); + return (start+c+end); +} +list getPerms(string str){ + list permutations; + if(str.empty()){ + string s=""; + permutations.push_back(s); + return permutations; + } + + char first=str[0]; + string reminder=str.substr(1); + list words=getPerms(reminder); + list::iterator i=words.begin(); + for(;i!=words.end();i++){ + for(int j=0;j<=(*i).size();j++){ + string s=insertCharAt(*i,first,j); + permutations.push_back(s); + } + } + return permutations; +} + +//second approach +void getParmsSecond(string prefix,string reminder,list &result){ + if(reminder.size()==0){ + result.push_back(prefix); + } + + int len=reminder.size(); + for(int i=0;i getParmsSecond(string str){ + list result; + getParmsSecond("",str,result); + return result; +} + +//end of second approach +int main(){ + string str="ABCD"; + list ans; +// ans=getPerms(str); + ans=getParmsSecond(str); + list::iterator i=ans.begin(); + for(;i!=ans.end();i++){ + cout<<*i< +using namespace std; +map buildFreqTable(string str){ + map freq; + int i=0; + while(i!=str.size()){ + if(freq.find(str[i])==freq.end()){ + freq[str[i]]=0; + } + freq[str[i]]+=1; + i++; + } + + return freq; +} +void printPerms(map &frequency,string prefix,int remaining,list &result){ + if(remaining==0){ + result.push_back(prefix); + return; + } + map::iterator i=frequency.begin(); + for(;i!=frequency.end();i++){ + int count=frequency[i->first]; + if(count>0){ + frequency[i->first]-=1; + printPerms(frequency,prefix+(i->first),remaining-1,result); + frequency[i->first]=count; + } + } + +} +list printPerms(string str){ + list result; + map frequency=buildFreqTable(str); + printPerms(frequency,"",str.size(),result); + return result; +} +int main(){ + string str="aabbbbc"; + list ans; + ans=printPerms(str); + list::iterator i=ans.begin(); + for(;i!=ans.end();i++){ + cout<<*i< +using namespace std; +string insertInside(string str,int leftIndex){ + string left=str.substr(0,leftIndex+1); + string right=str.substr(leftIndex+1,str.size()); + return left+"()"+right; + +} +set generateParens(int remaining){ + set result; + + if(remaining==0){ + result.insert(""); + }else{ + set prev=generateParens(remaining-1); + set::iterator itr=prev.begin(); + for(;itr!=prev.end();itr++){ + for(int i=0;i<(*itr).size();i++){ + if((*itr)[i]=='('){ + string s=insertInside((*itr),i); + result.insert(s); + } + } + result.insert("()"+(*itr)); + } + + } + return result; +} + +//second approach +void addParen(list &result,int leftRem,int rightRem,char *str,int count){ + if(leftRem<0 || rightRem0){ + str[count]='('; + addParen(result,leftRem-1,rightRem,str,count+1); + } + if(rightRem>leftRem){ + str[count]=')'; + addParen(result,leftRem,rightRem-1,str,count+1); + } + + } +} +list generateParensSecond(int count){ + char *str=new char[count*2]; +// fill(str,str+(count*2),'0'); + list result; + addParen(result,count,count,str,0); + return result; + +} + +//end of second approach +int main(){ + int n=4; + set ans; + ans=generateParens(n); + set::iterator i=ans.begin(); + for(;i!=ans.end();i++){ + cout<<*i< ansSecond; + ansSecond=generateParensSecond(n); + list::iterator j=ansSecond.begin(); + for(;j!=ansSecond.end();j++){ + cout<<*j<