From ba7c008a9017715227c0d99345fbf477bb37fa53 Mon Sep 17 00:00:00 2001 From: CODESTIEN <32845547+Tarunyo@users.noreply.github.com> Date: Tue, 2 Oct 2018 15:01:06 +0530 Subject: [PATCH 01/20] made change --- DisjointSet.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/DisjointSet.cpp b/DisjointSet.cpp index 1608234..dc9578b 100644 --- a/DisjointSet.cpp +++ b/DisjointSet.cpp @@ -57,6 +57,7 @@ int main(){ cout< Date: Tue, 2 Oct 2018 16:18:37 +0530 Subject: [PATCH 02/20] Add files via upload --- stack.cpp | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 stack.cpp diff --git a/stack.cpp b/stack.cpp new file mode 100644 index 0000000..480bede --- /dev/null +++ b/stack.cpp @@ -0,0 +1,76 @@ +#include +#include + +void main() +{clrscr(); +struct node +{ +int info; +node *next; +}*top,*save,*ptr; + +int c=0,data; +top=NULL; + +while(c<3) +{ +cout<<"1.Push\n2.Pop\n3.Exit\n"; +cin>>c; + +switch(c) +{ +case 1: +cout<<"Enter Data\n"; +cin>>data; +ptr =new node; +ptr->info=data; +ptr->next=NULL; + +if(top==NULL) +{ +top=ptr; +cout<<"Item Inserted\n"; +} + +else +{ +save=top; +top=ptr; +top->next=save; +cout<<"Item Inserted\n"; +} + +break; + +case 2: +if(top==NULL) +{ +cout<<"Underflow\n"; +} + +else +{ +ptr=top; +top=top->next; +delete ptr; +cout<<"Item Deleted\n"; +} +break; +} + +if(top!=NULL) +{ +cout<<"Stack:\n"; +ptr=top; +while(ptr!=NULL) +{ +cout<<"<-"<info; +ptr=ptr->next; +} +cout<<"\n"; +} + +} + +} + From 9985388467e11fb614f2db358115ce95a19a1f99 Mon Sep 17 00:00:00 2001 From: Rohit Kumar Date: Tue, 2 Oct 2018 16:20:35 +0530 Subject: [PATCH 03/20] Create heap.cpp --- heap.cpp | 142 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 heap.cpp diff --git a/heap.cpp b/heap.cpp new file mode 100644 index 0000000..dc596b0 --- /dev/null +++ b/heap.cpp @@ -0,0 +1,142 @@ + +// A C++ program to Create Binary Heap Operations +#include +#include +using namespace std; + +// Prototype of a utility function to swap two integers +void swap(int *x, int *y); + +// A class for Min Heap +class MinHeap +{ + int *harr; // pointer to array of elements in heap + int capacity; // maximum possible size of min heap + int heap_size; // Current number of elements in min heap +public: + // Constructor + MinHeap(int capacity); + + // to heapify a subtree with the root at given index + void MinHeapify(int ); + + int parent(int i) { return (i-1)/2; } + + // to get index of left child of node at index i + int left(int i) { return (2*i + 1); } + + // to get index of right child of node at index i + int right(int i) { return (2*i + 2); } + + // to extract the root which is the minimum element + int extractMin(); + + // Decreases key value of key at index i to new_val + void decreaseKey(int i, int new_val); + + // Returns the minimum key (key at root) from min heap + int getMin() { return harr[0]; } + + // Deletes a key stored at index i + void deleteKey(int i); + + // Inserts a new key 'k' + void insertKey(int k); +}; + +// Constructor: Builds a heap from a given array a[] of given size +MinHeap::MinHeap(int cap) +{ + heap_size = 0; + capacity = cap; + harr = new int[cap]; +} + +// Inserts a new key 'k' +void MinHeap::insertKey(int k) +{ + if (heap_size == capacity) + { + cout << "\nOverflow: Could not insertKey\n"; + return; + } + + // First insert the new key at the end + heap_size++; + int i = heap_size - 1; + harr[i] = k; + + // Fix the min heap property if it is violated + while (i != 0 && harr[parent(i)] > harr[i]) + { + swap(&harr[i], &harr[parent(i)]); + i = parent(i); + } +} + +// Decreases value of key at index 'i' to new_val. It is assumed that +// new_val is smaller than harr[i]. +void MinHeap::decreaseKey(int i, int new_val) +{ + harr[i] = new_val; + while (i != 0 && harr[parent(i)] > harr[i]) + { + swap(&harr[i], &harr[parent(i)]); + i = parent(i); + } +} + +// Method to remove minimum element (or root) from min heap +int MinHeap::extractMin() +{ + if (heap_size <= 0) + return INT_MAX; + if (heap_size == 1) + { + heap_size--; + return harr[0]; + } + + // Store the minimum value, and remove it from heap + int root = harr[0]; + harr[0] = harr[heap_size-1]; + heap_size--; + MinHeapify(0); + + return root; +} + + +// This function deletes key at index i. It first reduced value to minus +// infinite, then calls extractMin() +void MinHeap::deleteKey(int i) +{ + decreaseKey(i, INT_MIN); + extractMin(); +} + +// A recursive method to heapify a subtree with the root at given index +// This method assumes that the subtrees are already heapified +void MinHeap::MinHeapify(int i) +{ + int l = left(i); + int r = right(i); + int smallest = i; + if (l < heap_size && harr[l] < harr[i]) + smallest = l; + if (r < heap_size && harr[r] < harr[smallest]) + smallest = r; + if (smallest != i) + { + swap(&harr[i], &harr[smallest]); + MinHeapify(smallest); + } +} + +// A utility function to swap two elements +void swap(int *x, int *y) +{ + int temp = *x; + *x = *y; + *y = temp; +} From 290745c63029d3ff0605c8dfc0b4eb7ecc971c2d Mon Sep 17 00:00:00 2001 From: KSHITIJ BITHEL <32517082+KSHITIJBITHEL@users.noreply.github.com> Date: Tue, 2 Oct 2018 16:22:29 +0530 Subject: [PATCH 04/20] added bubble sort optimized bubble sort --- sort/bubble_sort.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 sort/bubble_sort.cpp diff --git a/sort/bubble_sort.cpp b/sort/bubble_sort.cpp new file mode 100644 index 0000000..a3e8708 --- /dev/null +++ b/sort/bubble_sort.cpp @@ -0,0 +1,47 @@ +//this is optimized . here number of swaps will be less; +//time complexity: +//best case: O(n) +//Average and worst case: O(n²) +//space complexity O(1); + +#include +using namespace std; + +void bubbleSort(int a[],int n){ + int count=0; + for(int i=0;ia[j+1]){ + swap(a[j],a[j+1]); + isSorted=false; + + } + count++; + if(isSorted){ + break; + } + } + + } + cout<<"Number of swaps: "< Date: Sat, 27 Oct 2018 17:50:37 +0530 Subject: [PATCH 05/20] Segement tree added for sum of given range problem. --- SegmentTree.cpp | 159 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 SegmentTree.cpp diff --git a/SegmentTree.cpp b/SegmentTree.cpp new file mode 100644 index 0000000..05699d1 --- /dev/null +++ b/SegmentTree.cpp @@ -0,0 +1,159 @@ + +// C program to show segment tree operations like construction, query +// and update +#include +#include + +// A utility function to get the middle index from corner indexes. +int getMid(int s, int e) { return s + (e -s)/2; } + +/* A recursive function to get the sum of values in given range + of the array. The following are parameters for this function. + + st --> Pointer to segment tree + si --> Index of current node in the segment tree. Initially + 0 is passed as root is always at index 0 + ss & se --> Starting and ending indexes of the segment represented + by current node, i.e., st[si] + qs & qe --> Starting and ending indexes of query range */ +int getSumUtil(int *st, int ss, int se, int qs, int qe, int si) +{ + // If segment of this node is a part of given range, then return + // the sum of the segment + if (qs <= ss && qe >= se) + return st[si]; + + // If segment of this node is outside the given range + if (se < qs || ss > qe) + return 0; + + // If a part of this segment overlaps with the given range + int mid = getMid(ss, se); + return getSumUtil(st, ss, mid, qs, qe, 2*si+1) + + getSumUtil(st, mid+1, se, qs, qe, 2*si+2); +} + +/* A recursive function to update the nodes which have the given + index in their range. The following are parameters + st, si, ss and se are same as getSumUtil() + i --> index of the element to be updated. This index is + in the input array. + diff --> Value to be added to all nodes which have i in range */ +void updateValueUtil(int *st, int ss, int se, int i, int diff, int si) +{ + // Base Case: If the input index lies outside the range of + // this segment + if (i < ss || i > se) + return; + + // If the input index is in range of this node, then update + // the value of the node and its children + st[si] = st[si] + diff; + if (se != ss) + { + int mid = getMid(ss, se); + updateValueUtil(st, ss, mid, i, diff, 2*si + 1); + updateValueUtil(st, mid+1, se, i, diff, 2*si + 2); + } +} + +// The function to update a value in input array and segment tree. +// It uses updateValueUtil() to update the value in segment tree +void updateValue(int arr[], int *st, int n, int i, int new_val) +{ + // Check for erroneous input index + if (i < 0 || i > n-1) + { + printf("Invalid Input"); + return; + } + + // Get the difference between new value and old value + int diff = new_val - arr[i]; + + // Update the value in array + arr[i] = new_val; + + // Update the values of nodes in segment tree + updateValueUtil(st, 0, n-1, i, diff, 0); +} + +// Return sum of elements in range from index qs (quey start) +// to qe (query end). It mainly uses getSumUtil() +int getSum(int *st, int n, int qs, int qe) +{ + // Check for erroneous input values + if (qs < 0 || qe > n-1 || qs > qe) + { + printf("Invalid Input"); + return -1; + } + + return getSumUtil(st, 0, n-1, qs, qe, 0); +} + +// A recursive function that constructs Segment Tree for array[ss..se]. +// si is index of current node in segment tree st +int constructSTUtil(int arr[], int ss, int se, int *st, int si) +{ + // If there is one element in array, store it in current node of + // segment tree and return + if (ss == se) + { + st[si] = arr[ss]; + return arr[ss]; + } + + // If there are more than one elements, then recur for left and + // right subtrees and store the sum of values in this node + int mid = getMid(ss, se); + st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + + constructSTUtil(arr, mid+1, se, st, si*2+2); + return st[si]; +} + +/* Function to construct segment tree from given array. This function + allocates memory for segment tree and calls constructSTUtil() to + fill the allocated memory */ +int *constructST(int arr[], int n) +{ + // Allocate memory for the segment tree + + //Height of segment tree + int x = (int)(ceil(log2(n))); + + //Maximum size of segment tree + int max_size = 2*(int)pow(2, x) - 1; + + // Allocate memory + int *st = new int[max_size]; + + // Fill the allocated memory st + constructSTUtil(arr, 0, n-1, st, 0); + + // Return the constructed segment tree + return st; +} + +// Driver program to test above functions +int main() +{ + int arr[] = {1, 3, 5, 7, 9, 11}; + int n = sizeof(arr)/sizeof(arr[0]); + + // Build segment tree from given array + int *st = constructST(arr, n); + + // Print sum of values in array from index 1 to 3 + printf("Sum of values in given range = %dn", + getSum(st, n, 1, 3)); + + // Update: set arr[1] = 10 and update corresponding + // segment tree nodes + updateValue(arr, st, n, 1, 10); + + // Find sum after the value is updated + printf("Updated sum of values in given range = %dn", + getSum(st, n, 1, 3)); + return 0; +} From 9b206c56e9c7cfcb94bdfee210e048d8f4136a56 Mon Sep 17 00:00:00 2001 From: Sourabh Singh <32551625+singhsourabh@users.noreply.github.com> Date: Sat, 27 Oct 2018 18:16:44 +0530 Subject: [PATCH 06/20] Create Fenwick-tree.cpp --- Fenwick-tree.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Fenwick-tree.cpp diff --git a/Fenwick-tree.cpp b/Fenwick-tree.cpp new file mode 100644 index 0000000..7e9cae6 --- /dev/null +++ b/Fenwick-tree.cpp @@ -0,0 +1,30 @@ +#include +#define LSB(x) x&-x +using namespace std; +int BIT[1000], A[1000], N; +void update(int idx, int val){ + for(; idx<=N; idx+= LSB(idx)){ + BIT[idx] += val; + } +} + +int query(int idx){ + int sum = 0; + for(; idx>0; idx-= LSB(idx)){ + sum += BIT[idx]; + } + return sum; +} + +int main(){ + N = 16; + int l,r; + //creating BIT + for(int i = 1; i<=N; i++){ + A[i] = i; + update(i, A[i]); + } + //range query + cin >> l >> r; + cout << query(r) - query(l-1); +} From f398148386a9345fccf7e06a914799cdb3754100 Mon Sep 17 00:00:00 2001 From: Amit Sarkar Date: Sat, 27 Oct 2018 18:17:10 +0530 Subject: [PATCH 07/20] segment tree with lazy propagation --- Segment Tree Lazy Propagation.cpp | 67 ++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Segment Tree Lazy Propagation.cpp diff --git a/Segment Tree Lazy Propagation.cpp b/Segment Tree Lazy Propagation.cpp new file mode 100644 index 0000000..fc9c562 --- /dev/null +++ b/Segment Tree Lazy Propagation.cpp @@ -0,0 +1,67 @@ +#include +using namespace std; +typedef long long int ll; +ll tree[400001],tree1[400001]; +void lazy(ll node,ll l,ll r) +{ + tree[node]+=tree1[node]*(r-l+1); + if(l==r) + { + tree1[node]=0; + return; + } + tree1[2*node]+=tree1[node]; + tree1[2*node+1]+=tree1[node]; + tree1[node]=0; +} +ll q0(ll node,ll l,ll r,ll l1,ll r1,ll val=0){ + //cout<>t; + while(t--) + { + ll n,m; + cin>>n>>m; + ll i,j,k; + memset(tree,0,sizeof(tree)); + memset(tree1,0,sizeof(tree1)); + while(m--) + { + ll x,p,q,v; + cin>>x; + if(x==0) + { + cin>>p>>q>>v; + q0(1,1,n,p,q,v); + } + else{ + cin>>p>>q; + cout< Date: Sat, 27 Oct 2018 18:32:49 +0530 Subject: [PATCH 08/20] Added Binary Indexed Tree --- BIT_subarrays_sum_in_given_range.cpp | 55 ++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 BIT_subarrays_sum_in_given_range.cpp diff --git a/BIT_subarrays_sum_in_given_range.cpp b/BIT_subarrays_sum_in_given_range.cpp new file mode 100644 index 0000000..a25a08a --- /dev/null +++ b/BIT_subarrays_sum_in_given_range.cpp @@ -0,0 +1,55 @@ +#include +using namespace std; +#define N 500000 +pair a[N+1],c[N+1]; +long long int b; +int bit[N+1]; +void update(int ind,int n) +{ + while(ind<=n) + { + bit[ind]++; + ind+=ind&(-ind); + } +} +long long int que(int ind) +{ + long long int ans=0; + while(ind>0) + { + ans+=bit[ind]; + ind-=ind&(-ind); + } + return ans; +} +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(0); + int n,q; + long long int cnt,l,r; + cin>>n>>q; + for(int i=1;i<=n;i++) + cin>>b,a[i].first+=a[i-1].first+b,a[i].second=i,c[i]=a[i]; + sort(c+1,c+n+1); + for(int i=1;i<=n;i++) + a[c[i].second].second=i; + while(q--) + { + cnt=0; + cin>>l>>r; + for(int i=1;i<=n;i++) + { + int h=upper_bound(c+1,c+n+1,make_pair(a[i].first-l,INT_MAX))-c; + int lo=lower_bound(c+1,c+n+1,make_pair(a[i].first-r,INT_MIN))-c; + if(a[i].first>=l && a[i].first<=r) + cnt+=1; + cnt+=que(h-1)-que(lo-1); + update(a[i].second,n); + } + cout< Date: Sat, 27 Oct 2018 18:35:30 +0530 Subject: [PATCH 09/20] Create k-dimensionaltree.cpp --- k-dimensionaltree.cpp | 109 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 k-dimensionaltree.cpp diff --git a/k-dimensionaltree.cpp b/k-dimensionaltree.cpp new file mode 100644 index 0000000..3789077 --- /dev/null +++ b/k-dimensionaltree.cpp @@ -0,0 +1,109 @@ +// A C++ program to demonstrate operations such as searching and insertion of KD tree + +#include +using namespace std; + +const int k = 2; + +// A structure to represent node of the kd tree +struct Node +{ + int point[k]; // To store k dimensional point + Node *left, *right; +}; + +// A method to create a node of K D tree +struct Node* newNode(int arr[]) +{ + struct Node* temp = new Node; + + for (int i=0; ipoint[i] = arr[i]; + + temp->left = temp->right = NULL; + return temp; +} + +// Inserts a new node and returns root of modified tree The parameter depth is used to decide axis of comparison +Node *insertRec(Node *root, int point[], unsigned depth) +{ + // Tree is empty? + if (root == NULL) + return newNode(point); + + // Calculate current dimension (cd) of comparison + unsigned cd = depth % k; + + // Compare the new point with root on current dimension 'cd' and decide the left or right subtree + if (point[cd] < (root->point[cd])) + root->left = insertRec(root->left, point, depth + 1); + else + root->right = insertRec(root->right, point, depth + 1); + + return root; +} + +// Function to insert a new point with given point in KD Tree and return new root. It mainly uses above recursive function "insertRec()" +Node* insert(Node *root, int point[]) +{ + return insertRec(root, point, 0); +} + +// A utility method to determine if two Points are same +// in K Dimensional space +bool arePointsSame(int point1[], int point2[]) +{ + // Compare individual pointinate values + for (int i = 0; i < k; ++i) + if (point1[i] != point2[i]) + return false; + + return true; +} + +// Searches a Point represented by "point[]" in the K D tree. The parameter depth is used to determine current axis. +bool searchRec(Node* root, int point[], unsigned depth) +{ + // Base cases + if (root == NULL) + return false; + if (arePointsSame(root->point, point)) + return true; + + // Current dimension is computed using current depth and total dimensions (k) + unsigned cd = depth % k; + + // Compare point with root with respect to cd (Current dimension) + if (point[cd] < root->point[cd]) + return searchRec(root->left, point, depth + 1); + + return searchRec(root->right, point, depth + 1); +} + +// Searches a Point in the K D tree. It mainly uses searchRec() +bool search(Node* root, int point[]) +{ + // Pass current depth as 0 + return searchRec(root, point, 0); +} + +// Program to test above functions +int main() +{ + struct Node *root = NULL; + int points[][k] = {{3, 6}, {17, 15}, {13, 15}, {6, 12}, + {9, 1}, {2, 7}, {10, 19}}; + + int n = sizeof(points)/sizeof(points[0]); + + for (int i=0; i Date: Sat, 27 Oct 2018 20:26:37 +0700 Subject: [PATCH 10/20] add data structure array --- arrays/delete_nth.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 arrays/delete_nth.py diff --git a/arrays/delete_nth.py b/arrays/delete_nth.py new file mode 100644 index 0000000..10e8b30 --- /dev/null +++ b/arrays/delete_nth.py @@ -0,0 +1,38 @@ +""" +Given a list lst and a number N, create a new list +that contains each number of the list at most N times without reordering. +For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], +drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, +which leads to [1,2,3,1,2,3] +""" +import collections + + +# Time complexity O(n^2) +def delete_nth_naive(array, n): + ans = [] + for num in array: + if ans.count(num) < n: + ans.append(num) + return ans + + +# Time Complexity O(n), using hash tables. +def delete_nth(array, n): + result = [] + counts = collections.defaultdict(int) # keep track of occurrences + + for i in array: + + if counts[i] < n: + result.append(i) + counts[i] += 1 + + return result + +a = [1,2,3,1,2,1,2,3] +n = 2 + +print (delete_nth_naive(a, n)) +print (delete_nth(a, n)) + From fd0e48ecbdc65404f4bb03b321d8b528061c6d6f Mon Sep 17 00:00:00 2001 From: Bak-JH Date: Sat, 27 Oct 2018 22:47:04 +0900 Subject: [PATCH 11/20] added quick sort --- sort/quick_sort.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 sort/quick_sort.cpp diff --git a/sort/quick_sort.cpp b/sort/quick_sort.cpp new file mode 100644 index 0000000..5f2391e --- /dev/null +++ b/sort/quick_sort.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +void swap(int& a, int& b) +{ + int temp = a; + a = b; + b = temp; +} + +void quickSort(int arr[], int left, int right) +{ + int i = left, j = right; + int pivot = arr[(left+right)/2]; + + while (i <= j) { + while (arr[i] < pivot) i++; + while (arr[j] > pivot) j--; + + if (i <= j) swap(arr[i++], arr[j--]); + } + + if (left < j) quickSort(arr, left, j); + if (i < right) quickSort(arr, i, right); +} + +int main(){ + int arr[] = {6, 1, 3, 4, 5}; + int n = sizeof(arr) / sizeof(int); + + cout << "Array before sorting :" << endl; + for(int i = 0 ;i < n; ++i){ + cout << arr[i] << " "; + } + cout << endl; + + quickSort(arr, 0, n-1); + cout<<"Array after sorting :"< Date: Sat, 27 Oct 2018 10:58:52 -0400 Subject: [PATCH 12/20] Fixed some spelling errors and reorganized the html --- CONTRIBUTING.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 82c40e1..2c09937 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,5 @@
    -
  • Algorithms can br from any field(ML etc) and any language
  • -
  • - Add Comments. Your code should be self documented -
  • -
  • Use relivant names
  • -
+
  • Algorithms can be from any field (ML etc) and language
  • +
  • Add Comments. Your code should be self documented
  • +
  • Use relevant names
  • + From ee380c87ec15ff9f42228853fcafd64acdecb1ea Mon Sep 17 00:00:00 2001 From: KVVaisakh <36007302+KVVaisakh@users.noreply.github.com> Date: Sat, 27 Oct 2018 23:03:21 +0530 Subject: [PATCH 13/20] queue queue in c --- queue.c | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 queue.c diff --git a/queue.c b/queue.c new file mode 100644 index 0000000..70184f4 --- /dev/null +++ b/queue.c @@ -0,0 +1,72 @@ +#include +#include +#include + +// A structure to represent a queue +struct Queue +{ + int front, rear, size; + unsigned capacity; + int* array; +}; + +// function to create a queue of given capacity. +// It initializes size of queue as 0 +struct Queue* createQueue(unsigned capacity) +{ + struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue)); + queue->capacity = capacity; + queue->front = queue->size = 0; + queue->rear = capacity - 1; // This is important, see the enqueue + queue->array = (int*) malloc(queue->capacity * sizeof(int)); + return queue; +} + +// Queue is full when size becomes equal to the capacity +int isFull(struct Queue* queue) +{ return (queue->size == queue->capacity); } + +// Queue is empty when size is 0 +int isEmpty(struct Queue* queue) +{ return (queue->size == 0); } + +// Function to add an item to the queue. +// It changes rear and size +void enqueue(struct Queue* queue, int item) +{ + if (isFull(queue)) + return; + queue->rear = (queue->rear + 1)%queue->capacity; + queue->array[queue->rear] = item; + queue->size = queue->size + 1; + printf("%d enqueued to queue\n", item); +} + +// Function to remove an item from queue. +// It changes front and size +int dequeue(struct Queue* queue) +{ + if (isEmpty(queue)) + return INT_MIN; + int item = queue->array[queue->front]; + queue->front = (queue->front + 1)%queue->capacity; + queue->size = queue->size - 1; + return item; +} + +// Function to get front of queue +int front(struct Queue* queue) +{ + if (isEmpty(queue)) + return INT_MIN; + return queue->array[queue->front]; +} + +// Function to get rear of queue +int rear(struct Queue* queue) +{ + if (isEmpty(queue)) + return INT_MIN; + return queue->array[queue->rear]; +} + From 687037d1dcee8b8001b1ca3a6ce91a9851961111 Mon Sep 17 00:00:00 2001 From: Avan Date: Sun, 28 Oct 2018 01:48:01 +0530 Subject: [PATCH 14/20] Create Segment_tree(without_recursion).cpp Time Complexities: Tree Construction : O( n ) Query in Range : O( Log n ) Updating an element : O( Log n ) --- Segment_tree(without_recursion).cpp | 84 +++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Segment_tree(without_recursion).cpp diff --git a/Segment_tree(without_recursion).cpp b/Segment_tree(without_recursion).cpp new file mode 100644 index 0000000..0924dc7 --- /dev/null +++ b/Segment_tree(without_recursion).cpp @@ -0,0 +1,84 @@ +/*Segment Trees without recursion + +Finds the sum of elements from index l to r where 0 <= l <= r <= n-1 +Changes value of a specified element of the array to a new given value. We need to update arr[i] = x where 0 <= i <= n-1. +*/ + +#include +#define ll int +using namespace std; + +const ll N = 1000005; + +ll n; + + +ll seg_tree[2 * N]; + + +void _build( ll arr[]) +{ + + for (ll i=0; i 0; --i) + seg_tree[i] = seg_tree[i<<1] + seg_tree[i<<1 | 1]; +} + + +void update_tree_node(ll p, ll value) +{ + + seg_tree[p+n] = value; + p = p+n; + + for (ll i=p; i > 1; i >>= 1) + seg_tree[i>>1] = seg_tree[i] + seg_tree[i^1]; +} + + +ll query(ll l, ll r) +{ + ll ans = 0; + + for (l += n, r += n; l < r; l >>= 1, r >>= 1) + { + if (l&1) + ans += seg_tree[l++]; + + if (r&1) + ans += seg_tree[--r]; + } + + return ans; +} + + +int main() +{ + cin>>n; + ll a[n]; + for(ll i=0;i>a[i]; + _build(a); + ll Q; + cin>>Q; + while(Q--) + { + ll l,r,x,ind,val; + cin>>x; + if(x==2) + { + + cin>>l>>r; + cout << query(l, r)<>ind>>val; + update_tree_node(ind, val); + } + } + return 0; +} From 2496b23463d718a236bef89f23f8e777d515bccf Mon Sep 17 00:00:00 2001 From: Avan Date: Sun, 28 Oct 2018 02:03:38 +0530 Subject: [PATCH 15/20] Create Fenwick_tree(Binary_indexed_tree).cpp Space Complexity: O(N) Time Complexity: O(logN) (for update and query) --- Fenwick_tree(Binary_indexed_tree).cpp | 32 +++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Fenwick_tree(Binary_indexed_tree).cpp diff --git a/Fenwick_tree(Binary_indexed_tree).cpp b/Fenwick_tree(Binary_indexed_tree).cpp new file mode 100644 index 0000000..0be0fbb --- /dev/null +++ b/Fenwick_tree(Binary_indexed_tree).cpp @@ -0,0 +1,32 @@ +#include +#define ll long long int +using namespace std; + +ll Fen_tree[100005], a[100005], n; +void updt(ll x, ll val) +{ + for(; x <= n; x += x&-x) + Fen_tree[x] += val; +} +ll query(ll val) +{ + ll sum = 0; + for(; val > 0; val -= val&-val) + sum += Fen_tree[val]; + return sum; +} + +int main() +{ + cin>>n; + ll i,x,l,r; + for(i = 1; i <= n; i++) + { + cin>>a[i]; + updt(i, a[i]); + } + cin>>x>>l>>r; + cout<<"Sum of first "< Date: Mon, 29 Oct 2018 18:29:42 +0900 Subject: [PATCH 16/20] Added list data structure --- List.cpp | 109 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 List.cpp diff --git a/List.cpp b/List.cpp new file mode 100644 index 0000000..89a1d45 --- /dev/null +++ b/List.cpp @@ -0,0 +1,109 @@ +#include + +template < typename T > +class Node +{ +public: + T data; + Node* next; + + Node (T data) { this->data = data; } + Node(){} +}; + +template < typename T > +class List +{ +public: + int count; + Node* head = new Node; + + List (); + + void add (T data); + void remove (int index); + int size () { return this->count; } + void print (); +}; + +template +List::List () +{ + this->count = 0; + this->head->next = nullptr; + this->head->next = nullptr; +} + +template < typename T > +void List::add (T data) +{ + Node* newNode = new Node(data); + newNode->next = nullptr; + + if (head->next == nullptr) { head->next = newNode; } + else { + Node* temp = head; + while (temp->next != nullptr) + temp = temp->next; + temp->next = newNode; + } + + ++List::count; +} + +template +void List::remove (int index) +{ + Node* temp = head; + Node* target = head; + + if(count < index) { std::cout << "out of index!" << std::endl; return; } + + for (int i = 0; i < index; ++i) { + temp = temp->next; + target = target->next; + } + target = target->next; + + temp->next = target->next; + target->next = nullptr; + delete target; + --List::count; +} + +template +void List::print () +{ + Node* iterator; + iterator = head; + + while(iterator->next != nullptr) { + iterator = iterator->next; + std::cout << iterator->data << " "; + } + std::cout << std::endl; +} + +int main () +{ + // These codes are test + List test; + test.add ('A'); + test.print (); + + test.add ('B'); + test.print (); + + test.add ('C'); + test.print (); + + test.remove(5); + test.print(); + + test.remove(1); + test.print(); + + return 0; +} + + From d22dd93bdf5fd884cf031d46ad20e693ffe2578c Mon Sep 17 00:00:00 2001 From: SakritiDixit Date: Tue, 30 Oct 2018 21:43:37 +0530 Subject: [PATCH 17/20] Data Structures added C++ codes on data structures like linked list, stacks and queues, priority queues, generic trees, binary trees, BSTs, graphs, DP, and tries are added --- ds/BST/bst1.h | 141 ++++++++ ds/BST/bst2.h | 294 ++++++++++++++++ ds/BinaryTrees/binarytree.h | 522 ++++++++++++++++++++++++++++ ds/DP/allways.cpp | 25 ++ ds/DP/coin_tower.cpp | 41 +++ ds/DP/count1ton.cpp | 88 +++++ ds/DP/denomination.cpp | 151 ++++++++ ds/DP/editDistance.cpp | 180 ++++++++++ ds/DP/knapsack.cpp | 112 ++++++ ds/DP/lcs.cpp | 130 +++++++ ds/DP/loot.cpp | 38 ++ ds/DP/matrix_multiplication.cpp | 60 ++++ ds/DP/mincost.cpp | 176 ++++++++++ ds/DP/mincount.cpp | 94 +++++ ds/GenericTrees/treefunctions.h | 310 +++++++++++++++++ ds/GenericTrees/treenode.h | 21 ++ ds/Graphs/graph.h | 286 +++++++++++++++ ds/LinkedList/bubblesortll.cpp | 67 ++++ ds/LinkedList/llmergesort.cpp | 80 +++++ ds/LinkedList/node.cpp | 353 +++++++++++++++++++ ds/LinkedList/swap.cpp | 79 +++++ ds/Priority Queues/minheap.h | 216 ++++++++++++ ds/Stack and Queue/queuearr.h | 87 +++++ ds/Stack and Queue/queuell.h | 71 ++++ ds/Stack and Queue/reversestack.cpp | 78 +++++ ds/Stack and Queue/stackarr.h | 64 ++++ ds/Stack and Queue/stackll.h | 66 ++++ ds/Tries and Huffman Codes/trie.cpp | 108 ++++++ 28 files changed, 3938 insertions(+) create mode 100644 ds/BST/bst1.h create mode 100644 ds/BST/bst2.h create mode 100644 ds/BinaryTrees/binarytree.h create mode 100644 ds/DP/allways.cpp create mode 100644 ds/DP/coin_tower.cpp create mode 100644 ds/DP/count1ton.cpp create mode 100644 ds/DP/denomination.cpp create mode 100644 ds/DP/editDistance.cpp create mode 100644 ds/DP/knapsack.cpp create mode 100644 ds/DP/lcs.cpp create mode 100644 ds/DP/loot.cpp create mode 100644 ds/DP/matrix_multiplication.cpp create mode 100644 ds/DP/mincost.cpp create mode 100644 ds/DP/mincount.cpp create mode 100644 ds/GenericTrees/treefunctions.h create mode 100644 ds/GenericTrees/treenode.h create mode 100644 ds/Graphs/graph.h create mode 100644 ds/LinkedList/bubblesortll.cpp create mode 100644 ds/LinkedList/llmergesort.cpp create mode 100644 ds/LinkedList/node.cpp create mode 100644 ds/LinkedList/swap.cpp create mode 100644 ds/Priority Queues/minheap.h create mode 100644 ds/Stack and Queue/queuearr.h create mode 100644 ds/Stack and Queue/queuell.h create mode 100644 ds/Stack and Queue/reversestack.cpp create mode 100644 ds/Stack and Queue/stackarr.h create mode 100644 ds/Stack and Queue/stackll.h create mode 100644 ds/Tries and Huffman Codes/trie.cpp diff --git a/ds/BST/bst1.h b/ds/BST/bst1.h new file mode 100644 index 0000000..5c89220 --- /dev/null +++ b/ds/BST/bst1.h @@ -0,0 +1,141 @@ +using namespace std; +template +class BinaryTreeNode { +public: + T data; + BinaryTreeNode *left; + BinaryTreeNode *right; + + BinaryTreeNode(T data) { + this->data = data; + this->left = NULL; + this->right = NULL; + } +}; + +class BST +{ + BinaryTreeNode* root; + bool searchutil(int k, BinaryTreeNode* node) + { + if(node==NULL) + return false; + if(node->data==k) + return true; + else if(node->data>k) + return searchutil(k,node->left); + else + return searchutil(k,node->right); + + } + + BinaryTreeNode* insertUtil(int k,BinaryTreeNode* node) + { + if(node==NULL) + { + BinaryTreeNode* newnode=new BinaryTreeNode(k); + return newnode; + } + if(node->data>k) + node->left=insertUtil(k,node->left); + else + node->right=insertUtil(k,node->right); + return node; + + } + + BinaryTreeNode* deleteitemUtil(int k,BinaryTreeNode* node) + { + if(node==NULL) + { + return NULL; + } + if(node->data>k) + node->left=deleteitemUtil(k,node->left); + else if(node->dataright=deleteitemUtil(k,node->right); + + + else + { + + if(node->left!=NULL&&node->right!=NULL) + { + BinaryTreeNode* current; + current=node->right; + while(current->left!=NULL) + { + current=current->left; + } + node->data=current->data; + node->right=deleteitemUtil(current->data,node->right); + return node; + } + else if(node->left!=NULL) + { + return node->left; + + } + + else if(node->right!=NULL) + { + return node->right; + } + + else + return NULL; + } + + } + + void print(BinaryTreeNode* root1) { + if(root1==NULL) + return; + + cout<data<<":"; + if(root1->left!=NULL) + cout<<"L:"<left->data<<","; + if(root1->right!=NULL) + cout<<"R:"<right->data; + cout<left); + print(root1->right); + + + } + + + +public: + BST() + { + root=NULL; + } + ~BST() + { + delete root; + } + + void insert(int k) + { + + root= insertUtil(k,root); + } + + void deleteData(int k) + { + root= deleteitemUtil(k,root); + } + + void printTree() + { + print(root); + } + + bool hasData(int k) + { + return searchutil(k,root); + } +}; + + diff --git a/ds/BST/bst2.h b/ds/BST/bst2.h new file mode 100644 index 0000000..4c380e7 --- /dev/null +++ b/ds/BST/bst2.h @@ -0,0 +1,294 @@ +#include +#include +#include +#include + +using namespace std; +template +class BinaryTreeNode { + public : + T data; + BinaryTreeNode *left; + BinaryTreeNode *right; + + BinaryTreeNode(T data) { + this -> data = data; + left = NULL; + right = NULL; + } +}; + +class trio +{ + public: + int min; + int max; + bool boolval; +}; + +//To search for a node in a BST +BinaryTreeNode* searchInBST(BinaryTreeNode *root , int k){ + + if(root==NULL) + return NULL; + if(root->data==k) + return root; + else if(root->data>k) + return searchInBST(root->left,k); + else + return searchInBST(root->right,k); +} + +//To find the elements in range from K1 to K2 +void elementsInRangeK1K2(BinaryTreeNode* root, int k1, int k2) { + + if(root==NULL) + return; + if(root->data>k2) + { + elementsInRangeK1K2(root->left,k1,k2); + return; + } + if(root->dataright,k1,k2); + return; + } + + elementsInRangeK1K2(root->left,k1,k2); + cout<data<<" "; + elementsInRangeK1K2(root->right,k1,k2); + + +} + +//To check if a binary tree in BST or not +trio isBSTutil(BinaryTreeNode *root) +{ + if(root==NULL) + { + trio t; + t.min=INT_MAX; + t.max=INT_MIN; + t.boolval=true; + return t; + } + + trio t; + trio t1=isBSTutil(root->left); + trio t2=isBSTutil(root->right); + + if(t1.boolval&&t2.boolval) + { + if(t1.maxdata&&t2.min>root->data) + t.boolval=true; + else t.boolval=false; + } + else t.boolval=false; + t.min=min(root->data,min(t1.min,t2.min)); + t.max=max(root->data,max(t1.max,t2.max)); + return t; +} + +//To construct a BSt from a given array +BinaryTreeNode* constructTree(int *input, int n) { + if(n==0) + return NULL; + int mid=(n-1)/2; + BinaryTreeNode* root=new BinaryTreeNode(input[mid]); + root->left=constructTree(input,mid); + root->right=constructTree(input+mid+1,n-mid-1); + return root; + +} + +//To find the path of a node in the tree from the node to the root +//Returns a vector containing the nodes in the path +vector path(BinaryTreeNode* root,int k) +{ + if(root==NULL) + { + vector v; + return v; + } + if(root->data==k) + { + vector v; + v.push_back(root->data); + return v; + } + + else if(root->data>k) + { + vector v1=path(root->left,k); + v1.push_back(root->data); + return v1; + } + + else if(root->data v2=path(root->right,k); + v2.push_back(root->data); + return v2; + } +} + +//To print the tree in levelwise order +void printLevelWise(BinaryTreeNode* root) { + queue*> q; + + if(root!=NULL) + { + //cout<data<* k=q.front(); + q.pop(); + + cout<data<<":"; + cout<<"L:"; + + if(k->left!=NULL) + { + q.push(k->left); + cout<left->data<<" "; + } + else cout<<"-1"; + cout<<", R:"; + if(k->right!=NULL) + { + q.push(k->right); + + cout<right->data<<" "; + } + else cout<<"-1"; + +cout< *root, int*a) +{ + if(root==NULL) + return;//-1; + inorder(root->left,a); + + a[k1++]=root->data; + + inorder(root->right,a); + + +} + +//TO FIND THE NODES WHICH SUM UP TO K IN A BST +#include +void nodesSumToS(BinaryTreeNode *root, int sum) +{ + int* a=new int[1000]; + inorder2(root,a); + + int i=0,j=k1-1; + while(isum) + j--; + if(sum2==sum) + { + cout<* root , int val1 , int val2){ + + if(root==NULL) + return -1; + if(root->data==val1) + return val1; + if(root->data==val2) + return val2; + int l=lcaInBST(root->left,val1,val2); + int r=lcaInBST(root->right,val1,val2); + + if(l==-1) + return r; + else if(r==-1) + return l; + else + { + return root->data; + } + +} + +//To find the sum of nodes from root to leaf +void rootToLeafPathsSumToK(BinaryTreeNode *root, int k, string s="") +{ + + if(root==NULL) + return; + if(root->left==NULL&&root->right==NULL) + { + if(k==root->data) + { + + cout<data); + cout<left,k-root->data,s+to_string(root->data)+" "); + + rootToLeafPathsSumToK(root->right,k-root->data,s+to_string(root->data)+" "); + +} + +//To make a BSt into sorted linked list +pair*, Node*> BSTll(BinaryTreeNode* root) +{ + if(root==NULL) + { + pair*,Node*> p; + p.first=NULL; + p.second=NULL; + return p; + } + pair*,Node*> p1=BSTll(root->left); + pair*,Node*> p2=BSTll(root->right); + pair*,Node*> p; + + Node* newnode= new Node(root->data); + if(p1.first==NULL) + p.first=newnode; + else + p.first=p1.first; + + if(p1.second!=NULL) + p1.second->next=newnode; + newnode->next=p2.first; + + if(p2.second==NULL) + p.second=newnode; + else + p.second=p2.second; + + return p; +} + +Node* constructBSTLL(BinaryTreeNode* root) { + + return BSTll(root).first; + +} \ No newline at end of file diff --git a/ds/BinaryTrees/binarytree.h b/ds/BinaryTrees/binarytree.h new file mode 100644 index 0000000..d79115c --- /dev/null +++ b/ds/BinaryTrees/binarytree.h @@ -0,0 +1,522 @@ +#include +#include +#include +#include +#include +#include + + +using namespace std; + +/* + +Functions Performed: +1. To input the tree +2. To print the tree in a levelwise order +3. To count number of nodes +4. To remove leaf nodes +5. To check if a node is present in the tree +6. To check the height of the tree +7. To form the mirror image of the binary tree +8. To build a tree from the Preorder and Inorder +9. To build a tree from the Postorder and Inorder +10. To find the diameter of the tree +11. To check if the tree is height balanced or not +12. To check the depth of a node from the root of the tree +13. To print each level on a new line +14. To print the tree in a zigzag fashion +15. To construct a tree from an array +15. To find the path of a node from node to root +16. To find Least Common Ancestor of two nodes in the binary tree + +*/ +template +class BinaryTreeNode { + public : + T data; + BinaryTreeNode *left; + BinaryTreeNode *right; + + BinaryTreeNode(T data) { + this -> data = data; + left = NULL; + right = NULL; + } +}; + +class pairs +{ +public: + int height; + int diameter; +}; + + +//To take input in a levelwise order +//Enter 0 to stop +BinaryTreeNode* takeinput() +{ + int rootdata; + cout<<"Enter root data:"<>rootdata; + BinaryTreeNode* root=new BinaryTreeNode(rootdata); + int ch; + queue*> q; + q.push(root); + while(!q.empty()) + { + BinaryTreeNode* k=q.front(); + q.pop(); + cout<<"Enter the number of childrenren of node:"<data<>l; + if(l!=0) + { + BinaryTreeNode* leftnode=new BinaryTreeNode(l); + k->left=leftnode; + q.push(leftnode); + } + + + int r; + cin>>r; + if(r!=0) + { + BinaryTreeNode* rightnode=new BinaryTreeNode(r); + k->right=rightnode; + q.push(rightnode); + } + } + + return root; +} + +//To print in a levelwise order +void printLevelWise(BinaryTreeNode* root) { + queue*> q; + + if(root!=NULL) + { + q.push(root); + } + while(!q.empty()) + { + BinaryTreeNode* k=q.front(); + q.pop(); + + cout<data<<":"; + cout<<"L:"; + + if(k->left!=NULL) + { + q.push(k->left); + cout<left->data<<" "; + } + else cout<<"-1"; + cout<<", R:"; + if(k->right!=NULL) + { + q.push(k->right); + + cout<right->data<<" "; + } + else cout<<"-1"; + +cout< *root) +{ + if(root==NULL) + return 0; + return 1+countNodes(root->left)+countNodes(root->right); + +} + +//To remove leaf nodes from the binary tree +BinaryTreeNode* removeLeafNodes(BinaryTreeNode *root,BinaryTreeNode * parent=NULL) { + + if(root->left==NULL&&root->right==NULL) + { + if(parent!=NULL) + { + if(parent->left==root) + parent->left=NULL; + if(parent->right==root) + parent->right=NULL; + } + return parent; + } + if(parent!=NULL) + cout<data<<" "; + cout<data<left!=NULL) + root=removeLeafNodes(root->left,root); + if(root->right!=NULL) + root=removeLeafNodes(root->right,root); + + if(parent!=NULL) + return parent; +else + return root; + + +} + +//To check if an integer is present as a node in the tree +bool isNodePresent(BinaryTreeNode* root, int x) { + + if(root==NULL) + return false; + + if(root->data==x) + return true; + bool ch1=isNodePresent(root->left,x); + bool ch2=isNodePresent(root->right,x); + return ch1||ch2; + +} + +int height(BinaryTreeNode *root) { + + if(root==NULL) + return 0; + int k1=height(root->left); + int k2=height(root->right); + + return 1+std::max(k1,k2); + +} + +//To form a mirror image of a binary tree +void mirrorBinaryTree(BinaryTreeNode* root) { + + if(root==NULL) + return; + + BinaryTreeNode* temp=root->right; + root->right=root->left; + root->left=temp; + + mirrorBinaryTree(root->left); + mirrorBinaryTree(root->right); + +} + +//To form a binary tree from preorder and inorder +BinaryTreeNode* getTreeFromPreorderAndInorder(int *preorder, int ps, int pe, int *inorder, int is, int ie) { + + + int l=ie; + int rootdata=preorder[ps]; + BinaryTreeNode* root=new BinaryTreeNode(rootdata); + //LEFT SUBTREE + ps=ps+1; + int count=-1; + for(int i=is;ileft=NULL; + else if(ie==is) + { + BinaryTreeNode* lchild=new BinaryTreeNode(inorder[ie]); + root->left=lchild; + } + else + { + root->left=getTreeFromPreorderAndInorder(preorder,ps,pe,inorder,is,ie); + } + + //RIGHT SUBTREE + is=ie+2; + ps=pe+1; + ie=l; + pe=ie-is+ps; + if(ieright=NULL; + else if(ie==is) + { + BinaryTreeNode* rchild=new BinaryTreeNode(inorder[ie]); + root->right=rchild; + } + else + { + root->right=getTreeFromPreorderAndInorder(preorder,ps,pe,inorder,is,ie); + } + + return root; + +} + +//To form a binary tree from postorder and inorder +BinaryTreeNode* getTreeFromPostorderAndInorder(int *postorder, int ps, int pe, int *inorder, int is, int ie) +{ + + int iel=ie; + int pel=pe; + int rootdata=postorder[pe]; + BinaryTreeNode* root=new BinaryTreeNode(rootdata); + //LEFT SUBTREE + int count=-1; + for(int i=is;ileft=NULL; + else if(ie==is) + { + BinaryTreeNode* lchild=new BinaryTreeNode(inorder[ie]); + root->left=lchild; + } + else + { + root->left=getTreeFromPostorderAndInorder(postorder,ps,pe,inorder,is,ie); + } + + //RIGHT SUBTREE + is=ie+2; + ps=pe+1; + ie=iel; + pe=pel-1; + if(ieright=NULL; + else if(ie==is) + { + BinaryTreeNode* rchild=new BinaryTreeNode(inorder[ie]); + root->right=rchild; + } + else + { + root->right=getTreeFromPostorderAndInorder(postorder,ps,pe,inorder,is,ie); + } + + return root; + + +} + +//To find the diameter of a binary tree +//order of n complexity. better that o(n^2) for normal method +pairs diameter(BinaryTreeNode* root) +{ + if(root==NULL) + { + pairs p; + p.height=0; + p.diameter=0; + return p; + } + + pairs h2=diameter(root->left); + pairs h3=diameter(root->right); + pairs h1; + h1.height= max(h2.height,h3.height)+1; + int h = h2.height + h3.height; + h1.diameter= max(h,max(h2.diameter,h3.diameter)); + + return h1; +} + +//Helper function to check if a binary tree isheight balanced or not +//order of n complexity. better that o(n^2) for normal method +pair balanced(BinaryTreeNode *root) +{ + if(root==NULL) + { + pair p; + p.first=true; + p.second=0; + return p; + } + + pair p1; + pair p2=balanced(root->left); + pair p3=balanced(root->right); + + p1.second = 1+max(p2.second,p3.second); + if(p3.first&&p2.first) + { + if(abs(p2.second-p3.second)>1) + p1.first=false; + else + p1.first=true; + } + else + p1.first=false; + return p1; +} + +bool isBalanced(BinaryTreeNode *root) +{ + return balanced(root).first; + +} + +//To find depth of a node from the root of the tree +int depth(BinaryTreeNode *root,BinaryTreeNode *node,int i=0) { + if(root==NULL) + return -1; + if(root->data==node->data) + return i; + int ans=depth(root->left,node,i+1); + if(ans==-1) + { + depth(root->right,node,i+1); + } +} + +//To print a tree such that each level is at new line. +void printLevelATNewLine1(BinaryTreeNode *root) { + + queue*> q; + if(root!=NULL) + { + q.push(root); + q.push(NULL); + } + while(!q.empty()) + { + BinaryTreeNode * k=q.front(); + q.pop(); + if(k==NULL) + { + cout<data<<" "; + if(k->left!=NULL) + q.push(k->left); + + if(k->right!=NULL) + q.push(k->right); + } + } +} + +//To print a tree in a zigzag order +//using 2 stacks +void zigZagOrder1(BinaryTreeNode *root) { + + stack*> s1,s2; + s1.push(root); + BinaryTreeNode* k=s1.top(); + while(!s1.empty()||!s2.empty()) + { + while(!s1.empty()) + { + BinaryTreeNode* k=s1.top(); + s1.pop(); + cout<data<<" "; + if(k->left!=NULL) + s2.push(k->left); + if(k->right!=NULL) + s2.push(k->right); + if(s1.empty()) + cout<* k=s2.top(); + s2.pop(); + cout<data<<" "; + if(k->right!=NULL) + s1.push(k->right); + if(k->left!=NULL) + s1.push(k->left); + if(s2.empty()) + cout<* constructTree(int *input, int n) { + if(n==0) + return NULL; + int mid=(n-1)/2; + BinaryTreeNode* root=new BinaryTreeNode(input[mid]); + root->left=constructTree(input,mid); + root->right=constructTree(input+mid+1,n-mid-1); + return root; + +} + + +//To find the path of a node in the tree from the node to the root +//Returns a vector containing the nodes in the path +vector path(BinaryTreeNode* root,int k) +{ + if(root==NULL) + { + vector v; + return v; + } + if(root->data==k) + { + vector v; + v.push_back(root->data); + return v; + } + vector v1=path(root->left,k); + if(v1.size()!=0) + { + v1.push_back(root->data); + return v1; + } + else + { + vector v2=path(root->right,k); + if(v2.size()!=0) + { + v2.push_back(root->data); + return v2; + } + else + return v2; + } +} + +//To find Least Common Ancestor of two nodes in the binary tree +int lcaBinaryTree(BinaryTreeNode * root , int val1, int val2) +{ + if(root==NULL) + return -1; + if(root->data==val1) + return val1; + if(root->data==val2) + return val2; + int l=lcaBinaryTree(root->left,val1,val2); + int r=lcaBinaryTree(root->right,val1,val2); + + if(l==-1) + return r; + else if(r==-1) + return l; + else + { + return root->data; + } + +} \ No newline at end of file diff --git a/ds/DP/allways.cpp b/ds/DP/allways.cpp new file mode 100644 index 0000000..c2dd276 --- /dev/null +++ b/ds/DP/allways.cpp @@ -0,0 +1,25 @@ +#include +#include + + +//RECURSIVE +int allWays(int x, int n, int z=1) { + + if(x==0) + return 1; + + if(pow(z,n)>x) + return 0; + int count=0; + for(int i=z;pow(i,n)<=x;i++) + { + count+=allWays(x-pow(i,n),n,i+1); + } + return count; +} + +//DP +int allWays_DP(int x, int n, int z=1) { + + +} diff --git a/ds/DP/coin_tower.cpp b/ds/DP/coin_tower.cpp new file mode 100644 index 0000000..e9b9847 --- /dev/null +++ b/ds/DP/coin_tower.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; + +//SEEMS WRONG BUT ONE TEST CASE WORKS OTHERS, TLE +string solve(int n, int x, int y, string s="Beerus") +{ + // Write your code here . + if(n<=0) + return s; + + if(s.compare("Beerus")==0) + s="Whis"; + else + s="Beerus"; + + int b=0,w=0; + string s1=solve(n-1,x,y,s); + if(s1.compare("Beerus")==0) + b++; + else + w++; + + string s2=solve(n-x,x,y,s); + if(s2.compare("Beerus")==0) + b++; + else + w++; + + string s3=solve(n-y,x,y,s); + if(s3.compare("Beerus")==0) + b++; + else + w++; + //cout<w) + return "Whis"; + else + return "Beerus"; + +} + diff --git a/ds/DP/count1ton.cpp b/ds/DP/count1ton.cpp new file mode 100644 index 0000000..b176775 --- /dev/null +++ b/ds/DP/count1ton.cpp @@ -0,0 +1,88 @@ +#include +#include +using namespace std; + +//NAIVE RECURSIVE APPROACH O(2^N) +int countStepsTo1RECURSIVE(int n,int count=0){ + if(n==1) + return 0; + int k1=INT_MAX,k2=INT_MAX,k3=INT_MAX; + k1=1+countStepsTo1RECURSIVE(n-1); + + if(n%2==0) + k2=1+countStepsTo1RECURSIVE(n/2); + + if(n%3==0) + k3=1+countStepsTo1RECURSIVE(n/3); + + return min(k1,min(k2,k3)); + +} + +//MEMOIZATION APPROACH O(N) +int countStepsTo1memoization(int n,int* ans){ + if(n==1) + return 0; + if(n==2) + return 1; + if(n==3) + return 1; + int k1=INT_MAX,k2=INT_MAX,k3=INT_MAX; + + if(ans[n-1]!=-1) + k1=ans[n-1]; + else k1=countStepsTo1memoization(n-1,ans); + + if(n%2==0) + if(ans[n/2]!=-1) + k2=ans[n/2]; + else k2=countStepsTo1memoization(n/2,ans); + + if(n%3==0) + if(ans[n/3]!=-1) + k3=ans[n/3]; + else k3=countStepsTo1memoization(n/3,ans); + + return 1+min(k1,min(k2,k3)); + +} + + +int countStepsTo1MEMOIZATION(int n) +{ + int* ans= new int[n+1]; + + for(int i=0;i<=n;i++) + ans[i]=-1; + + return countStepsTo1memoization(n,ans); +} + + +//DYNAMIC PROGRAMMING APPROACH O(N)----BEST APPROACH +int countStepsTo1DP(int n) +{ + int* ans= new int[n+1]; + ans[0]=0; + ans[1]=0; + ans[2]=1; + ans[3]=1; + for(int i=4;i<=n;i++) + { + ans[i]=ans[i-1]; + if(i%2==0) + ans[i]=min(ans[i],ans[i/2]); + if(i%3==0) + ans[i]=min(ans[i],ans[i/3]); + ans[i]=ans[i]+1; + } + return ans[n]; +} + + +int main() +{ + //cout< +using namespace std; + +int countWaysToMakeChange_recursive(int den[], int n, int value){ + + if(n==0) + return 0; + if(value<0) + return 0; + if(value==0) + return 1; + + int count=0; + count=countWaysToMakeChange_recursive(den+1,n-1,value); + count+=countWaysToMakeChange_recursive(den,n,value-den[0]); + return count; + +} + +int countWaysToMakeChange_DP(int den[], int n, int value){ + int** dp = new int*[n+1]; + for(int i=0;i=0) + dp[i][j]+=dp[i][j-den[i-1]]; + } + } +return dp[n][value]; + + +} + + +int main() +{ + int d; + cin>>d; + int * a=new int[d]; + for(int i=0;i>a[i]; + int v; + cin>>v; + cout<=0) + count2+=dp[i-den[j]]; + int rem=i-den[j]; + for(int k=0;k=0) + count2+=dp[rem-den[k]]; + } + //cout<value) + return 0; + int flag=0; + for(int i=0;i=den[j];j++) + { + + int rem=i-den[j]; + dp[i]+=dp[rem]; + if(i==den[j]) + dp[i]++; + cout<=den[k];k++) + { + if(i-den[j]==den[k]&&den[j]!=den[k]) + { + if(flag==0) + { + flag=1; + dp[i]-=min(dp[den[j]],dp[den[k]]); + } + + } + if(den[k]!=den[j]&&den[k]%den[j]==0) + dp[i]-=min(dp[i-den[j]],dp[i-den[k]]); + } + + } + + } + for(int i=0;i +#include +#include +#include +using namespace std; +//EFFICIENT BUT WRONG. +//WE HAVE TO TAKE CARE OF THE SEQUENCE OF THE ELEMENTS IN THE STRING TOO. +//LIKE: ABC AND DCB WILL NOT HAVE 1 STEP BUT MINIMUM 3 STEPS TO BECOME EQUAL. +/* +int editDistance(string s1, string s2){ + + unordered_mapm; + for(int i=0;i0) + m[s2[i]]--; + else + count2++; + } + else + count2++; + } + + unordered_map::iterator it; + for(it=m.begin();it!=m.end();it++) + { + if(it->second!=0) + count1=count1+it->second; + } + + int res= min(count1,count2) + abs(count1-count2); + cout<s2.size()) + return s1.size()-s2.size(); + return s2.size()-s1.size(); + } + if(s1[0]==s2[0]) + return editDistance(s1.substr(1),s2.substr(1)); + + //INSERT S1[0] IN S2[0] + int x=editDistance(s1.substr(1),s2); + + //DELETE S2[0] FROM S2 + int y=editDistance(s1,s2.substr(1)); + + //REPLACE S2[0] FROM S1[0] + int z=editDistance(s1.substr(1),s2.substr(1)); + + return 1+min(x,min(y,z)); +} + +int editDistancememoisation(string s1, string s2, int**dp) +{ + if(s1.size()==0||s2.size()==0) + { + if(s1.size()>s2.size()) + { + dp[s1.size()][s2.size()]=s1.size()-s2.size(); + return s1.size()-s2.size(); + } + + dp[s1.size()][s2.size()]=s2.size()-s1.size(); + return s2.size()-s1.size(); + } + int i=s1.size(); + int j=s2.size(); + + if(dp[i][j]!=-1) + return dp[i][j]; + + if(s1[0]==s2[0]) + { + dp[i][j]=editDistancememoisation(s1.substr(1),s2.substr(1),dp); + return dp[i][j]; + } + + int x=editDistancememoisation(s1.substr(1),s2,dp); + int y=editDistancememoisation(s1,s2.substr(1),dp); + int z=editDistancememoisation(s1.substr(1),s2.substr(1),dp); + + dp[i][j]=1+min(x,min(y,z)); + return dp[i][j]; +} + +int editDistanceMEMOISATION(string s1, string s2) +{ + int**dp=new int*[s1.size()+1]; + + for(int i=0;i>s1>>s2; + cout< +#include +using namespace std; +int knapsack_RECURSIVE(int* weights, int* values, int n, int maxWeight){ + + if(n==0) + return 0; + int item_present; + //IF CURRENT ITEM IS PUT IN KNAPSACK + if(maxWeight-weights[0]>=0) + item_present = values[0] + knapsack(weights+1,values+1,n-1,maxWeight-weights[0]); + else + item_present=INT_MIN; + + + //IF CURRENT ITEM IS NOT PUT IN KNAPSACK + int item_absent = knapsack(weights+1,values+1,n-1,maxWeight); + cout<=weights[i-1]) + { + int x=values[i-1]+dp[i-1][j-weights[i-1]]; + int y=dp[i-1][j]; + dp[i][j]=max(x,y); + } + else + dp[i][j]=dp[i-1][j]; + } + } + return dp[m-1][n-1]; + + + +} diff --git a/ds/DP/lcs.cpp b/ds/DP/lcs.cpp new file mode 100644 index 0000000..69d2696 --- /dev/null +++ b/ds/DP/lcs.cpp @@ -0,0 +1,130 @@ +#include +#include +#include +using namespace std; + +int lcsrecursive(string s,string t) +{ + if(s.size()==0||t.size()==0) + return 0; + + if(s[0]==t[0]) + { + return 1+lcsrecursive(s.substr(1),t.substr(1)); + } + + int x=lcsrecursive(s.substr(1),t); + int y=lcsrecursive(s,t.substr(1)); + + return max(x,y); +} + +int lcsmemoisation(string s,string t,int**dp) +{ + if(s.size()==0||t.size()==0){ + dp[s.size()][t.size()]=0; + return 0; + } + int i=s.size(); + int j=t.size(); + + if(dp[i][j]!=-1) + return dp[i][j]; + + if(s[0]==t[0]) + { + dp[i-1][j-1]=lcsmemoisation(s.substr(1),t.substr(1),dp); + //cout<>s>>t; + cout< +#include +using namespace std; + +int getMaxMoneyDP(int arr[], int n) +{ + int * dp= new int[n+1]; + dp[0]=0; + dp[1]=arr[0]; + + for(int i=2;i<=n;i++) + { + dp[i] = max(arr[i-1]+dp[i-2], dp[i-1]); + } + return dp[n]; +} + +int getMaxMoneymemoisation(int arr[], int n, int* dp) +{ + if(n==0) + return 0; + if(dp[n]!=-1) + return dp[n]; + + int x=getMaxMoneymemoisation(arr+1,n-1,dp); + int y=arr[0] + getMaxMoneymemoisation(arr+2,n-2,dp); + + dp[n]=max(x,y); + return dp[n]; +} + +int getMaxMoneyMEMOISATION(int arr[], int n) +{ + int* dp= new int[n+1]; + for(int i=0;i<=n;i++) + dp[i]=-1; + return getMaxMoneymemoisation(arr,n,dp); +} diff --git a/ds/DP/matrix_multiplication.cpp b/ds/DP/matrix_multiplication.cpp new file mode 100644 index 0000000..b94f5fd --- /dev/null +++ b/ds/DP/matrix_multiplication.cpp @@ -0,0 +1,60 @@ +#include +#include +using namespace std; + +int mcm_DP(int* p,int n) +{ + int** dp=new int*[n]; + for(int i=0;i>n; + int* p= new int[n+1]; + for(int i=0;i>p[i]; + cout< +#include +#include +using namespace std; + +int mincost(int** input,int i,int j,int m,int n) +{ + if(i==m-1&&j==n-1) + return input[m-1][n-1]; + + if(i>=m||j>=n) + return INT_MAX; + + int a=mincost(input,i+1,j,m,n); + int b=mincost(input,i,j+1,m,n); + int c=mincost(input,i+1,j+1,m,n); + + return input[i][j] + min(a,min(b,c)); + +} + +int minCostPath(int **input, int m, int n) { + + return mincost(input,0,0,m,n); + +} + + +int mincostmemoisation___lower(int** input,int** dp,int i,int j,int m,int n) +{ + + if(i==m-1&&j==n-1) + { + dp[i][j]=input[m-1][n-1]; + return input[m-1][n-1]; + } + + if(i>=m||j>=n) + return INT_MAX; + + int x,y,z; + if(i+1=m||j>=n) + return INT_MAX; + + if(dp[i][j]!=-1) + return dp[i][j]; + + + int x,y,z; + x=mincostmemoisation(input,dp,i+1,j,m,n); + y=mincostmemoisation(input,dp,i+1,j+1,m,n); + z=mincostmemoisation(input,dp,i,j+1,m,n); + + int res= input[i][j] + min(x,min(y,z)); + if(i>m>>n; + + int ** input= new int*[m]; + for(int i=0;i>input[i][j]; + } + } + cout< +#include +//DP METHOD. MOST EFFICIENT +int minCountDP(int n){ + + if(n==0) + return 0; + if(n==1) + return 1; + int * ans=new int[n+1]; + ans[0]=0; + ans[1]=1; + for(int i=2;i<=n;i++) + { + int min=INT_MAX; + for(int j=1;j<=sqrt(i);j++) + { + int k=1+ans[i-j*j]; + if(km) + { + min=m; + ans[n]=min;//VERY IMPORTANT STEP. DON'T SAVE EVERY VALUE OF RECURSION AS IT WILL DO THAT ALREADY. JUST SAVE END VALUE. + } + + } + return min; +} + +int minCountMEMOIZATION(int n){ + + int * ans=new int[n+1]; + for(int i=0;i1) + min2=1+minCountRecursive(n-(k-1)*(k-1)); + + return min(min1,min2); +} + + +int main() +{ + cout< +#include "treenode.h" +using namespace std; + +//INPUT FUNCTION +TreeNode* takeinput() +{ + int rootdata; + //cout<<"Enter root data:"<>rootdata; + TreeNode* root=new TreeNode(rootdata); + int ch; + queue*> q; + q.push(root); + while(!q.empty()) + { + TreeNode* k=q.front(); + q.pop(); + //cout<<"Enter the number of childrenren of node:"<data<>ch; + for(int i=0;idata<>children; + TreeNode* ch1=new TreeNode(children); + k->children.push_back(ch1); + q.push(ch1); + } + } + return root; +} + +//PRINT FUNCTION WHICH IS BASIC AND SIMPLE BASICALLY, PREORDER TRAVERSAL +void print(TreeNode* root) +{ + cout<data<<":"; + for(int i=0;ichildren.size();i++) + { + cout<children[i]->data<<","; + } + cout<children.size();i++) + { + print(root->children[i]); + } +} + +//LEVEL ORDER TRAVERSAL +//USES QUEUE FOR LEVEL ORDER TRAVERSAL +void printLevelWise(TreeNode* root) { + queue*> q; + q.push(root); + while(!q.empty()) + { + TreeNode* k=q.front(); + q.pop(); + cout<data<<":"; + for(int i=0;ichildren.size();i++) + { + cout<children[i]->data; + if(i!=k->children.size()-1) + cout<<","; + q.push(k->children[i]); + } + cout<* root) +{ + int k=1; + for(int i=0;ichildren.size();i++) + k=k+countnodes(root->children[i]); + return k; +} + +int sumOfNodes(TreeNode* root) +{ + int k=root->data; + for(int i=0;ichildren.size();i++) + k=k+sumOfNodes(root->children[i]); + return k; +} + +//NODE WITH MAXIMUM DATA +TreeNode* maxDataNode(TreeNode* root) +{ + if(root==NULL) + return NULL; + TreeNode* k=root; + for(int i=0;ichildren.size();i++) + { + TreeNode* m=maxDataNode(root->children[i]); + if(m->data>k->data) + k=m; + } + return k; +} + +//HEIGHT CAN BE FROM 0 INDEXING OR 1 INDEXING +//FOR 1 INDEXING, NULL=0 INDEX +int height(TreeNode* root) +{ + int m=0; + for(int i=0;ichildren.size();i++) + { + int k=height(root->children[i]); + if(k>m) + m=k; + } + return 1+m; +} + +//DEPTH IS THE DISTANCE OF THE NODE FROM ROOT +//ROOT FROM ROOT HAS 0 DEPTH +void depth(TreeNode* root,int k) +{ + if(k==0) + { + cout<data<<" "; + return; + } + + for(int i=0;ichildren.size();i++) + { + depth(root->children[i],k-1); + } +} + +//NUMBER OF LEAF NODES +int numLeafNodes(TreeNode* root) +{ + if(root->children.size()==0) + return 1; + int k=0; + for(int i=0;ichildren.size();i++) + k=k+numLeafNodes(root->children[i]); + return k; +} + +//TYPES OF TRAVERSALS +void preOrder(TreeNode* root) { + if(root==NULL) + return; + cout<data<<" "; + for(int i=0;ichildren.size();i++) + preOrder(root->children[i]); + + +} + +//POST ORDER TRAVERSAL IS USED FOR DEALLOCATING THE TREE +void postOrder(TreeNode* root) { + if(root==NULL) + return; + for(int i=0;ichildren.size();i++) + postOrder(root->children[i]); + cout<data<<" "; + +} + +bool containsX(TreeNode* root, int x) +{ + if(x==root->data) + return true; + + for(int i=0;ichildren.size();i++) + { + bool ans=containsX(root->children[i],x); + if(ans==true) + return ans; + } + return false; + +} + +int nodesGreaterThanX(TreeNode *root, int x) +{ + int a; + if(xdata) + a=1; + else + a=0; + for(int i=0;ichildren.size();i++) + { + a=a+nodesGreaterThanX(root->children[i],x); + } + return a; +} + +#include +pair*,int> maxSum(TreeNode *root) +{ + int sum=root->data; + for(int i=0;ichildren.size();i++) + sum=sum+root->children[i]->data; + TreeNode* k=root; + for(int i=0;ichildren.size();i++) + { + pair*,int> m=maxSum(root->children[i]); + int sum2=m.second; + if(sum2>sum) + { + k=m.first; + sum=sum2; + } + } + pair*, int> p(k,sum); + return p; + +} + +TreeNode* maxSumNode(TreeNode *root) +{ + pair*,int> q=maxSum(root); + return q.first; + +} + + +bool isIdentical(TreeNode *root1, TreeNode * root2) +{ + if(root1->data!=root2->data) + return false; + else if(root1->children.size()!=root2->children.size()) + return false; + else + { + for(int i=0;ichildren.size();i++) + { + bool k=isIdentical(root1->children[i],root2->children[i]); + if(k==false) + return false; + } + return true; + } +} + +#include +TreeNode* nextLargerElement(TreeNode* root, int n) +{ + int k=INT_MAX; + TreeNode* ni; + if(root->data>n) + { + k=root->data; + ni=root; + } + else ni=NULL; + + for(int i=0;ichildren.size();i++) + { + TreeNode* t=nextLargerElement(root->children[i],n); + if(t!=NULL) + if(k>t->data) + { + ni=t; + k=t->data; + } + } + return ni; + +} + +TreeNode* replace(TreeNode* root, int x) +{ + if(x==root->data) + root->data=INT_MIN; + + for(int i=0;ichildren.size();i++) + { + root->children[i]=replace(root->children[i],x); + } + return root; +} + + + +TreeNode * secondLargest(TreeNode *root) +{ + if(root->children.size()==0) + return NULL; + TreeNode* l=maxDataNode(root); + cout<data<data; + l->data=INT_MIN; + TreeNode* s=maxDataNode(root); + cout<data<data=k; + if(s->data==l->data) + { + //print(root); + root=replace(root,s->data); + //print(root); + s=maxDataNode(root); + if(s->data==INT_MIN) + return NULL; + else + return s; + } + + else + return s; +} + diff --git a/ds/GenericTrees/treenode.h b/ds/GenericTrees/treenode.h new file mode 100644 index 0000000..635e4ee --- /dev/null +++ b/ds/GenericTrees/treenode.h @@ -0,0 +1,21 @@ +#include +#include +#include +using namespace std; + +template +class TreeNode{ +public: + T data; + vectorchildren; + TreeNode(T d) + { + data=d; + } + ~TreeNode() + { + for(int i=0;i +using namespace std; + +class graph +{ + int n; + int e; + int** g; +public: + graph(int n,int e) + { + this->n=n; + this->e=e; + g=new int* [n]; + for(int i=0;i>s>>d; + g[s][d]=1; + g[d][s]=1; + } + } + + void RemoveEdge() + { + int s, d; + cout<<"Enter Vertices:"<>s>>d; + g[s][d]=0; + g[d][s]=0; + } +private: + + void DFS(int start,bool* visited) + { + cout< q; + q.push(start); + + while(!q.empty()) + { + int k=q.front(); + q.pop(); + cout<>s; + bool* visited=new bool[n]; + for(int i=0;i* getpathDFS(bool* visited,int v1,int v2) + { + if(v1==v2) + { + vector * t= new vector; + t->push_back(v1); + return t; + } + visited[v1]=true; + vector * b= new vector; + + for(int i=0;iempty()) + continue; + else + { + b->push_back(v1); + return b; + } + } + } + } + return b; + } + + //Question5 + vector getpathBFS(int s,int e,bool* visited) + { + unordered_map m; + visited[s]=true; + queue q; + q.push(s); + int flag=0; + while(!q.empty()) + { + int k=q.front(); + q.pop(); + for(int i=0;i path; + if(flag==1) + { + int k=e; + while(s!=k) + { + path.push_back(k); + k=m[k]; + } + path.push_back(s); + } + return path; + + } + + //Question6 + bool isConnected() + { + int s; + bool* visited=new bool[n]; + for(int i=0;i DFS_CC(int start,bool* visited) + { + vector b; + vector temp; + b.push_back(start); + visited[start]=true; + for(int i=0;i> ConnectedComponents() + { + int s; + vector> v; + vector t; + bool* visited=new bool[n]; + for(int i=0;i +#include "node.cpp" +using namespace std; + +node* bubble_sort_LinkedList_itr(node* head) +{ + int i=0,j=0; + int l=length(head); + node* prev,* curr,* next; + prev=NULL; + curr=head; + next=curr->next; + int count; + while(idata > curr->next->data) + { + count++; + if(prev==NULL) + { + curr->next=next->next; + next->next=curr; + head=next; + prev=head; + next=curr->next; + } + else + { + prev->next=next; + curr->next=next->next; + next->next=curr; + prev=prev->next; + next=curr->next; + } + } + else + { + prev=curr; + curr=curr->next; + next=curr->next; + } + + j++; + } + if(count==0) + break; + + i++; + curr=head; + prev=NULL; + next=curr->next; + } + return head; +} + + +int main() +{ + node* head=insertend(); + print(head); + head=bubble_sort_LinkedList_itr(head); + print(head); +} \ No newline at end of file diff --git a/ds/LinkedList/llmergesort.cpp b/ds/LinkedList/llmergesort.cpp new file mode 100644 index 0000000..cf774c8 --- /dev/null +++ b/ds/LinkedList/llmergesort.cpp @@ -0,0 +1,80 @@ +#include +#include "node.cpp" +using namespace std; + +node* merge(node *head1, node *head2) +{ + + node* head=NULL; + node* tail=NULL; + node* temp; + while(head1!=NULL&&head2!=NULL) + { + if(head1->data<=head2->data) + { + temp=head1; + head1=head1->next; + } + else + { + temp=head2; + head2=head2->next; + } + if(head==NULL) + { + head=temp; + tail=temp; + } + else + { + tail->next=temp; + tail=temp; + } + } + if(head1!=NULL) + tail->next=head1; + if(head2!=NULL) + tail->next=head2; + return head; +} + +node* mergeSort(node *head) +{ + + int n=length(head); + if(n==0||n==1) + return head; + node* head1=head; + node* head2=NULL; + node* temp=head; + int i=0; + while(temp!=NULL) + { + if(i<(n/2)-1) + { + temp=temp->next; + i++; + } + else + { + head2=temp->next; + temp->next=NULL; + break; + } + } + print(head1); + print(head2); + head1=mergeSort(head1); + head2=mergeSort(head2); + return merge(head1,head2); +} + +int main() +{ + node* head; + head=insertend(); + print(head); + head=mergeSort(head); + print(head); + +} \ No newline at end of file diff --git a/ds/LinkedList/node.cpp b/ds/LinkedList/node.cpp new file mode 100644 index 0000000..5a7f9a9 --- /dev/null +++ b/ds/LinkedList/node.cpp @@ -0,0 +1,353 @@ +#include +using namespace std; + +class node{ + public: + int data; + node* next; + node(int x) + { + data=x; + next=NULL; + } +}; + + + node* insertbeg() + { + node* head=NULL; + int data; + cin>>data; + while(data!=-1) + { + node* newn=new node(data); + if(head==NULL) + head=newn; + else + { + newn->next=head; + head=newn; + } + } + return head; + } + + node* insertend() + { + node* head=NULL; + node* tail=NULL; + int data; + cin>>data; + while(data!=-1) + { + node* newn=new node(data); + if(head==NULL) + { + head=newn; + tail=newn; + } + else + { + tail->next=newn; + tail=newn; + } + cin>>data; + } + return head; + + } + +int length(node *head) +{ + node*temp=head; + if(temp==NULL) + return 0; + return 1+length(temp->next); + +} + + + void insertati(node* head, int i,int data) + { + node* newn=new node(data); + node* temp=head; + int n=1; + while(n!=i-1&&temp->next!=NULL) + { + temp=temp->next; + n++; + } + if(n!=i-1) + return; + else + { + if(temp->next!=NULL) + newn->next=temp->next; + temp->next=newn; + } + } + +node* deleteati(node* head, int i) +{ + node* temp=head; + int n=length(head); + if(n<=i) + return head; + if(i==0) + { + head=head->next; + } + else + { + int c=0; + while(c!=i-1) + { + temp=temp->next; + c++; + } + temp->next=temp->next->next; + + } + return head; + +} + +node* insertNodeRec(node *head, int i, int data) +{ + if(i==0) + { + node* newnode=new node(data); + newnode->next=head; + head=newnode; + return head; + } + else + { + int l=length(head); + if(i>l) + return head; + else + { + node* temp=head; + if(i-1>0) + return insertNodeRec(temp->next,i-1,data); + else + { + node* newnode=new node(data); + newnode->next=temp->next; + temp->next=newnode; + return head; + } + + } + } +} + +void print(node* head) + { + node* temp=head; + while(temp!=NULL) + { + cout<data<<" "; + temp=temp->next; + } + cout<next,current); + current->next=prev; + return head; +} + +node *reverse_linked_list_rec(node *head) +{ + if(head->next==NULL) + return head; + node* h=reverse_linked_list_rec(head->next); + node* tail=head->next; + tail->next=head; + head->next= NULL; + return h; +} + +node* rev_linkedlist_itr(node* head) +{ + node* slow=NULL; + node* fast=head; + node* temp=head; + while(temp!=NULL) + { + temp=fast->next; + fast->next=slow; + slow=fast; + fast=temp; + } + return slow; +} + +int indexOfNRecursive(node *head, int n) { + if(head==NULL) + return -1; + if(head->data==n) + return 0; + int k=indexOfNRecursive(head->next,n); + if(k!=-1) + return 1+k; + else return -1; + +} + + +node* arrange_LinkedList(node* head) +{ + node* headev=NULL; + node* tailev=NULL; + + node* headodd=NULL; + node* tailodd=NULL; + + node* temp=head; + while(temp!=NULL) + { + if((temp->data)%2==0) + { + if(headev==NULL) + headev=tailev=temp; + else + { + tailev->next=temp; + tailev=temp; + } + } + else + { + if(headodd==NULL) + headodd=tailodd=temp; + else + { + tailodd->next=temp; + tailodd=temp; + } + + } + temp=temp->next; + } + if(headodd==NULL) + { + head=headev; + tailev=NULL; + } + else if(headev==NULL) + { + head=headodd; + tailodd=NULL; + } + else + { + tailodd->next=headev; + tailev->next=NULL; + head=headodd; + } + return head; +} + + +node* append_LinkedList(node* head,int n) +{ + int l=length(head); + node* temp=head; + while(l-n-1>0) + { + temp=temp->next; + l--; + } + node* temp2=temp->next; + temp->next=NULL; + temp=temp2; + while(temp->next!=NULL) + { + temp=temp->next; + } + temp->next=head; + head=temp2; + //delete temp; + //delete temp2; + return head; + +} + +node* eliminate_duplicate(node* head) +{ + node* t1=head; + node* t2=t1->next; + while(t2!=NULL) + { + if(t1->data==t2->data) + { + node* p=t2; + t2=t2->next; + delete p; + } + else + { + t1->next=t2; + t1=t1->next; + t2=t2->next; + } + } + t1->next=t2; + + return head; + + +} + +void print_linkedlist_spl(node*head) +{ + if(head==NULL) + return; + print_linkedlist_spl(head->next); + cout<data<<" "; + +} + +bool check_palindrome(node* head) +{ + + int n=length(head); + if(n-count==0||n-count==1) + return true; + node* temp=head; + int i=1; + while(inext; + i++; + } + count++; + if(head->data==temp->data) + return check_palindrome(head->next); + else + return false; + +} +node* midpoint_linkedlist(node *head) +{ + node* t1= head; + node* t2= head; + while(t2->next!=NULL&&t2->next->next!=NULL) + { + t2=t2->next->next; + t1=t1->next; + } + return t1; + +} diff --git a/ds/LinkedList/swap.cpp b/ds/LinkedList/swap.cpp new file mode 100644 index 0000000..6486cd9 --- /dev/null +++ b/ds/LinkedList/swap.cpp @@ -0,0 +1,79 @@ +#include +using namespace std; +#include "node.cpp" + +node* swap_nodes(node *head,int i,int j) +{ + if(i==j) + return head; + node *t1, *t2,*temp1,*temp2,*temp; + t1=t2=head; + temp1=temp2=temp=NULL; + int flag=0,a=i,b=j; + while(i-1>0) + { + t1=t1->next; + i--; + } + cout<data<0) + { + t2=t2->next; + j--; + } + cout<data<next; + temp2=temp->next->next; + temp->next=head; + temp1->next=head->next; + head=temp1; + temp->next->next=temp2; + } + else + { + if(a-b==1||b-a==1) + { + if(t1->next==t2) + { + t1->next=t2->next; + t2->next=t1->next->next; + t1->next->next=t2; + } + else + { + t2->next=t1->next; + t1->next=t2->next->next; + t2->next->next=t1; + } + + } + else + { + temp=t1->next; + temp1=t1->next->next; + temp2=t2->next->next; + t1->next=t2->next; + t2->next=temp; + t1->next->next=temp1; + t2->next->next=temp2; + } + } + return head; +} + +int main() +{ + node* head=insertend(); + print(head); + head=swap_nodes(head,0,1); + print(head); + +} \ No newline at end of file diff --git a/ds/Priority Queues/minheap.h b/ds/Priority Queues/minheap.h new file mode 100644 index 0000000..3c769cf --- /dev/null +++ b/ds/Priority Queues/minheap.h @@ -0,0 +1,216 @@ +#include +using namespace std; +class minheap +{ + int * arr; + int size; + + void upheapify(); + void downheapify(); + void swap(int& a, int& b); + +public: + minheap() + { + arr= new int[10000]; + size=0; + } + void insert(int a); + int getmin(); + int removemin(); + int getsize(); + void printheap(); + +}; + +void minheap::swap(int&a, int&b) +{ + int t=a; + a=b; + b=t; +} + +void minheap::upheapify() +{ + int x=size; + int y=(size-1)/2; + if(y<0) + return; + while(y >= 0 && arr[y] > arr[x]) + { + swap(arr[x],arr[y]); + x=y; + y=(x-1)/2; + } + +} + +void minheap::downheapify() +{ + int x=0; + int y=2*x + 1; + int z=2*x + 2; + int minpos; + while((yarr[y]) || (zarr[z])) + { + if(y pq; + + public : + + PriorityQueue() { + + } + + bool isEmpty() { + return pq.size() == 0; + } + + // Return the size of priorityQueue - no of elements present + int getSize() { + return pq.size(); + } + + int getMin() { + if(isEmpty()) { + return 0; // Priority Queue is empty + } + return pq[0]; + } + + void swap(int&a, int&b) + { + int t=a; + a=b; + b=t; + } + + void insert(int element) { + pq.push_back(element); + + int childIndex = pq.size() - 1; + + while(childIndex > 0) { + int parentIndex = (childIndex - 1) / 2; + + if(pq[childIndex] < pq[parentIndex]) { + int temp = pq[childIndex]; + pq[childIndex] = pq[parentIndex]; + pq[parentIndex] = temp; + } + else { + break; + } + childIndex = parentIndex; + } + + } + + int removeMin() { + // Complete this function + int size=pq.size(); + if(size==0) + return -1; + + int k=pq[0]; + swap(pq[0], pq[size-1]); + pq.pop_back(); + size--; + + + int x=0; + int y=2*x + 1; + int z=2*x + 2; + int minpos; + while((ypq[y]) || (zpq[z])) + { + if(y +class queue +{ + T* data; + int front; + int rear; + int size; + int capacity; +public: + queue(int s) + { + data=new T[s]; + front=-1; + rear=0; + size=0; + capacity=s; + } + void enqueue(int element) + { + if(size==capacity) + { + T* newdata=new T[2*capacity]; + int j=0; + for(int i=front;i +class node { + public : + T data; + node *next; + + node(T data) { + this -> data = data; + next = NULL; + } +}; + +template +class Queue { + node* front; + node* rear; + int size; + public : + Queue() { + front=rear=NULL; + size=0; + } + + void enqueue(T data) { + + node* newnode= new node(data); + if(rear==NULL) + { + front=rear=newnode; + } + else + { + rear->next=newnode; + rear=newnode; + } + size++; + } + + int getSize() { + return size; + } + + bool isEmpty() { + return size==0; + } + + T dequeue() { + // Return 0 if queue is empty + if(front==NULL) + return 0; + T data=front->data; + node* temp=front; + if(front->next==NULL) + { + front=rear=NULL; + } + else + front=front->next; + delete temp; + size--; + return data; + } + + T getfront() { + // Return 0 if queue is empty + if(front==NULL) + return 0; + return front->data; + } +}; diff --git a/ds/Stack and Queue/reversestack.cpp b/ds/Stack and Queue/reversestack.cpp new file mode 100644 index 0000000..f3287c1 --- /dev/null +++ b/ds/Stack and Queue/reversestack.cpp @@ -0,0 +1,78 @@ +#include +#include +using namespace std; + +void reverseStack2(stack &s1, stack &s2) +{ + + if(s1.empty()) + return; + int a=s1.top(); + s1.pop(); + reverseStack2(s1,s2); //assume it comes back with reverse stack + while(!s1.empty()) + { + int x=s1.top(); + s1.pop(); + s2.push(x); + } + s1.push(a); + while(!s2.empty()) + { + int x=s2.top(); + s2.pop(); + s1.push(x); + } +} + + +void reverseStack(stack &s1, stack &s2,int c=0) { + + //reverse(s1,s2); + if(c==0) + { + c=s1.size(); + cout< s1,s2; + int n,x,i=1; + cin>>n; + while(i<=n) + { + cin>>x; + s1.push(x); + i++; + } + reverseStack(s1,s2); + while(!s1.empty()) + { + cout< +#include +template +using namespace std; + +class stack +{ + T* data; + int nextIndex; + int size; + +public: + stack() + { + data=new T[10]; + nextIndex=0; + size=10; + } + void push(int e) + { + if(nextIndex==size) + { + T * newdata=new T[2*size]; + for(int i=0;i +class Node { + public : + T data; + Node *next; + + Node(T data) { + this -> data = data; + next = NULL; + } +}; + +template +class Stack { + Node *head; + int size; // number of elements prsent in stack + + public : + + Stack() { + head=NULL; + size=0; + } + + int getSize() { + return size; + } + + bool isEmpty() { + return size==0; + } + + void push(T element) { + Node* newnode=new Node(element); + newnode->next=head; + head=newnode; + size++; + } + + T pop() { + // Return 0 if stack is empty. Don't display any other message + if(head==NULL) + return 0; + else + { + T ans=head->data; + Node* temp=head; + head=head->next; + size--; + delete temp; + return ans; + } + + } + + T top() { + // Return 0 if stack is empty. Don't display any other message + if(head==NULL) + return 0; + else + { + return head->data; + } + } +}; diff --git a/ds/Tries and Huffman Codes/trie.cpp b/ds/Tries and Huffman Codes/trie.cpp new file mode 100644 index 0000000..48a1dbd --- /dev/null +++ b/ds/Tries and Huffman Codes/trie.cpp @@ -0,0 +1,108 @@ +#include +using namespace std; + +class TrieNode { + public : + char data; + TrieNode **children; + bool isTerminal; + + TrieNode(char data) { + this -> data = data; + children = new TrieNode*[26]; + for(int i = 0; i < 26; i++) { + children[i] = NULL; + } + isTerminal = false; + } +}; + +class Trie { + TrieNode *root; + + public : + + Trie() { + root = new TrieNode('\0'); + } + + void insertWord(TrieNode *root, string word) { + // Base case + if(word.size() == 0) { + root -> isTerminal = true; + return; + } + + // Small Calculation + int index = word[0] - 'a'; + TrieNode *child; + if(root -> children[index] != NULL) { + child = root -> children[index]; + } + else { + child = new TrieNode(word[0]); + root -> children[index] = child; + } + + // Recursive call + insertWord(child, word.substr(1)); + } + + // For user + void insertWord(string word) { //it is basically overloading + insertWord(root, word); + } + + bool search(TrieNode* root,string word) { + + if(word.size()==0) + { + return root->isTerminal; + } + + int i= word[0]-'a'; + if(root->children[i]!=NULL) + return search(root->children[i],word.substr(1)); + else + return false; + } + + bool search(string word) { + + return search(root,word); + + } +}; + +int main() { + int choice; + cin >> choice; + Trie t; + + //cout << "asasas"; + while(choice != -1){ + string word; + bool ans; + switch(choice) { + case 1 : // insert + // getline(cin, word); + cin >> word; + t.insertWord(word); + break; + case 2 : // search + // getline(cin, word); + cin >> word; + ans = t.search(word); + if (ans) { + cout << "true" << endl; + } else { + cout << "false" << endl; + } + break; + default : + return 0; + } + cin >> choice; + } + return 0; +} \ No newline at end of file From 29d9da87853eff84fa21d70d5d6bbdee6da2d58a Mon Sep 17 00:00:00 2001 From: RathodKinjal76 <12bce076@gmail.com> Date: Wed, 31 Oct 2018 17:01:53 +0530 Subject: [PATCH 18/20] Added quick sort algo implementation in python --- sort/quick_sort.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 sort/quick_sort.py diff --git a/sort/quick_sort.py b/sort/quick_sort.py new file mode 100644 index 0000000..c3bd9bd --- /dev/null +++ b/sort/quick_sort.py @@ -0,0 +1,10 @@ +def quick_sort(arr): + if len(arr) <= 1: + return arr + pivot = arr[len(arr) // 2] + left = [x for x in arr if x < pivot] + middle = [x for x in arr if x == pivot] + right = [x for x in arr if x > pivot] + return quick_sort(left) + middle + quick_sort(right) + +print (quick_sort([5,2,8,3,9,12,43])) # This will print [2,3,5,8,9,12,43] From 001dbf50c471b17f53f0b5ad0b9a63a874c017fd Mon Sep 17 00:00:00 2001 From: Anshu Kumar Date: Tue, 26 Feb 2019 16:33:53 +0530 Subject: [PATCH 19/20] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f76d946..01a26c6 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ -

    Add only Advanced Data Structrues

    +

    Some cool data structures Repo

    +

    This repo contains the implementation of various data structus in different languages.

    From e5312afed589f8cd69db7b77e778fcf94f140dbb Mon Sep 17 00:00:00 2001 From: Anshu Kumar Date: Sat, 23 Oct 2021 09:25:20 +0530 Subject: [PATCH 20/20] Create hello.cpp --- hello.cpp | 1 + 1 file changed, 1 insertion(+) create mode 100644 hello.cpp diff --git a/hello.cpp b/hello.cpp new file mode 100644 index 0000000..e3cd11b --- /dev/null +++ b/hello.cpp @@ -0,0 +1 @@ +#include