├── .gitignore ├── Bloom-Filter ├── Base.hpp ├── Check.hpp ├── HashFunctions.hpp ├── Insert.hpp ├── README.md ├── a.out └── src.cpp ├── Disjoint-Sets ├── Compressed.cpp ├── Naive.cpp ├── README.md └── a.out ├── Double-Ended-Queue ├── a.out ├── basicHelper.hpp ├── findPivot.cpp └── maxElWindow.cpp ├── Fenwick-Tree ├── .gitignore ├── BuildTree.hpp ├── Includes.hpp ├── README.md ├── Src.cpp ├── Update.hpp └── getSum.hpp ├── Graphs ├── .gitignore ├── BFS.cpp ├── Bellman-Ford.cpp ├── DFS.cpp ├── Dijkstra.cpp ├── Floyd-Warshall.cpp ├── Problems │ ├── noOfWays.cpp │ ├── removeLessK.cpp │ └── shortestPathUnWeighted.cpp ├── Topological-Sort.cpp ├── Unweighted.hpp ├── Weighted.hpp └── isCyclic.cpp ├── Hashing ├── .gitignore ├── basicHash.cpp ├── chainedHash.cpp ├── indexMapping.cpp ├── linearProbing.cpp └── tester.cpp ├── Heaps ├── KLargestElements.cpp ├── MaxHeap.h ├── MinHeap.cpp ├── a.out ├── basicHeapTemplate.h └── combineHeaps.cpp ├── LICENSE ├── Linked-Lists ├── .gitignore ├── addNumbers.cpp ├── basicActions.hpp ├── deleteKeys.cpp ├── detectLoop.cpp ├── difference.cpp ├── introToRecursionLL.cpp ├── oddEven.cpp ├── palindrome.cpp ├── pointerBasics.cpp ├── pointerBasics2.cpp ├── pointersCon.cpp ├── reverseFirstKNodes.cpp ├── reverseKPairs.cpp ├── reverseLinkedList.cpp ├── single.cpp ├── skipList.cpp ├── sum0s.cpp ├── sumOfNode0s.cpp └── swapPairs.cpp ├── Palindromic-Tree ├── README.md ├── a.out └── palindromic-tree.cpp ├── Persistant-Segment-Tree ├── Build.hpp ├── README.md ├── Src.cpp ├── Structure.hpp ├── Upgrade.hpp └── a.out ├── README.md ├── Segment-Tree ├── .DS_Store ├── Lazy-Propogation │ ├── BuildTree.cpp │ └── a.out ├── Problems │ ├── CF197D.cpp │ ├── DIVMAC.cpp │ ├── Distinct.cpp │ ├── LCM.cpp │ ├── XeniaBitOp.cpp │ ├── a.out │ └── luckyQueries.cpp ├── README.md ├── a.out ├── buildTree.hpp ├── maxRangeQuery.cpp └── minRangeQuery.cpp ├── Strings ├── a.out ├── lengthEncoding.cpp ├── reverseString.cpp └── searchRowColumn.cpp ├── Suffix-Arrays ├── Build.cpp ├── EfficientSuffixArray.cpp └── a.out ├── Suffix-Trees ├── Base.hpp ├── Insert.hpp ├── Main.cpp ├── PrintTree.hpp ├── Problems │ ├── a.out │ └── subString.cpp ├── README.md └── a.out ├── Treap ├── .gitignore ├── Delete.hpp ├── Includes.hpp ├── Insert.hpp ├── Operations.hpp ├── README.md ├── ShowTree.hpp ├── Src.cpp └── Structure.hpp ├── Trees ├── BTrees │ ├── NodeStructure.hpp │ ├── a.out │ └── basicTemplate.cpp ├── Binary_Search_Tree │ ├── .DS_Store │ ├── .gitignore │ ├── KthLargest.cpp │ ├── TreeOne.cpp │ ├── a.exe │ ├── a.out │ ├── alternateCorners.cpp │ ├── basicTreeTemplate.h │ ├── classicIterative │ │ ├── a.out │ │ ├── inOrderIterative.cpp │ │ ├── leafNodes.cpp │ │ ├── levelOrderIterative.cpp │ │ ├── maximumElement_BST.cpp │ │ ├── postOrderIterative.cpp │ │ └── preOrderIterative.cpp │ ├── consecutiveCount.cpp │ ├── correctTheBST.cpp │ ├── countRange.cpp │ ├── deepestNode.cpp │ ├── fullNodes.cpp │ ├── heightOfATree.cpp │ ├── inorderIterative.cpp │ ├── isBST2.cpp │ ├── isBst1.cpp │ ├── isomorphicOrNot.cpp │ ├── kthLargestElement.cpp │ ├── leafNodesCount.cpp │ ├── leastCommonAncestor.cpp │ ├── leftSubTreeSum.cpp │ ├── leftTreeView.cpp │ ├── maxElementBW2Nodes.cpp │ ├── maxSumPath.cpp │ ├── mirrorTree.cpp │ ├── nodesAtDistanceK.cpp │ ├── oddEvenLevelDifference.cpp │ ├── rightSubTreeSum.cpp │ ├── secondLargest.cpp │ ├── sumOfAllNodes.cpp │ ├── swapOddLevelNodes.cpp │ ├── test.cpp │ ├── verticalSum.cpp │ └── zigZagTraversal.cpp └── Binary_Tree │ ├── BFS_newLines.cpp │ ├── a.out │ ├── basicTreeTemplate.h │ ├── binarySum.cpp │ ├── boundaryTraversal.cpp │ ├── boundaryTraversalRecursive.cpp │ ├── createDefaultTree.hpp │ ├── diagnolTraversal.cpp │ ├── maximumElement.cpp │ ├── mergeBinaryTrees.cpp │ ├── minimumElement.cpp │ ├── nodesAtDistanceD.cpp │ └── shortestRootToLeafPath.cpp ├── Trie ├── BaseTemplate.hpp ├── Dict.cpp ├── README.md ├── TrieFunctions.cpp ├── a.out ├── countStrings.cpp ├── maxFreq.cpp ├── replaceWords.cpp ├── searchWord.cpp └── searchWordsWithGivenPrefix.cpp ├── XOR-Linked-List ├── Includes.hpp ├── Src.cpp ├── Structure.hpp └── a.out ├── queue ├── README.md ├── a.out ├── basicActions.h ├── priority_queue.cpp └── queues_LL.cpp └── stacks ├── README.md ├── a.out ├── basicActions.h └── reverseString.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | /.* 2 | /a.* 3 | 4 | -------------------------------------------------------------------------------- /Bloom-Filter/Base.hpp: -------------------------------------------------------------------------------- 1 | /* 2 | Seed = 444 3 | Character Length Max. = 32 4 | Size of Bit-Set = 32 5 | */ 6 | 7 | #ifndef BASE 8 | #define BASE 9 | #include 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | bitset<32> bset; 15 | #include "HashFunctions.hpp" 16 | #include "Check.hpp" 17 | #include "Insert.hpp" 18 | 19 | #endif 20 | -------------------------------------------------------------------------------- /Bloom-Filter/Check.hpp: -------------------------------------------------------------------------------- 1 | #ifndef CHK 2 | #define CHK 3 | #include "Base.hpp" 4 | 5 | bool Check(const char *c) { 6 | int hashOne = jenkinHash(c); 7 | int hashTwo = murmur_32(c, strlen(c), 444); 8 | hashOne %= size_; 9 | hashTwo %= size_; 10 | 11 | return (bset[size_ - hashOne] && bset[size_ - hashTwo]); 12 | } 13 | #endif 14 | -------------------------------------------------------------------------------- /Bloom-Filter/HashFunctions.hpp: -------------------------------------------------------------------------------- 1 | #ifndef HASH 2 | #define HASH 3 | #include "Base.hpp" 4 | static uint32_t size_ = 32; 5 | 6 | uint64_t mix(uint64_t h) { 7 | h ^= (h) >> 23; 8 | (h) *= 0x2127599bf4325c37ULL; 9 | (h) ^= (h) >> 47; 10 | 11 | return h; 12 | } 13 | 14 | uint32_t jenkinHash(const char *c) { 15 | uint32_t hash = 0; 16 | 17 | while(*c) { 18 | hash += *c; 19 | hash += (hash << 10); 20 | hash ^= (hash >> 6); 21 | ++c; 22 | } 23 | 24 | hash += (hash << 3); 25 | hash ^= (hash >> 11); 26 | hash += (hash << 15); 27 | 28 | return hash; 29 | } 30 | 31 | uint32_t murmur_32(const char* key, size_t len, uint32_t seed) 32 | { 33 | uint32_t h = seed; 34 | if (len > 3) { 35 | size_t i = len >> 2; 36 | do { 37 | uint32_t k; 38 | memcpy(&k, key, sizeof(uint32_t)); 39 | key += sizeof(uint32_t); 40 | k *= 0xcc9e2d51; 41 | k = (k << 15) | (k >> 17); 42 | k *= 0x1b873593; 43 | h ^= k; 44 | h = (h << 13) | (h >> 19); 45 | h = h * 5 + 0xe6546b64; 46 | } while (--i); 47 | } 48 | if (len & 3) { 49 | size_t i = len & 3; 50 | uint32_t k = 0; 51 | do { 52 | k <<= 8; 53 | k |= key[i - 1]; 54 | } while (--i); 55 | k *= 0xcc9e2d51; 56 | k = (k << 15) | (k >> 17); 57 | k *= 0x1b873593; 58 | h ^= k; 59 | } 60 | h ^= len; 61 | h ^= h >> 16; 62 | h *= 0x85ebca6b; 63 | h ^= h >> 13; 64 | h *= 0xc2b2ae35; 65 | h ^= h >> 16; 66 | return h; 67 | } 68 | 69 | uint64_t fasthash64(const void *buf, size_t len, uint64_t seed) 70 | { 71 | const uint64_t m = 0x880355f21e6d1965ULL; 72 | const uint64_t *pos = (const uint64_t *)buf; 73 | const uint64_t *end = pos + (len / 8); 74 | const unsigned char *pos2; 75 | uint64_t h = seed ^ (len * m); 76 | uint64_t v; 77 | 78 | while (pos != end) { 79 | v = *pos++; 80 | h ^= mix(v); 81 | h *= m; 82 | } 83 | 84 | pos2 = (const unsigned char*)pos; 85 | v = 0; 86 | 87 | switch (len & 7) { 88 | case 7: v ^= (uint64_t)pos2[6] << 48; 89 | case 6: v ^= (uint64_t)pos2[5] << 40; 90 | case 5: v ^= (uint64_t)pos2[4] << 32; 91 | case 4: v ^= (uint64_t)pos2[3] << 24; 92 | case 3: v ^= (uint64_t)pos2[2] << 16; 93 | case 2: v ^= (uint64_t)pos2[1] << 8; 94 | case 1: v ^= (uint64_t)pos2[0]; 95 | h ^= mix(v); 96 | h *= m; 97 | } 98 | 99 | return mix(h); 100 | } 101 | 102 | uint32_t fasthash32(const void *buf, size_t len, uint32_t seed) { 103 | uint64_t Hsh = fasthash64(buf, len, seed); 104 | 105 | Hsh -= (Hsh << 32); 106 | return Hsh; 107 | } 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /Bloom-Filter/Insert.hpp: -------------------------------------------------------------------------------- 1 | #ifndef INS_WR 2 | #define INS_WR 3 | #include "Base.hpp" 4 | 5 | bitset<32> Insert(const char *c) { 6 | int sz = strlen(c); 7 | 8 | 9 | int hashOne = jenkinHash(c); 10 | int hashTwo = murmur_32(c, sz, 444); 11 | int hashThree = fasthash32(c, sz, 444); 12 | 13 | hashOne %= size_; 14 | hashTwo %= size_; 15 | hashThree %= size_; 16 | 17 | bset |= (1 << (size_ - hashOne)); 18 | bset |= (1 << (size_ - hashTwo)); 19 | bset |= (1 << (size_ - hashThree)); 20 | 21 | return bset; 22 | } 23 | 24 | #endif 25 | -------------------------------------------------------------------------------- /Bloom-Filter/README.md: -------------------------------------------------------------------------------- 1 | ### Bloom Filter. 2 | 3 | ![](https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2F4.bp.blogspot.com%2F-l2nxkF4rMVg%2FVK7qaa0ND0I%2FAAAAAAAAAAg%2FkPC-a4ykUJ8%2Fs1600%2FBloom-fig1.1.png&f=1&nofb=1) 4 | 5 | #### Introduction. 6 | A Bloom filter is a space-efficient probabilistic data structure, conceived by Burton 7 | Howard Bloom in 1970, that is used to test whether an element is a member of a set. 8 | False positive matches are possible, but false negatives are not – in other words, a query 9 | returns either "possibly in set" or "definitely not in set". Elements can be added to the set, 10 | but not removed (though this can be addressed with the counting Bloom filter variant); 11 | The more elements that are added to the set, the larger the probability of false positives. 12 | 13 | #### Hash Function. 14 | 3 Non-Cryptographic Hash functions are used to occupy bits. An Hash function must be consistent and 15 | must exhibit good Avalanche Effect. In this Code, We used 3 following 32-bit Hash functions: 16 | 17 | - Murmur Hash 18 | - Jenkins Hash 19 | - Fast Hash 20 | 21 | We can use any number of hash functions. Lower the size of the bit-array, higher the probability of 22 | false negatives. 23 | 24 | - Avalanche Effect: It is the effect which results in a completely different value even if the input is 25 | slightly changed. 26 | 27 | #### Insertion. 28 | Each of the 3 Hash functions give us a digit. Let us assume 3 hash functions to be h1, h2 and h3. 29 | If h1 = 3, h2 = 5 and h3 = 8, Size of the bit-array = 15. The Positions 3, 5 and 8 are occupied. 30 | For the next word, let h1 = 4, h2 = 3 and h3 = 5. But, 3 and 5 are already occupied. So 4 is marked. 31 | 32 | The bit-array now looks like <0 0 0 1 1 1 0 0 1 0 0 0 0 0 0> 33 | 34 | #### Check. 35 | Checking if a word is present or not is simple. If all the hash-function's indices in the bit-array are 1, 36 | then we can say the word has a high probability of being present. 37 | 38 | #### Deletion. 39 | Deletion of word may seem simple but it is not recommended. As deletion means flipping the ones of the 40 | hash-function indices, Any other word which might have occupied that index will be lost. When no of words 41 | are high, there is a high probability that many words will be lost. Hence, we don't delete words from 42 | bloom filter. 43 | 44 | To know more: [Tutorial](https://www.youtube.com/c/manosriram) 45 | -------------------------------------------------------------------------------- /Bloom-Filter/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Bloom-Filter/a.out -------------------------------------------------------------------------------- /Bloom-Filter/src.cpp: -------------------------------------------------------------------------------- 1 | #include "Base.hpp" 2 | 3 | int main() { 4 | const char *cp[] = {"one", "two", "zzz"}; 5 | 6 | Insert(cp[0]); 7 | Insert(cp[1]); 8 | 9 | cout << Check(cp[2]); // Definitely Not Present. 10 | Insert(cp[2]); 11 | cout << endl; 12 | cout << Check(cp[2]); // Maybe it is present. 13 | } 14 | -------------------------------------------------------------------------------- /Disjoint-Sets/Compressed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | static int parent[264], sz[264], rnk[264]; 4 | 5 | // Create a new set. 6 | void make_set(int vertex) { 7 | parent[vertex] = vertex; 8 | sz[vertex] = 1; 9 | rnk[vertex] = 0; 10 | } 11 | 12 | // O(logN) time. 13 | int find_set(int vertex) { 14 | if (vertex == parent[vertex]) return vertex; 15 | 16 | return parent[vertex] = find_set(parent[vertex]); 17 | } 18 | 19 | // Union By Size. 20 | void union_sets_by_sz(int set_a, int set_b) { 21 | set_a = find_set(set_a); 22 | set_b = find_set(set_b); 23 | if (set_a != set_b) { 24 | if (sz[set_a] < sz[set_b]) swap(set_a, set_b); 25 | 26 | parent[set_b] = set_a; 27 | sz[set_a] += sz[set_b]; 28 | } 29 | } 30 | 31 | // Union By Rank. 32 | void union_sets_by_rank(int set_a, int set_b) { 33 | set_a = find_set(set_a); 34 | set_b = find_set(set_b); 35 | if (set_a != set_b) { 36 | if (rnk[set_a] < rnk[set_b]) swap(set_a, set_b); 37 | 38 | parent[set_b] = set_a; 39 | if (rnk[set_a] == rnk[set_b]) ++rnk[set_a]; 40 | } 41 | } 42 | 43 | int main() { 44 | // Create 3 different sets. 45 | make_set(1); 46 | make_set(2); 47 | make_set(3); 48 | 49 | // Union Operation bw 1 and 2. 50 | union_sets_by_sz(1, 2); 51 | union_sets_by_rank(2, 3); 52 | 53 | cout << find_set(3); // 1 54 | } 55 | 56 | -------------------------------------------------------------------------------- /Disjoint-Sets/Naive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | static int parent[264]; 4 | 5 | void make_set(int vertex) { 6 | parent[vertex] = vertex; 7 | } 8 | 9 | // O(n) time. 10 | int find_set(int vertex) { 11 | if (vertex == parent[vertex]) return vertex; 12 | 13 | return find_set(parent[vertex]); 14 | } 15 | 16 | void union_sets(int set_a, int set_b) { 17 | set_a = find_set(set_a); 18 | set_b = find_set(set_b); 19 | if (set_a != set_b) 20 | parent[set_b] = set_a; 21 | } 22 | 23 | int main() { 24 | // Create 3 different sets. 25 | make_set(1); 26 | make_set(2); 27 | make_set(3); 28 | 29 | // Union Operation bw 1 and 2. 30 | union_sets(1, 2); 31 | 32 | cout << find_set(2); // 1 33 | } 34 | -------------------------------------------------------------------------------- /Disjoint-Sets/README.md: -------------------------------------------------------------------------------- 1 | **Disjoint Data-Structure for quick union and find.** 2 | 3 | ``` 4 | Applications: 5 | 1. Connected components in a graph. 6 | 2. Search for connected components in an image. 7 | 3. Compress jumps along a segment / Painting subarrays offline. 8 | 4. Kruskals minimum spanning tree and many more... 9 | ``` 10 | 11 | 12 | ### Read more [here](http://manosriram.xyz/post/5ecfca6cd51dc36e5ce1c0e6/Disjoint-Sets) 13 | -------------------------------------------------------------------------------- /Disjoint-Sets/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Disjoint-Sets/a.out -------------------------------------------------------------------------------- /Double-Ended-Queue/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Double-Ended-Queue/a.out -------------------------------------------------------------------------------- /Double-Ended-Queue/basicHelper.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 264 3 | using namespace std; 4 | 5 | struct DEQ { 6 | int *q; 7 | int front, last; 8 | }; 9 | 10 | void initDEQ(DEQ *deq) { 11 | deq->front = -1; 12 | deq->last = MAX; 13 | deq->q = new int[MAX]; 14 | } 15 | 16 | void insertFront(DEQ *deq, int data) { 17 | deq->q[++deq->front] = data; 18 | } 19 | 20 | void insertLast(DEQ *deq, int data) { 21 | deq->q[--deq->last] = data; 22 | } 23 | 24 | void dqFront(DEQ *deq) { 25 | --deq->front; 26 | } 27 | 28 | void dqLast(DEQ *deq) { 29 | ++deq->last; 30 | } 31 | 32 | int getFront(DEQ *deq) { 33 | if (deq->front != -1) 34 | return deq->q[deq->front]; 35 | 36 | return -1; 37 | } 38 | 39 | int getLast(DEQ *deq) { 40 | if (deq->last != MAX) 41 | return deq->q[deq->last]; 42 | 43 | return MAX; 44 | } 45 | 46 | void printDEQ(DEQ *deq) { 47 | int itr = 0; 48 | while (itr <= deq->front) { 49 | cout << deq->q[itr] << " "; 50 | itr++; 51 | } 52 | cout << "<--> "; 53 | itr = deq->last; 54 | while (itr < MAX) { 55 | cout << deq->q[itr] << " "; 56 | itr++; 57 | } 58 | cout << '\n'; 59 | } -------------------------------------------------------------------------------- /Double-Ended-Queue/findPivot.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Double-Ended-Queue/findPivot.cpp -------------------------------------------------------------------------------- /Double-Ended-Queue/maxElWindow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicHelper.hpp" 3 | using namespace std; 4 | 5 | int main() { 6 | int a[] = {1, 3, -1, -3, 5, 3, 6, 7}; 7 | 8 | 9 | 10 | } -------------------------------------------------------------------------------- /Fenwick-Tree/.gitignore: -------------------------------------------------------------------------------- 1 | a.out 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /Fenwick-Tree/BuildTree.hpp: -------------------------------------------------------------------------------- 1 | #include "./Includes.hpp" 2 | #include "./Update.hpp" 3 | 4 | vector Build(vector sumArray, int n) { 5 | vector BTree(n); 6 | 7 | for (int t=1;t<=n;++t) 8 | BTree[t] = 0; 9 | 10 | for (int t=0;t 5 | #include 6 | #include 7 | #include 8 | using std::cout; 9 | using std::cin; 10 | using std::vector; 11 | 12 | #endif 13 | 14 | -------------------------------------------------------------------------------- /Fenwick-Tree/README.md: -------------------------------------------------------------------------------- 1 | ## Fenwick-Tree || Binary-Indexed-Tree 2 | ![Fenwick-Tree](https://upload.wikimedia.org/wikipedia/commons/d/dc/BITDemo.gif) 3 | ### Introduction. 4 | 5 | A Fenwick tree or binary indexed tree is a data structure that can efficiently update elements and calculate 6 | prefix sums in a table of numbers. As it is a Prefix-Tree, we can usually get range results between 0 -> x. 7 | 8 | Although Fenwick-Tree is said to be a Tree, it is implemented as an array using the properties of the tree. 9 | The whole concept of Fenwick-Tree was created just because any number can be represented in power of 2s. 10 | 11 | This structure was proposed by Boris Ryabko in 1989 with a further modification published in 1992. 12 | It has subsequently became known under the name Fenwick tree after Peter Fenwick who has described this structure 13 | in his 1994 paper. 14 | 15 | Fenwick-Tree is understood easily by using 1-based-array instead of 0-based-array. 16 | 17 | ### Time-Complexity. 18 | 19 | Building the Tree: O(nlogn). O(n) if optimized. (One-Time process) 20 | Update: O(logn) 21 | Query: O(logn) 22 | 23 | ### Parent-Child Access. 24 | 25 | The Essence of this Data-Structure is that it is efficient to travel between child and parent. As said, we can 26 | assume each element as a power of 2. Each Node stores the result between 0 to x. So to calculate the result bw 27 | 0 and y, we can sum up the results between parts till y. Ex: [0, y] can be obtained by [0, x1] + [0, x2] + ... 28 | [0, xn], where xn = y. 29 | 30 | We can get the child of a Node by just considering this operation: x += (x & (x-1)), where 'x' is the index of 31 | the current element. We just flip the last set-bit and add it to the current index-value so that we get the 32 | child's index. We continue this operation until we reach the last node ie, (index <= n). 33 | 34 | Similarly, we can get the Parent of a Node by just considering this operation: x -= (x & (x - 1)), where 'x' is 35 | the index of the current element. Just flipping the last set-bit and subtracting it from the current-index value 36 | will give us the index of Parent Node. We continue this operation until we reach the Root-Node ie, (index > 0). 37 | 38 | ### Building Tree. 39 | 40 | As said, we use the Traversal-Technique to update nodes. We loop-through the array-elementsand call 41 | the updateNode() for each of the element. It updates the node and its children too as they are dependent 42 | on this node. 43 | 44 | ### Querying: 45 | 46 | Similarly, we go through [0, x] summing up the results of each index. Finally, when we hit the end; 47 | we return the result. 48 | 49 | 50 | -------------------------------------------------------------------------------- /Fenwick-Tree/Src.cpp: -------------------------------------------------------------------------------- 1 | #include "./BuildTree.hpp" 2 | #include "./getSum.hpp" 3 | 4 | int main() { 5 | vector sumArray { 3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3 }; 6 | 7 | vector BTree = Build(sumArray, sumArray.size()); 8 | 9 | for (int t=1;t<=BTree.size();++t) 10 | cout << BTree[t] << " "; 11 | } 12 | -------------------------------------------------------------------------------- /Fenwick-Tree/Update.hpp: -------------------------------------------------------------------------------- 1 | #ifndef UPD 2 | #define UPD 3 | 4 | #include "./Includes.hpp" 5 | 6 | void updateNode(vector &BTree, int in, int n, int val) { 7 | while (in <= n) { 8 | BTree[in] += val; 9 | 10 | in += in & (-in); 11 | } 12 | } 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /Fenwick-Tree/getSum.hpp: -------------------------------------------------------------------------------- 1 | #ifndef SUM 2 | #define SUM 3 | 4 | #include "./Includes.hpp" 5 | 6 | 7 | int getSum(vector BTree, int in) { 8 | int sum = 0; 9 | ++in; 10 | 11 | while (in > 0) { 12 | sum += BTree[in]; 13 | in -= in & (-in); 14 | 15 | } 16 | return sum; 17 | } 18 | 19 | int getRangeSum(vector BTree, int st, int ed) { 20 | --st; 21 | int left = getSum(BTree, st); 22 | int right = getSum(BTree, ed); 23 | 24 | return (right - left); 25 | } 26 | 27 | #endif 28 | 29 | -------------------------------------------------------------------------------- /Graphs/.gitignore: -------------------------------------------------------------------------------- 1 | /a.out 2 | -------------------------------------------------------------------------------- /Graphs/BFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | vector g[100]; 7 | bool visited[100] = { false }; 8 | 9 | void BFS() { 10 | queue q; 11 | q.push(1); 12 | visited[1] = true; 13 | while (!q.empty()) { 14 | int currentNode = q.front(); 15 | cout << currentNode << " "; 16 | q.pop(); 17 | 18 | for (auto node: g[currentNode]) { 19 | if (!visited[node]) { 20 | visited[node] = true; 21 | q.push(node); 22 | } 23 | } 24 | } 25 | } 26 | 27 | void addEdge(int s, int d) { 28 | g[s].push_back(d); 29 | g[d].push_back(s); 30 | return; 31 | } 32 | 33 | int main() { 34 | int n = 4; 35 | addEdge(1, 2); 36 | addEdge(1, 3); 37 | addEdge(2, 3); 38 | addEdge(2, 4); 39 | 40 | BFS(); 41 | } 42 | -------------------------------------------------------------------------------- /Graphs/Bellman-Ford.cpp: -------------------------------------------------------------------------------- 1 | #include "Weighted.hpp" 2 | int *dist; 3 | 4 | /* 5 | The difference between Dijkstra and Bellman Ford's Algorithm is that Bellman Ford's Algorithm works for Negative weights too, whereas Dijkstra's doesnt. 6 | 7 | Time Complexity: O(nm), where 'n' is the number of vertices and 'm' is the number of edges. 8 | */ 9 | 10 | void Bellman(Graph *g) { 11 | int times = (g->n) - 1; 12 | 13 | while (times--) { 14 | for (int t=1;t<=g->n;++t) { 15 | auto node = g->list[t]; 16 | 17 | for (auto vtx: node) { 18 | if (dist[t] + vtx.second < dist[vtx.first]) 19 | dist[vtx.first] = dist[t] + vtx.second; 20 | } 21 | } 22 | } 23 | return; 24 | } 25 | 26 | int main() { 27 | Graph *g = new Graph(7); 28 | 29 | dist = new int[g->n]; 30 | for (int t=1;t<=g->n;++t) 31 | dist[t] = INT_MAX/2; 32 | 33 | dist[1] = 0; 34 | 35 | g->addEdge(1, 2, 6); 36 | g->addEdge(1, 3, 5); 37 | g->addEdge(1, 4, 5); 38 | g->addEdge(2, 5, -1); 39 | g->addEdge(3, 2, -2); 40 | g->addEdge(3, 5, 1); 41 | g->addEdge(4, 3, -2); 42 | g->addEdge(4, 6, -1); 43 | g->addEdge(5, 7, 3); 44 | g->addEdge(6, 7, 3); 45 | 46 | Bellman(g); 47 | 48 | for (int t=1;t<=g->n;++t) 49 | cout << dist[t] << " "; 50 | } 51 | 52 | -------------------------------------------------------------------------------- /Graphs/DFS.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | vector g[100]; 7 | bool visited[100] = { false }; 8 | 9 | void DFS(int x) { 10 | if (visited[x]) return; 11 | 12 | cout << x << " "; 13 | visited[x] = true; 14 | for (auto node: g[x]) { 15 | if (!visited[node]) DFS(node); 16 | } 17 | return; 18 | } 19 | 20 | void addEdge(int s, int d) { 21 | g[s].push_back(d); 22 | g[d].push_back(s); 23 | } 24 | 25 | int main() { 26 | int n = 4; 27 | 28 | addEdge(1, 3); 29 | addEdge(1, 2); 30 | addEdge(2, 3); 31 | addEdge(2, 4); 32 | 33 | DFS(1); 34 | } 35 | -------------------------------------------------------------------------------- /Graphs/Dijkstra.cpp: -------------------------------------------------------------------------------- 1 | #include "Weighted.hpp" 2 | int all = false, *dist; 3 | 4 | /* 5 | Dijkstra Algorithm. 6 | Time Complexity: O(ElogV), where 'E' is the total number of edges and 'V' is the number of vertices. 7 | 8 | */ 9 | 10 | // Function which gives us the Least unvisited dist[] value. 11 | int minNode(Graph *g) { 12 | int min_ = INT_MAX, node, ct = 0; 13 | 14 | for (int t=1;t<=g->n;++t) { 15 | if (!g->visited[t]) { 16 | if (dist[t] < min_) { 17 | min_ = dist[t]; 18 | node = t; 19 | } 20 | } else ++ct; 21 | } 22 | if (ct == (g->n)-1) all = true; 23 | 24 | return node; 25 | } 26 | 27 | void Dijkstra(Graph *g) { 28 | // Loop till every node is visited. 29 | while (!all) { 30 | int node = minNode(g); // Current Min Dist Unvisited Node. 31 | g->visited[node]= true; // Mark the current Node as visited. 32 | 33 | // Relax the current node. 34 | for (auto x : g->list[node]) { 35 | if (dist[node] + x.second < dist[x.first]) 36 | dist[x.first] = dist[node] + x.second; 37 | } 38 | } 39 | return; 40 | } 41 | 42 | int main() { 43 | Graph *g = new Graph(6); 44 | dist = new int[10]; 45 | 46 | // Initially, we will assume that all Nodes are at Infinite distance from root. 47 | for (int t=1;t<=g->n;++t) 48 | dist[t] = INT_MAX/2; 49 | 50 | // Distance between Root Node to itself is 0. 51 | dist[1] = 0; 52 | 53 | g->addEdge(1, 2, 2); 54 | g->addEdge(1, 3, 4); 55 | g->addEdge(2, 3, 1); 56 | g->addEdge(2, 4, 7); 57 | g->addEdge(3, 5, 3); 58 | g->addEdge(4, 6, 1); 59 | g->addEdge(5, 4, 2); 60 | g->addEdge(5, 6, 5); 61 | 62 | Dijkstra(g); 63 | 64 | for (int t=1;t<=g->n;++t) 65 | cout << dist[t] << " "; 66 | } 67 | -------------------------------------------------------------------------------- /Graphs/Floyd-Warshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define INF INT_MAX 3 | using namespace std; 4 | int dist[64][64], adj[64][64]; 5 | 6 | void setDistances(int n) { 7 | for (int t=1;t<=n;++t) { 8 | for (int j=1;j<=n;++j) { 9 | if (t == j) dist[t][j] = 0; 10 | else if (adj[t][j]) dist[t][j] = adj[t][j]; 11 | else dist[t][j] = INF; 12 | } 13 | } 14 | return; 15 | } 16 | 17 | void Floyd(int n) { 18 | for (int k=1;k<=n;++k) { 19 | for (int t=1;t<=n;++t) { 20 | for (int j=1;j<=n;++j) { 21 | dist[t][j] = min(dist[t][j], (dist[t][k] + dist[k][j])); 22 | } 23 | } 24 | } 25 | return; 26 | } 27 | 28 | void addEdge(int src, int dest, int wt) { 29 | adj[src][dest] = wt; 30 | adj[dest][src] = wt; 31 | } 32 | 33 | void initGraph(int n) { 34 | for (int t=1;t<=n;++t) { 35 | for (int j=1;j<=n;++j) { 36 | if (t == j) adj[t][j] = 0; 37 | else adj[t][j] = INF; 38 | } 39 | } 40 | return; 41 | } 42 | 43 | int main() { 44 | int n = 5; 45 | initGraph(n); 46 | 47 | addEdge(1, 2, 5); 48 | addEdge(1, 4, 9); 49 | addEdge(1, 5, 1); 50 | addEdge(2, 3, 2); 51 | addEdge(3, 2, 2); 52 | addEdge(3, 4, 7); 53 | addEdge(4, 1, 9); 54 | addEdge(4, 3, 7); 55 | addEdge(4, 5, 2); 56 | addEdge(5, 1, 1); 57 | addEdge(5, 4, 2); 58 | 59 | setDistances(n); 60 | Floyd(n); 61 | 62 | for (int t=1;t<=n;++t) { 63 | for (int j=1;j<=n;++j) { 64 | cout << dist[t][j] << " "; 65 | } 66 | cout << "\n"; 67 | } 68 | 69 | } 70 | 71 | -------------------------------------------------------------------------------- /Graphs/Problems/noOfWays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "Intro.hpp" 5 | using namespace std; 6 | int pathCount = 0; 7 | vector path[26]; 8 | 9 | int findWays(vector grph[], bool visited[], int src, int dest) 10 | { 11 | int ways = 0; 12 | 13 | queue qt; 14 | qt.push(src); 15 | visited[src] = true; 16 | 17 | while (!qt.empty()) 18 | { 19 | int root = qt.front(); 20 | visited[root] = true; 21 | qt.pop(); 22 | 23 | if (root == dest) 24 | continue; 25 | else 26 | { 27 | for (auto i = grph[root].begin(); i != grph[root].end(); i++) 28 | { 29 | if (*i == dest) 30 | ways++; 31 | 32 | if (!visited[*i]) 33 | { 34 | visited[*i] = true; 35 | qt.push(*i); 36 | } 37 | } 38 | } 39 | } 40 | return ways; 41 | } 42 | 43 | int main() 44 | { 45 | int nodes = 9; 46 | vector grph[26]; 47 | bool visited[nodes]; 48 | memset(visited, false, sizeof(visited)); 49 | 50 | addEdge(1, 0, grph); 51 | addEdge(0, 3, grph); 52 | addEdge(0, 4, grph); 53 | addEdge(0, 2, grph); 54 | addEdge(3, 5, grph); 55 | addEdge(3, 8, grph); 56 | addEdge(3, 4, grph); 57 | addEdge(8, 4, grph); 58 | addEdge(4, 7, grph); 59 | addEdge(4, 2, grph); 60 | addEdge(2, 6, grph); 61 | 62 | // printGraph(grph, nodes); 63 | cout << findWays(grph, visited, 1, 4) << endl; 64 | } 65 | -------------------------------------------------------------------------------- /Graphs/Problems/removeLessK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Intro.hpp"> 3 | using namespace std; 4 | 5 | bool removeNodeLessK(vector grph[], int vtx, int *deg, bool visited[], int k) 6 | { 7 | visited[vtx] = true; 8 | 9 | for (auto i = grph[vtx].begin(); i != grph[vtx].end(); i++) 10 | { 11 | if (deg[vtx] < k) 12 | deg[*i]--; 13 | 14 | if (!visited[*i]) 15 | { 16 | if (removeNodeLessK(grph, *i, deg, visited, k)) 17 | deg[*i]--; 18 | } 19 | } 20 | return (deg[vtx] < k); 21 | } 22 | 23 | int main() 24 | { 25 | int nodes = 9; 26 | vector grph[10]; 27 | int deg[10]; 28 | bool visited[nodes]; 29 | memset(visited, false, sizeof(visited)); 30 | 31 | addEdge(1, 2, grph); 32 | addEdge(1, 3, grph); 33 | addEdge(2, 4, grph); 34 | addEdge(2, 5, grph); 35 | addEdge(2, 6, grph); 36 | addEdge(3, 7, grph); 37 | addEdge(7, 8, grph); 38 | addEdge(8, 9, grph); 39 | 40 | for (int t = 0; t < nodes; t++) 41 | { 42 | deg[t] = grph[t].size(); 43 | } 44 | } -------------------------------------------------------------------------------- /Graphs/Problems/shortestPathUnWeighted.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | vector *g; 6 | int *dist; 7 | 8 | void initGraph(int n) { 9 | g = new vector[n]; 10 | dist = new int[n]; 11 | 12 | for (int t=1;t<=n;t++) 13 | dist[t] = -1; 14 | 15 | return; 16 | } 17 | 18 | void addEdge(int src, int dest) { 19 | g[src].push_back(dest); 20 | return; 21 | } 22 | 23 | void shortestDistance(int src) { 24 | int currentDist = 0; 25 | queue q; 26 | q.push(src); 27 | dist[src] = 0; 28 | 29 | while (!q.empty()) { 30 | int cN = q.front(); 31 | for (auto it : g[cN]) { 32 | if (dist[it] == -1) { 33 | dist[it] = dist[cN] + 1; 34 | q.push(it); 35 | } 36 | } 37 | q.pop(); 38 | } 39 | return; 40 | } 41 | 42 | int main() { 43 | initGraph(32); 44 | 45 | addEdge(1, 4); 46 | addEdge(1, 2); 47 | addEdge(2, 4); 48 | addEdge(2, 5); 49 | addEdge(3, 1); 50 | addEdge(3, 6); 51 | addEdge(4, 6); 52 | addEdge(4, 7); 53 | addEdge(5, 7); 54 | addEdge(7, 6); 55 | 56 | shortestDistance(3); 57 | for (int t=1;t<=7;t++) 58 | cout << t << " " << dist[t] << endl; 59 | } 60 | -------------------------------------------------------------------------------- /Graphs/Topological-Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | bool visited[64] = { false }; 6 | vector g[64]; 7 | stack ss; 8 | 9 | /* Topological Sort is a linear ordering of all its vertices such that if H contains an edge (u, v), 10 | * then u appears vefire v in the ordering. 11 | * If a graph is cyclic, then no linear ordering is possible. 12 | */ 13 | 14 | bool allvisited(int vtx) { 15 | for (auto edges: g[vtx]) if (!visited[vtx]) return false; 16 | 17 | return true; 18 | } 19 | 20 | void dfs(int vtx) { 21 | visited[vtx] = true; 22 | 23 | for (auto edge: g[vtx]) { 24 | if (visited[edge]) continue; 25 | 26 | dfs(edge); 27 | } 28 | ss.push(vtx); 29 | } 30 | 31 | int main() { 32 | int n = 4; 33 | g[1].push_back(3); 34 | g[1].push_back(2); 35 | g[3].push_back(4); 36 | 37 | for (int t=1;t 2 | #include 3 | using namespace std; 4 | 5 | class Graph { 6 | public: 7 | int n; 8 | bool *visited; 9 | vector *list; 10 | 11 | Graph(int n) { 12 | this->n = n+1; 13 | this->visited = new bool[this->n]; 14 | this->list = new vector[this->n]; 15 | 16 | memset(this->visited, false, n); 17 | } 18 | 19 | void addEdge(int src, int dest) { 20 | this->list[src].push_back(dest); 21 | return; 22 | } 23 | 24 | void printGraph() { 25 | for (int t=1;t<=n;t++) { 26 | cout << "Node " << t << " : "; 27 | for (auto edge: this->list[t]) { 28 | cout << edge << " "; 29 | } 30 | cout << endl; 31 | } 32 | return; 33 | } 34 | }; 35 | 36 | 37 | -------------------------------------------------------------------------------- /Graphs/Weighted.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Graph { 6 | public: 7 | int n; 8 | bool *visited; 9 | vector > *list; 10 | 11 | Graph(int n) { 12 | this->n = n; 13 | this->visited = new bool[n+1]; 14 | this->list = new vector >[n+1]; 15 | 16 | memset(this->visited, false, n); 17 | } 18 | 19 | void addEdge(int src, int dest, int wt) { 20 | this->list[src].push_back(make_pair(dest, wt)); 21 | return; 22 | } 23 | 24 | void printGraph() { 25 | for (int t=1;t<=this->n;++t) { 26 | cout << "Node " << t << " : "; 27 | for (auto edge: this->list[t]) { 28 | cout << "<" << edge.first << ", " << edge.second << "> "; 29 | } 30 | cout << endl; 31 | } 32 | return; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Graphs/isCyclic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | int visited[64] = { 0 }; 6 | vector g[64]; 7 | 8 | bool dfs(int vtx) { 9 | if (visited[vtx] == 1) return true; 10 | 11 | if (visited[vtx] == 0) { 12 | visited[vtx] = true; 13 | for (auto edge: g[vtx]) { 14 | if (dfs(edge)) return true; 15 | } 16 | } 17 | visited[vtx] = 2; 18 | return false; 19 | } 20 | 21 | int main() { 22 | int n = 2; 23 | g[1].push_back(0); 24 | g[0].push_back(1); 25 | 26 | for (int t=0;t 2 | using namespace std; 3 | 4 | struct hashing 5 | { 6 | int value; 7 | int key; 8 | }; 9 | 10 | 11 | void put(int value, hashing hash[],int n) { 12 | hash[value % n].value = value; 13 | hash[value % n].key = (value % n); 14 | } 15 | 16 | int get(int key, hashing hash[]) { 17 | return hash[key].value; 18 | } 19 | 20 | int main() 21 | { 22 | int n; 23 | 24 | struct hashing hash[n]; 25 | cin >> n; 26 | for (int t=0;t> temp; 32 | cout << get(temp,hash) << endl; 33 | } -------------------------------------------------------------------------------- /Hashing/chainedHash.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Hash 6 | { 7 | public: 8 | int Buckets; 9 | list *Table; 10 | list::iterator i; 11 | Hash(int key) 12 | { 13 | this->Buckets = key; 14 | Table = new list[Buckets]; 15 | } 16 | 17 | int getHash(int key) 18 | { 19 | return key % Buckets; 20 | } 21 | 22 | void insertHash(int key) 23 | { 24 | int index = getHash(key); 25 | cout << index << " "; 26 | Table[index].push_back(key); 27 | } 28 | void displayBuckets() 29 | { 30 | for (int t = 0; t < Buckets; t++) 31 | { 32 | for (auto x : Table[t]) 33 | { 34 | cout << " --> " << x << " "; 35 | } 36 | cout << '\n'; 37 | } 38 | } 39 | void deleteHash(int key) 40 | { 41 | int index = getHash(key); 42 | for (i = Table[index].begin(); i != Table[index].end(); i++) 43 | { 44 | if (*i == key) 45 | { 46 | Table[index].erase(i); 47 | break; 48 | } 49 | } 50 | } 51 | }; 52 | 53 | int main() 54 | { 55 | Hash h(5); 56 | h.insertHash(123); 57 | h.insertHash(312); 58 | h.insertHash(312); 59 | h.insertHash(321); 60 | h.insertHash(321); 61 | h.insertHash(321); 62 | h.insertHash(321); 63 | h.deleteHash(321); 64 | h.deleteHash(321); 65 | h.displayBuckets(); 66 | } -------------------------------------------------------------------------------- /Hashing/indexMapping.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 264 3 | using namespace std; 4 | bool contains[MAX][2]; 5 | 6 | bool checkPresence(int n) { 7 | if (n < 0) 8 | return contains[abs(n)][1]; 9 | else 10 | return contains[n][0]; 11 | } 12 | 13 | void insert(int n) { 14 | if (n < 0) 15 | contains[abs(n)][1] = true; 16 | else 17 | contains[n][0] = true; 18 | } 19 | 20 | int main() { 21 | insert(1); 22 | insert(-3); 23 | 24 | cout << checkPresence(-3); // 1 25 | } 26 | 27 | -------------------------------------------------------------------------------- /Hashing/linearProbing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getHash(int key, int n) 5 | { 6 | return key % n; 7 | } 8 | 9 | int checkFree(int key, int index, int a[]) 10 | { 11 | if (a[index] == NULL) 12 | return index; 13 | 14 | return checkFree(key, index + 1, a); 15 | } 16 | 17 | int main() 18 | { 19 | int n, temp; 20 | cin >> n; 21 | int m = n; 22 | int *a = new int[n]; 23 | while (m--) 24 | { 25 | cin >> temp; 26 | int hash = getHash(temp, n); 27 | int index = checkFree(hash, 0, a); 28 | a[index] = temp; 29 | } 30 | for (int t = 0; t < n; t++) 31 | cout << a[t] << " "; 32 | } -------------------------------------------------------------------------------- /Hashing/tester.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int checkFree(int key, int index, int a[]) 5 | { 6 | if (a[index] == NULL) 7 | return index; 8 | 9 | return checkFree(key, index + 1, a); 10 | } 11 | 12 | int main() 13 | { 14 | int n, t; 15 | cin >> n; 16 | int *a = new int[n]; 17 | a[0] = 123; 18 | a[1] = 123; 19 | a[3] = 123; 20 | cout << checkFree(12, 0, a); 21 | } -------------------------------------------------------------------------------- /Heaps/KLargestElements.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "MaxHeap.h" 3 | using namespace std; 4 | 5 | void printKLargest(Heap *heap, int k) { 6 | int n = heap->currentHeapSize; 7 | buildHeap(heap, n); 8 | for (int t = 0;t 2 | using namespace std; 3 | 4 | struct Heap 5 | { 6 | int *heapArr; 7 | int currentHeapSize; 8 | int maxHeapSize; 9 | }; 10 | 11 | void heapifyDown(Heap *heap, int i, int n) 12 | { 13 | int largest = i; 14 | int left = 2 * i; 15 | int right = 2 * i + 1; 16 | 17 | if (left <= n && heap->heapArr[left] > heap->heapArr[largest]) 18 | largest = left; 19 | 20 | if (right <= n && heap->heapArr[right] > heap->heapArr[largest]) 21 | largest = right; 22 | 23 | if (largest != i) 24 | { 25 | swap(heap->heapArr[i], heap->heapArr[largest]); 26 | heapifyDown(heap, largest, n); 27 | } 28 | return; 29 | } 30 | 31 | void insert(Heap *heap, int key) 32 | { 33 | heap->heapArr[++heap->currentHeapSize] = key; 34 | return; 35 | } 36 | 37 | void buildHeap(Heap *heap, int n) 38 | { 39 | for (int t = n / 2; t >= 1; t--) 40 | { 41 | heapifyDown(heap, t, n); 42 | } 43 | return; 44 | } 45 | 46 | int extractMax(Heap *&heap) 47 | { 48 | int root = heap->heapArr[1]; 49 | 50 | swap(heap->heapArr[1], heap->heapArr[heap->currentHeapSize]); 51 | 52 | heap->currentHeapSize--; 53 | 54 | heapifyDown(heap, 1, heap->currentHeapSize); 55 | return root; 56 | } 57 | 58 | void printHeap(Heap *heap, int n) 59 | { 60 | for (int t = 1; t <= n; t++) 61 | cout << heap->heapArr[t] << " "; 62 | 63 | cout << endl; 64 | return; 65 | } 66 | 67 | void heapSort(Heap *heap) 68 | { 69 | int n = heap->currentHeapSize; 70 | for (int t = 1; t <= n; t++) 71 | { 72 | extractMax(heap); 73 | } 74 | printHeap(heap, n); 75 | return; 76 | } 77 | 78 | Heap *initHeap() 79 | { 80 | Heap *heap = new Heap(); 81 | heap->currentHeapSize = 0; 82 | heap->maxHeapSize = 64; 83 | heap->heapArr = new int[heap->maxHeapSize]; 84 | return heap; 85 | } 86 | 87 | // int main() 88 | // { 89 | // Heap *heap = new Heap(); 90 | // heap->currentHeapSize = 0; 91 | // heap->maxHeapSize = 64; 92 | // heap->heapArr = new int[heap->maxHeapSize]; 93 | 94 | // insert(heap, 1); 95 | // insert(heap, 4); 96 | // insert(heap, 5); 97 | // insert(heap, 90); 98 | // insert(heap, -90); 99 | // insert(heap, -40); 100 | // insert(heap, 3); 101 | 102 | // int size = heap->currentHeapSize; 103 | // buildHeap(heap, size); 104 | 105 | // heapSort(heap); 106 | // } -------------------------------------------------------------------------------- /Heaps/MinHeap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicHeapTemplate.h" 3 | using namespace std; 4 | 5 | void MIN_heapifyUp(Heap *&hp) 6 | { 7 | int index = hp->currentHeapSize; 8 | while (hasParent(index) && (hp->heapArr[index] < hp->heapArr[getParentIndex(index)])) 9 | { 10 | swap(hp->heapArr[getParentIndex(index)], hp->heapArr[index]); 11 | index = getParentIndex(index); 12 | } 13 | return; 14 | } 15 | 16 | void insertKey(Heap *&hp, int key) 17 | { 18 | ensureExtraCapacity(hp); 19 | hp->heapArr[++hp->currentHeapSize] = key; 20 | MIN_heapifyUp(hp); 21 | return; 22 | } 23 | 24 | int main() 25 | { 26 | Heap *hp = new Heap(); 27 | 28 | hp->heapCapacity = 64; 29 | hp->currentHeapSize = 0; 30 | hp->heapArr = new int[hp->currentHeapSize]; 31 | memset(hp->heapArr, INT_MIN, hp->heapCapacity); 32 | hp->heapArr[0] = INT_MIN; 33 | 34 | insertKey(hp, 5); 35 | insertKey(hp, 3); 36 | insertKey(hp, 17); 37 | insertKey(hp, 10); 38 | insertKey(hp, 84); 39 | insertKey(hp, 19); 40 | insertKey(hp, 6); 41 | insertKey(hp, 22); 42 | insertKey(hp, 9); 43 | 44 | printHeap(hp); 45 | } -------------------------------------------------------------------------------- /Heaps/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Heaps/a.out -------------------------------------------------------------------------------- /Heaps/basicHeapTemplate.h: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Heap 5 | { 6 | int *heapArr; 7 | int heapCapacity; 8 | int currentHeapSize; 9 | int shrunkenSize; 10 | }; 11 | 12 | bool hasParent(int index) 13 | { 14 | if (index <= 0) 15 | return false; 16 | 17 | return true; 18 | } 19 | 20 | void ensureExtraCapacity(Heap *hp) 21 | { 22 | if (hp->currentHeapSize >= hp->heapCapacity) 23 | { 24 | hp->heapCapacity = 2 * hp->heapCapacity; 25 | } 26 | return; 27 | } 28 | 29 | int getParentIndex(int childIndex) 30 | { 31 | return (childIndex / 2); 32 | } 33 | 34 | int getLeftChildIndex(Heap *hp, int i) 35 | { 36 | int left = 2 * i; 37 | if (left >= hp->currentHeapSize) 38 | return -1; 39 | 40 | return left; 41 | } 42 | 43 | int getRightChildIndex(Heap *hp, int i) 44 | { 45 | int left = (2 * i) + 1; 46 | if (left >= hp->currentHeapSize) 47 | return -1; 48 | 49 | return left; 50 | } 51 | 52 | bool hasLeftChild(Heap *hp, int index) 53 | { 54 | if (index > hp->currentHeapSize || index <= 0) 55 | return false; 56 | 57 | return (hp->heapArr[2 * index] == INT_MAX) ? false : true; 58 | } 59 | 60 | bool hasRightChild(Heap *hp, int index) 61 | { 62 | if (index > hp->currentHeapSize || index <= 0) 63 | return false; 64 | 65 | return (hp->heapArr[(2 * index) + 1] == INT_MAX) ? false : true; 66 | } 67 | 68 | void printHeap(Heap *hp) 69 | { 70 | cout << endl; 71 | for (int t = 1; t < (hp->currentHeapSize / 2) + 1; t++) 72 | { 73 | cout << hp->heapArr[t] << " -> "; 74 | cout << " Left Child : "; 75 | cout << hp->heapArr[(2 * t)] << '\t'; 76 | 77 | cout << " Right Child : "; 78 | cout << hp->heapArr[(2 * t) + 1] << '\t'; 79 | cout << endl; 80 | } 81 | cout << endl; 82 | return; 83 | } 84 | 85 | void printHeapAsArray(Heap *hp) 86 | { 87 | for (int t = 1; t <= hp->currentHeapSize + hp->shrunkenSize + 1; t++) 88 | cout << hp->heapArr[t] << " "; 89 | 90 | cout << endl; 91 | return; 92 | } -------------------------------------------------------------------------------- /Heaps/combineHeaps.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "MaxHeap.h" 3 | using namespace std; 4 | 5 | void printHeap(Heap *hp) 6 | { 7 | cout << endl; 8 | for (int t = 1; t < (hp->currentHeapSize / 2) + 1; t++) 9 | { 10 | cout << hp->heapArr[t] << " -> "; 11 | cout << " Left Child : "; 12 | cout << hp->heapArr[(2 * t)] << '\t'; 13 | 14 | cout << " Right Child : "; 15 | cout << hp->heapArr[(2 * t) + 1] << '\t'; 16 | cout << endl; 17 | } 18 | cout << endl; 19 | return; 20 | } 21 | 22 | void combineHeaps(Heap *h1, Heap *h2) 23 | { 24 | int n = h2->currentHeapSize; 25 | for (int t=1;t<=n;t++) 26 | { 27 | insert(h1, h2->heapArr[t]); 28 | } 29 | buildHeap(h1, h1->currentHeapSize); 30 | return; 31 | } 32 | 33 | int main() 34 | { 35 | Heap *h1 = initHeap(); 36 | Heap *h2 = initHeap(); 37 | 38 | insert(h1, 50); 39 | insert(h1, 40); 40 | insert(h1, 30); 41 | insert(h1, 20); 42 | insert(h1, 31); 43 | insert(h1, 25); 44 | 45 | insert(h2, 100); 46 | insert(h2, 56); 47 | insert(h2, 80); 48 | insert(h2, 4); 49 | 50 | printHeap(h1); 51 | combineHeaps(h1, h2); 52 | printHeap(h1); 53 | } -------------------------------------------------------------------------------- /Linked-Lists/.gitignore: -------------------------------------------------------------------------------- 1 | /a.out 2 | /a.exe 3 | /.vscode 4 | -------------------------------------------------------------------------------- /Linked-Lists/addNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include "basicActions.hpp" 2 | using namespace std; 3 | 4 | Node *addLists(Node *head1, Node *head2) { 5 | int carry = 0, sum = 0; 6 | // Two Node pointers pointing to each of the list's head. 7 | Node *p = head1, *q = head2; 8 | // New list to store result. 9 | Node *result = nullptr; 10 | 11 | while (p || q) { 12 | sum = 0; 13 | // If 'p' Node exits, add it to sum and move forward. 14 | if (p) { 15 | sum += p->data; 16 | p = p->next; 17 | } 18 | // If 'q' Node exits, add it to sum and move forward. 19 | if (q) { 20 | sum += q->data; 21 | q = q->next; 22 | } 23 | // If there's 'carry', add 'carry' to 'sum' and reset 'carry' to 0. 24 | if (carry != 0) { 25 | sum += carry; 26 | carry = 0; 27 | } 28 | // If 'sum' is greater than or equal to 10, add one to 'carry' and reduce 'sum' by 10. 29 | if (sum >= 10) { 30 | carry = 1; 31 | sum -= 10; 32 | } 33 | // Insert 'sum' to a new list. 34 | insertAtEnd(result, sum); 35 | } 36 | // Return the newly made list. 37 | return result; 38 | } 39 | 40 | int main() { 41 | Node *head1 = nullptr; 42 | Node *head2 = nullptr; 43 | 44 | // 7 -> 5 -> 9 -> 4 -> 6 (Represents 64957) 45 | insertAtEnd(head1, 7); 46 | insertAtEnd(head1, 5); 47 | insertAtEnd(head1, 9); 48 | insertAtEnd(head1, 4); 49 | insertAtEnd(head1, 6); 50 | 51 | // 8 -> 4 (Represents 48) 52 | insertAtEnd(head2, 8); 53 | insertAtEnd(head2, 4); 54 | 55 | head1 = addLists(head1, head2); 56 | 57 | displayNodes(head1); 58 | } 59 | -------------------------------------------------------------------------------- /Linked-Lists/basicActions.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | struct Node { 7 | int data; 8 | Node *next; 9 | Node *point; 10 | }; 11 | 12 | void insertAtEnd(Node *&start, int data) { 13 | Node *temp = new Node(); 14 | Node *p; 15 | p = start; 16 | 17 | if (!start) { 18 | Node *temp = new Node(); 19 | 20 | temp->next = NULL; 21 | temp->data = data; 22 | start = temp; 23 | return; 24 | } else { 25 | while (p->next != NULL) { 26 | p = p->next; 27 | } 28 | p->next = temp; 29 | temp->data = data; 30 | temp->next = NULL; 31 | return; 32 | } 33 | } 34 | 35 | void displayNodes(Node *start) { 36 | Node *p; 37 | p = start; 38 | 39 | while (p != NULL) { 40 | if (p->next != NULL) 41 | cout << p->data << " -> "; 42 | else 43 | cout << p->data; 44 | p = p->next; 45 | } 46 | return; 47 | } 48 | 49 | Node *insertAtStart(Node *start, int data) { 50 | Node *temp = new Node(); 51 | temp = new Node; 52 | 53 | temp->data = data; 54 | temp->next = start; 55 | start = temp; 56 | return start; 57 | } 58 | 59 | Node *findMiddle(Node *start) { 60 | Node *p; 61 | p = start; 62 | int count = 0; 63 | while (p != NULL) { 64 | p = p->next; 65 | count++; 66 | } 67 | int i = 0; 68 | p = start; 69 | while (i != count / 2) { 70 | p = p->next; 71 | i++; 72 | } 73 | return p; 74 | } 75 | 76 | void deleteMiddleElement(Node *start) { 77 | Node *p, *q; 78 | p = start; 79 | int count = 0; 80 | while (p->next != NULL) { 81 | p = p->next; 82 | count++; 83 | } 84 | int i = 0; 85 | p = start; 86 | while (i != count / 2) { 87 | q = p; 88 | p = p->next; 89 | i++; 90 | } 91 | q->next = p->next; 92 | delete p; 93 | } 94 | 95 | void deleteLastElement(Node *start) { 96 | Node *p, *q; 97 | p = start; 98 | 99 | while (p->next != NULL) { 100 | q = p; 101 | p = p->next; 102 | } 103 | delete p; 104 | q->next = NULL; 105 | return; 106 | } 107 | 108 | Node *deleteFirstElement(Node *start) { 109 | Node *p; 110 | p = start->next; 111 | delete start; 112 | start = p; 113 | return start; 114 | } 115 | 116 | int getLength(Node *head) { 117 | Node *p = head; 118 | int count = 0; 119 | while (p->next != NULL) { 120 | count++; 121 | p = p->next; 122 | } 123 | return ++count; 124 | } 125 | -------------------------------------------------------------------------------- /Linked-Lists/deleteKeys.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | /* 6 | Function to Delete Keys. 7 | We can have 3 base cases : 8 | 9 | 1. If the Key is at the Start of the List, Remove Element at Start. 10 | 2. If the Key is at the End of the List, Remove Element at End. 11 | 3. If the Key is somewhere in the middle : 12 | -> Set Prev Node's (q) "next" to Current Node's (p) "next". 13 | -> Delete Current Node. 14 | -> Set Current Node to Prev's "next". 15 | 16 | */ 17 | 18 | Node *deleteKeys(Node *head, int x) 19 | { 20 | Node *p = head, *q = nullptr; 21 | 22 | while (p != nullptr) 23 | { 24 | // Element Found at Last. 25 | if (p->next == nullptr && p->data == x) 26 | { 27 | deleteLastElement(head); 28 | break; 29 | } 30 | // Element Found at Start. 31 | else if (p == head && p->data == x) 32 | { 33 | head = deleteFirstElement(head); 34 | p = head; 35 | q = nullptr; 36 | continue; 37 | } 38 | // Element Found Somewhere else. 39 | else if (p->data == x) 40 | { 41 | q->next = p->next; 42 | delete p; 43 | p = q->next; 44 | continue; 45 | } 46 | // Not Found. 47 | q = p; 48 | p = p->next; 49 | continue; 50 | } 51 | return head; 52 | } 53 | 54 | int main() 55 | { 56 | Node *head = nullptr; 57 | insertAtEnd(head, 4); 58 | insertAtEnd(head, 1); 59 | insertAtEnd(head, 2); 60 | insertAtEnd(head, 3); 61 | insertAtEnd(head, 4); 62 | insertAtEnd(head, 4); 63 | insertAtEnd(head, 5); 64 | insertAtEnd(head, 4); 65 | head = deleteKeys(head, 3); 66 | displayNodes(head); 67 | } 68 | -------------------------------------------------------------------------------- /Linked-Lists/detectLoop.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "unordered_set" 3 | #include "basicActions.h" 4 | using namespace std; 5 | 6 | void createLoop(Node *head) 7 | { 8 | Node *p = head; 9 | 10 | while (p->next != nullptr) 11 | { 12 | p = p->next; 13 | } 14 | p->next = head; 15 | return; 16 | } 17 | 18 | bool detectLoop(Node *head) 19 | { 20 | unordered_set s; 21 | Node *p = head; 22 | 23 | while (p != nullptr) 24 | { 25 | if (s.find(p) != s.end()) 26 | return true; 27 | 28 | s.insert(p); 29 | p = p->next; 30 | } 31 | return false; 32 | } 33 | 34 | int main() 35 | { 36 | Node *head = nullptr; 37 | insertAtEnd(head, 1); 38 | insertAtEnd(head, 2); 39 | insertAtEnd(head, 3); 40 | insertAtEnd(head, 4); 41 | insertAtEnd(head, 5); 42 | 43 | createLoop(head); 44 | 45 | detectLoop(head) ? cout << "Loop Detected.." << '\n' : cout << "No Loop Detected.." << '\n'; 46 | } 47 | -------------------------------------------------------------------------------- /Linked-Lists/difference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | // Driver Function. 6 | Node *findDifference(Node *head1, Node *head2) 7 | { 8 | // Setting two Temporary "Node" Pointers to traverse the lists.. 9 | Node *p = head1, *q = head2, *head; 10 | 11 | // Allocation of Memory for new Node. 12 | Node *temp = new Node(); 13 | 14 | // Setting Node's Data . 15 | temp->data = (p->data) - (q->data); 16 | temp->next = nullptr; 17 | 18 | // Pushing the pointers 'p' and 'q' forward traversing the lists. 19 | p = p->next; 20 | q = q->next; 21 | 22 | // Setting the head Pointer. 23 | head = temp; 24 | 25 | // Traversing Both the lists at the same time. 26 | while (p != nullptr && q != NULL) 27 | { 28 | // Insert the difference of the data elements of two lists at the end. 29 | insertAtEnd(head, (p->data - q->data)); 30 | 31 | // Pushing the pointers forward. 32 | p = p->next; 33 | q = q->next; 34 | } 35 | // returning the head of the Newly made List. 36 | return head; 37 | } 38 | 39 | int main() 40 | { 41 | // Three Heads for three Linked Lists. 42 | Node *head1 = nullptr; 43 | Node *head2 = nullptr; 44 | Node *head = nullptr; 45 | // Creation and Insertion of First List Data Elements. 46 | insertAtEnd(head1, 6); 47 | insertAtEnd(head1, 5); 48 | insertAtEnd(head1, 3); 49 | insertAtEnd(head1, 0); 50 | // Creating and Insertion of Second List Data Elements. 51 | insertAtEnd(head2, 4); 52 | insertAtEnd(head2, 5); 53 | insertAtEnd(head2, 2); 54 | insertAtEnd(head2, 0); 55 | 56 | // Calling the Driver Function. 57 | head = findDifference(head1, head2); 58 | 59 | displayNodes(head); 60 | 61 | } 62 | -------------------------------------------------------------------------------- /Linked-Lists/introToRecursionLL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | Node *recDis(Node *head) 6 | { 7 | if (!head) 8 | return nullptr; 9 | 10 | cout << head->data << " "; 11 | recDis(head->next); 12 | } 13 | 14 | int main() 15 | { 16 | Node *head = nullptr; 17 | insertAtEnd(head, 10); 18 | insertAtEnd(head, 20); 19 | insertAtEnd(head, 30); 20 | insertAtEnd(head, 40); 21 | insertAtEnd(head, 50); 22 | 23 | recDis(head); 24 | } 25 | -------------------------------------------------------------------------------- /Linked-Lists/oddEven.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | Node *oddEven(Node *head) 6 | { 7 | Node *head1 = nullptr, *head2 = NULL, *p = head; 8 | 9 | while (p != nullptr) 10 | { 11 | if (p->data % 2 == 0) 12 | { 13 | insertAtEnd(head1, p->data); 14 | } 15 | else 16 | { 17 | insertAtEnd(head2, p->data); 18 | } 19 | p = p->next; 20 | } 21 | p = head1; 22 | 23 | while (p->next != nullptr) { 24 | p = p->next; 25 | } 26 | 27 | p->next = head2; 28 | 29 | 30 | return head1; 31 | } 32 | 33 | int main() 34 | { 35 | Node *head = nullptr; 36 | insertAtEnd(head, 1); 37 | insertAtEnd(head, 2); 38 | insertAtEnd(head, 3); 39 | insertAtEnd(head, 4); 40 | insertAtEnd(head, 5); 41 | insertAtEnd(head, 6); 42 | insertAtEnd(head, 7); 43 | insertAtEnd(head, 8); 44 | 45 | head = oddEven(head); 46 | displayNodes(head); 47 | } 48 | -------------------------------------------------------------------------------- /Linked-Lists/palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | bool isPalindromeEff(Node *head) { 6 | Node *slowP = head, *fastP = head; 7 | 8 | while (fastP) { 9 | slowP = slowP->next; 10 | fastP = fastP->next->next; 11 | } 12 | Node *checkP = head; 13 | slowP = slowP->next; 14 | // cout << slowP->data << endl; 15 | while (slowP) { 16 | if (checkP->data != slowP->data) 17 | return false; 18 | 19 | slowP = slowP->next; 20 | checkP = checkP->next; 21 | } 22 | return true; 23 | } 24 | 25 | bool isPalindrome(Node *head) { 26 | Node *p = head; 27 | int a[1000000]; 28 | int cnt = 0; 29 | while (p != nullptr) { 30 | a[cnt] = p->data; 31 | cnt++; 32 | p = p->next; 33 | } 34 | int high = cnt - 1; 35 | int low = 0; 36 | while (low < high) { 37 | if (a[low] == a[high]) { 38 | low++; 39 | high--; 40 | continue; 41 | } else 42 | return false; 43 | } 44 | return true; 45 | } 46 | 47 | int main() { 48 | Node *head = nullptr; 49 | 50 | insertAtEnd(head, 1); 51 | insertAtEnd(head, 1); 52 | insertAtEnd(head, 2); 53 | insertAtEnd(head, 2); 54 | insertAtEnd(head, 1); 55 | insertAtEnd(head, 1); 56 | 57 | cout << isPalindromeEff(head) << endl; 58 | } 59 | -------------------------------------------------------------------------------- /Linked-Lists/pointerBasics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // int*** can reference to only type int** 5 | 6 | void pointerParameter(int *p, int **q, int ***r) 7 | { 8 | cout << *p << endl; 9 | cout << **q << endl; 10 | cout << ***r << endl; 11 | } 12 | 13 | int main() 14 | { 15 | int x = 5; 16 | 17 | int *p = &x; 18 | int **q; 19 | int ***r; 20 | 21 | q = &p; 22 | r = &q; 23 | 24 | ***r = 10; 25 | cout << p << endl; // address of 'x'. 26 | cout << *p << endl; // value at 'x'. 27 | 28 | cout << q << endl; // value of 'p' address. 29 | cout << *q << endl; // value of 'x' address. 30 | cout << **q << endl; // value of 'x'. 31 | 32 | cout << r << endl; // value of 'q' address 33 | cout << *r << endl; // value of 'p' address. 34 | cout << **r << endl; // value of 'x' address. 35 | cout << ***r << endl; // value of 'x'. 36 | 37 | pointerParameter(p, q, r); 38 | } -------------------------------------------------------------------------------- /Linked-Lists/pointerBasics2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | Node *next; 8 | Node *store; 9 | }; 10 | 11 | int main() 12 | { 13 | Node *root = NULL, *root2 = NULL; 14 | 15 | int a = 10; 16 | Node *forward[10]; 17 | 18 | // *forward[0]- 19 | forward[0]->store = root; 20 | root->data = 123; 21 | root = root->next; 22 | forward[1]->store = root; 23 | 24 | cout << forward[1]->store << endl; 25 | } -------------------------------------------------------------------------------- /Linked-Lists/pointersCon.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | void deleteWithoutHead(Node *ptr) 6 | { 7 | *ptr = *ptr->next; 8 | } 9 | 10 | int main() 11 | { 12 | Node *head = NULL; 13 | 14 | insertAtEnd(head, 10); 15 | insertAtEnd(head, 20); 16 | insertAtEnd(head, 4); 17 | insertAtEnd(head, 30); 18 | 19 | deleteWithoutHead(head->next); 20 | displayNodes(head); 21 | } -------------------------------------------------------------------------------- /Linked-Lists/reverseFirstKNodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | Node *reverseNodes(Node *head, int k) 6 | { 7 | Node *p, *q, *r, *first; 8 | first = head; 9 | p = head; 10 | q = p->next; 11 | r = q->next; 12 | 13 | while (k != 1) 14 | { 15 | q->next = p; 16 | p = q; 17 | q = r; 18 | r = r->next; 19 | k--; 20 | } 21 | q->next = p; 22 | first->next = r; 23 | head = q; 24 | return head; 25 | } 26 | 27 | int main() 28 | { 29 | Node *head = nullptr; 30 | int k; 31 | 32 | cin >> k; 33 | 34 | insertAtEnd(head, 1); 35 | insertAtEnd(head, 2); 36 | insertAtEnd(head, 3); 37 | insertAtEnd(head, 4); 38 | insertAtEnd(head, 5); 39 | insertAtEnd(head, 6); 40 | insertAtEnd(head, 7); 41 | insertAtEnd(head, 8); 42 | insertAtEnd(head, 9); 43 | 44 | if (k > 1) 45 | { 46 | head = reverseNodes(head, (k - 1)); 47 | displayNodes(head); 48 | } 49 | else 50 | cout << "K must atleast be 2." << '\n'; 51 | } 52 | -------------------------------------------------------------------------------- /Linked-Lists/reverseKPairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "basicActions.h" 4 | using namespace std; 5 | 6 | // Get the Top Most Element of the Next Stack. 7 | Node *getFirstK(Node *head, int k) { 8 | if (!head) return nullptr; 9 | k -= 1; 10 | while (k-- && head->next != nullptr) { 11 | head = head->next; 12 | } 13 | return head; 14 | } 15 | 16 | // Push Elements Into Stack. 17 | stack pushInto(Node *&head, int k, int &rem) { 18 | stack temp; 19 | while (k--) { 20 | temp.push(head); 21 | head = head->next; 22 | rem--; 23 | } 24 | return temp; 25 | } 26 | 27 | // Driver Function. 28 | Node *reverseKPairs(Node *head, int k) { 29 | // No Head, return nullptr. 30 | if (!head) return nullptr; 31 | 32 | stack st; 33 | Node *prev, *temp, *newHead, *top_ = nullptr, *bottom_ = NULL; 34 | bool fst = true; 35 | 36 | // 'rem' is the Original Length of the Linked List. 37 | int cnt = k, rem = getLength(head); 38 | 39 | while (true) { 40 | // If Current Length < k, then stop. (Since, we are reversing in pairs.) 41 | if (rem < k) 42 | break; 43 | 44 | // Push K elements in to Stack and return that Stack. 45 | st = pushInto(head, k, rem); 46 | // Get the Top Most Node of the Upcoming Stack. 47 | top_ = getFirstK(head, k); 48 | // Keep track of Previous Element. (To connect them) 49 | prev = st.top(); 50 | 51 | // If its the First Iteration, the set the Kth Element as the Head of the Modified List. 52 | if (fst) { 53 | newHead = prev; 54 | } 55 | // Pop Element From Stack. (Since, we got our prev element, we start from the next element) 56 | st.pop(); 57 | // Loop until the stack is empty. 58 | while (!st.empty()) { 59 | // Take the Top Element and make it as the 'Next' of the Previous Pointer (prev). (Eg : 2->1, 2 : Prev, 1 : Temp) 60 | temp = st.top(); 61 | st.pop(); 62 | prev->next = temp; 63 | // Make prev as Temp. 64 | prev = temp; 65 | } 66 | // Store the Bottom Element of the Stack. 67 | bottom_ = temp; 68 | // As the First Iteration is completed, we make the first iteration as completed. 69 | if (fst) { 70 | fst = false; 71 | } 72 | // Connect the Bottom Element in the Current Stack to the Top Element in the Next Stack. 73 | bottom_->next = top_; 74 | } 75 | // Connect any remaining elements left. 76 | while (rem--) { 77 | temp->next = head; 78 | temp = head; 79 | head = head->next; 80 | } 81 | 82 | // Return the newHead of the List. 83 | return newHead; 84 | } 85 | 86 | int main() { 87 | Node *head = nullptr; 88 | int k = 5; 89 | 90 | for (int t=1;t<=15;t++) 91 | insertAtEnd(head, t); 92 | 93 | head = reverseKPairs(head, k); 94 | displayNodes(head); 95 | cout << endl; 96 | } 97 | -------------------------------------------------------------------------------- /Linked-Lists/reverseLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | // Function with Return type set to type : " Node * " 6 | Node *reverseLL(Node *head) 7 | { 8 | // Three Pointers. 9 | Node *p, *q, *r; 10 | // 'p' set to head. 11 | p = head; 12 | // 'q' set next of p. 13 | q = p->next; 14 | // 'r' set next of q. 15 | r = q->next; 16 | 17 | // Iterating till 'r' is not nullptr. 18 | while (r != nullptr) 19 | { 20 | // Setting next of 'q' to previous node (p). 21 | q->next = p; 22 | // Setting Prev Node to Current Node. ('p' to 'q'). 23 | p = q; 24 | // Setting Current Node to Next Node. ('q' to 'r'). 25 | q = r; 26 | // Pushing Next Node Forward. 27 | r = r->next; 28 | } 29 | // When out of the loop, still 'q' is not connected to p.. So, we connect them. 30 | q->next = p; 31 | // Since the end of the List should be set to nullptr. 32 | p = head; 33 | p->next = nullptr; 34 | 35 | // New 'head' is set to q. 36 | head = q; 37 | 38 | // Then, we return Head Pointer. 39 | return head; 40 | } 41 | 42 | int main() 43 | { 44 | Node *head = nullptr; 45 | insertAtEnd(head, 1); 46 | insertAtEnd(head, 2); 47 | insertAtEnd(head, 3); 48 | insertAtEnd(head, 4); 49 | insertAtEnd(head, 5); 50 | cout << '\n'; 51 | cout << "Before Reversing.." << '\n'; 52 | // Display Linked List. 53 | displayNodes(head); 54 | 55 | cout << '\n'; 56 | 57 | // Calling Driver Function. 58 | head = reverseLL(head); 59 | 60 | cout << "After Reversing.." << '\n'; 61 | 62 | // Display Linked List. 63 | displayNodes(head); 64 | 65 | cout << '\n'; 66 | } 67 | -------------------------------------------------------------------------------- /Linked-Lists/single.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct node 5 | { 6 | int data; 7 | node *next; 8 | }; 9 | 10 | node *createNode(struct node *start, int data) 11 | { 12 | struct node *temp; 13 | temp = new node; 14 | 15 | temp->next = NULL; 16 | temp->data = data; 17 | start = temp; 18 | return start; 19 | } 20 | 21 | insertNodeAtEnd(struct node *start, int data) { 22 | struct node *temp; 23 | temp = new node; 24 | node *p; 25 | p = start; 26 | 27 | while (p->next != NULL) 28 | { 29 | p = p->next; 30 | } 31 | p->next = temp; 32 | temp->data = data; 33 | temp->next = NULL; 34 | } 35 | 36 | void displayNodes(struct node *start) 37 | { 38 | node *p; 39 | p = start; 40 | 41 | while (p->next != NULL) 42 | { 43 | cout << p->data << " -> "; 44 | p = p->next; 45 | } 46 | cout << p->data << endl; 47 | } 48 | 49 | node *insertAtStart(struct node *start, int data) 50 | { 51 | struct node *temp; 52 | 53 | temp = new node; 54 | 55 | temp->data = data; 56 | temp->next = start; 57 | start = temp; 58 | return start; 59 | } 60 | 61 | int findMiddle(struct node *start) 62 | { 63 | node *p; 64 | p = start; 65 | int count = 0; 66 | while (p->next != NULL) 67 | { 68 | p = p->next; 69 | count++; 70 | } 71 | int i = 0; 72 | p = start; 73 | while (i != count / 2) 74 | { 75 | p = p->next; 76 | i++; 77 | } 78 | return p->data; 79 | } 80 | 81 | void deleteMiddleElement(struct node *start) 82 | { 83 | node *p, *q; 84 | p = start; 85 | int count = 0; 86 | while (p->next != NULL) 87 | { 88 | p = p->next; 89 | count++; 90 | } 91 | int i = 0; 92 | p = start; 93 | while (i != count / 2) 94 | { 95 | q = p; 96 | p = p->next; 97 | i++; 98 | } 99 | q->next = p->next; 100 | delete p; 101 | } 102 | 103 | void deleteLastElement(struct node *start) 104 | { 105 | node *p, *q; 106 | p = start; 107 | 108 | while (p->next != NULL) 109 | { 110 | q = p; 111 | p = p->next; 112 | } 113 | delete p; 114 | q->next = NULL; 115 | cout << "Last Element Deleted!!" << endl; 116 | return; 117 | } 118 | 119 | node *deleteFirstElement(struct node *start) 120 | { 121 | node *p; 122 | p = start->next; 123 | delete start; 124 | start = p; 125 | cout << "First Element Deleted!!" << endl; 126 | return start; 127 | } 128 | 129 | void createLoop(struct node *start,int n) { 130 | node *p,*q; 131 | p=start; 132 | q=start; 133 | while(p->next != NULL) { 134 | p = p->next; 135 | } 136 | while (n--) { 137 | q = q->next; 138 | } 139 | p->next = q; 140 | } 141 | 142 | int findLoop(struct node *start) { 143 | node *p,*q; 144 | int flag=0; 145 | p = start; 146 | q = start; 147 | while (q->next && p && q) { 148 | p=p->next; 149 | q = q->next->next; 150 | if (p == q) { 151 | flag=1; 152 | break; 153 | } 154 | } 155 | if (flag) { 156 | p = start; 157 | while (p!=q) { 158 | p = p->next; 159 | q = q->next; 160 | } 161 | return p->data; 162 | } 163 | return 0; 164 | } 165 | 166 | node *reverseList(struct node *start) { 167 | node *prv,*nxt,*cur; 168 | cur = NULL; 169 | nxt = NULL; 170 | 171 | while (start) { 172 | nxt = start->next; 173 | start->next = cur; 174 | cur = start; 175 | start = nxt; 176 | } 177 | return cur; 178 | } 179 | 180 | int main() 181 | { 182 | node *start; 183 | start = NULL; 184 | 185 | insertNodeAtEnd(start, 9); 186 | insertNodeAtEnd(start, 91); 187 | insertNodeAtEnd(start, 41); 188 | insertNodeAtEnd(start, 67); 189 | insertNodeAtEnd(start, 123); 190 | insertNodeAtEnd(start, 3232); 191 | start = insertAtStart(start, 3412); 192 | displayNodes(start); 193 | 194 | cout << endl; 195 | 196 | start = reverseList(start); 197 | cout << endl; 198 | displayNodes(start); 199 | cout << endl; 200 | } 201 | -------------------------------------------------------------------------------- /Linked-Lists/skipList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | // Skip 'n' number of Nodes. 6 | Node *doSkips(Node *head, int skips) 7 | { 8 | Node *p = head; 9 | while (skips > 1) 10 | { 11 | p = p->next; 12 | skips--; 13 | } 14 | return p; 15 | } 16 | 17 | /* 18 | Node Structure : 19 | 20 | struct Node { 21 | int data; // Holds data of the Node. 22 | Node *next; // Next Node Pointer. 23 | Node *point; // Points to the Inner Node .. This pointer is used in *express pointer. 24 | 25 | }; 26 | 27 | ----------------------------------------------------------------------------------------------------------------------------- 28 | 29 | Building a Skip List. 30 | Step 1 : Start at head node. 31 | Step 2 : Push the Node's Data into express's "data" field. 32 | Step 3 : Push the Node's Address into express's "point" field. 33 | Step 4 : Skip 'n' Nodes. 34 | Step 5 : Repeat the process till the current node is not nullptr. 35 | 36 | */ 37 | 38 | Node *createSkipList(Node *head) 39 | { 40 | // ExpressWay Pointer. 41 | Node *express = nullptr; 42 | Node *p = head; 43 | Node *temp = nullptr; 44 | int skips = 5; 45 | 46 | // Push the first Node's "data" and "address" into the express pointer's field. 47 | if (p) 48 | { 49 | insertAtEnd(express, p->data); 50 | express->point = p; 51 | temp = express; 52 | } 53 | 54 | int count = 0; 55 | int len = getLength(head); 56 | while (count < len - 1) 57 | { 58 | count += skips + 1; 59 | // Do 'n' skips. 60 | p = doSkips(p, skips); 61 | 62 | // If there is a current node, then addd its "data" and "address" into express's fields. (address is pushed into the "point" field) 63 | if (p) 64 | { 65 | insertAtEnd(express, p->data); 66 | express = express->next; 67 | express->point = p; 68 | } 69 | } 70 | // Point the express pointer to the start of the newly made Express List. 71 | express = temp; 72 | 73 | // Return the Express List. 74 | return express; 75 | } 76 | 77 | void searchViaExpress(Node *head, int target) 78 | { 79 | if (!head) 80 | return; 81 | 82 | Node *p = head; 83 | 84 | while (p->next != nullptr) 85 | { 86 | // If Data is found, then return. 87 | if (p->data == target) 88 | { 89 | cout << "Target : " << p->data << '\n'; 90 | cout << "Target Found at Address : " << p << '\n'; 91 | return; 92 | } 93 | 94 | // If the Current Node's next Node's data is greater than Target value, then jump into the "point" address which means that our data is in this parition. 95 | if (p->next->data > target) 96 | p = p->point; 97 | 98 | // Else, just go to the next node. 99 | if (p->next->data < target) 100 | p = p->next; 101 | } 102 | 103 | // For the Last Node, we just get into the "point" field of the last node and search for the element. 104 | p = p->point; 105 | while (p != nullptr) 106 | { 107 | if (p->data == target) 108 | { 109 | cout << "Target : " << p->data << '\n'; 110 | cout << "Target Found at Address : " << p << '\n'; 111 | return; 112 | } 113 | p = p->next; 114 | } 115 | cout << "Element Not Found.." << '\n'; 116 | return; 117 | } 118 | 119 | int main() 120 | { 121 | Node *head = nullptr; 122 | Node *expressHead = nullptr; 123 | 124 | insertAtEnd(head, 10); 125 | insertAtEnd(head, 20); 126 | insertAtEnd(head, 22); 127 | insertAtEnd(head, 23); 128 | insertAtEnd(head, 27); 129 | insertAtEnd(head, 30); 130 | insertAtEnd(head, 43); 131 | insertAtEnd(head, 45); 132 | insertAtEnd(head, 50); 133 | insertAtEnd(head, 54); 134 | insertAtEnd(head, 57); 135 | insertAtEnd(head, 58); 136 | insertAtEnd(head, 62); 137 | insertAtEnd(head, 65); 138 | insertAtEnd(head, 67); 139 | 140 | int target; 141 | cout << "Enter Target Element : "; 142 | cin >> target; 143 | 144 | expressHead = createSkipList(head); 145 | searchViaExpress(expressHead, target); 146 | } 147 | -------------------------------------------------------------------------------- /Linked-Lists/sum0s.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | Node *sum0(Node *head) 6 | { 7 | int sum = 0; 8 | Node *prev = head, *temp = head, *res = head; 9 | 10 | while (temp->next != nullptr) 11 | { 12 | while (temp->data != 0 && temp->next) 13 | { 14 | sum += temp->data; 15 | temp = temp->next; 16 | } 17 | if (temp->next) 18 | { 19 | prev->data = sum; 20 | prev->next = temp->next; 21 | prev = temp->next; 22 | temp = prev; 23 | sum = 0; 24 | } 25 | } 26 | if (temp->data == 0 && !temp->next) { 27 | prev->data = sum; 28 | prev->next = temp->next; 29 | prev = temp->next; 30 | } 31 | return res; 32 | } 33 | 34 | int main() 35 | { 36 | Node *head = nullptr; 37 | 38 | insertAtEnd(head, 1); 39 | insertAtEnd(head, 2); 40 | insertAtEnd(head, 3); 41 | insertAtEnd(head, 0); 42 | insertAtEnd(head, 5); 43 | insertAtEnd(head, 4); 44 | insertAtEnd(head, 0); 45 | insertAtEnd(head, 3); 46 | insertAtEnd(head, 2); 47 | insertAtEnd(head, 0); 48 | insertAtEnd(head, 0); 49 | insertAtEnd(head, 0); 50 | insertAtEnd(head, 0); 51 | 52 | 53 | head = sum0(head); 54 | displayNodes(head); 55 | } 56 | -------------------------------------------------------------------------------- /Linked-Lists/sumOfNode0s.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | Node *sum0s(Node *head) 6 | { 7 | Node *temp = nullptr; 8 | Node *p = head; 9 | int sum = 0; 10 | while (p != nullptr) 11 | { 12 | if (p->data == 0) 13 | { 14 | insertAtEnd(temp, sum); 15 | sum = 0; 16 | p = p->next; 17 | continue; 18 | } 19 | sum += p->data; 20 | p = p->next; 21 | continue; 22 | } 23 | return temp; 24 | } 25 | 26 | int main() 27 | { 28 | Node *head = nullptr; 29 | 30 | insertAtEnd(head, 1); 31 | insertAtEnd(head, 2); 32 | insertAtEnd(head, 3); 33 | insertAtEnd(head, 4); 34 | insertAtEnd(head, 0); 35 | insertAtEnd(head, 5); 36 | insertAtEnd(head, 4); 37 | insertAtEnd(head, 0); 38 | insertAtEnd(head, 3); 39 | insertAtEnd(head, 2); 40 | insertAtEnd(head, 0); 41 | 42 | head = sum0s(head); 43 | displayNodes(head); 44 | } 45 | -------------------------------------------------------------------------------- /Linked-Lists/swapPairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicActions.h" 3 | using namespace std; 4 | 5 | Node *swapPairs(Node *head) 6 | { 7 | // Pointers of type "Node" to traverse through the list. 8 | Node *p, *q; 9 | // Temporary variable to swap Node's data. 10 | int temp; 11 | // Setting the Pointer 'p' to the head of the list. 12 | p = head; 13 | // Setting the Pointer 'q' to the 'next' node to that of 'p'. 14 | q = p->next; 15 | 16 | // Loop till both pointers have valid Node. (NOT nullptr) 17 | while (p != nullptr && q != NULL) 18 | { 19 | // Swapping Node's Data. 20 | temp = p->data; 21 | p->data = q->data; 22 | q->data = temp; 23 | 24 | // Pushing Pointer forward. 25 | p = q->next; 26 | q = p->next; 27 | } 28 | // Returning the head of the List. 29 | return head; 30 | } 31 | 32 | int main() 33 | { 34 | Node *head = nullptr; 35 | insertAtEnd(head, 1); 36 | insertAtEnd(head, 2); 37 | insertAtEnd(head, 3); 38 | insertAtEnd(head, 4); 39 | insertAtEnd(head, 5); 40 | insertAtEnd(head, 6); 41 | insertAtEnd(head, 7); 42 | 43 | head = swapPairs(head); 44 | 45 | displayNodes(head); 46 | } 47 | -------------------------------------------------------------------------------- /Palindromic-Tree/README.md: -------------------------------------------------------------------------------- 1 | ``` Palindromic Tree for O(n) String Operations! ``` 2 | -------------------------------------------------------------------------------- /Palindromic-Tree/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Palindromic-Tree/a.out -------------------------------------------------------------------------------- /Palindromic-Tree/palindromic-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | const int N = 1e5+10; 5 | int tree[N][26], idx; 6 | int len[N], link[N], t; 7 | char s[N]; 8 | 9 | void extend(int p) { 10 | while (s[p - len[t] - 1] != s[p]) t = link[t]; 11 | int x = link[t], c = s[p] - 'a'; 12 | while (s[p - len[x] - 1] != s[p]) x = link[x]; 13 | if (!tree[t][c]) { 14 | tree[t][c] = ++idx; 15 | len[idx] = len[t] + 2; 16 | link[idx] = len[idx] == 1 ? 2 : tree[x][c]; 17 | } t = tree[t][c]; 18 | } 19 | 20 | int main() { 21 | len[1] = -1, link[1] = 1; 22 | len[2] = 0, link[2] = 1; 23 | idx = t = 2; 24 | 25 | cin >> s; 26 | int n = strlen(s); 27 | for (int t=0;tdata = arr[st]; 7 | return; 8 | } 9 | int mid = (st + ed) / 2; 10 | N->left = new Node(nullptr, nullptr, 0); 11 | N->right = new Node(nullptr, nullptr, 0); 12 | 13 | Build(N->left, st, mid); 14 | Build(N->right, mid+1, ed); 15 | N->data = min(N->left->data, N->right->data); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Persistant-Segment-Tree/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Persistant-Segment-Tree/README.md -------------------------------------------------------------------------------- /Persistant-Segment-Tree/Src.cpp: -------------------------------------------------------------------------------- 1 | int arr[] = {1, 2, 3, 4, 5}; 2 | int n = sizeof(arr)/sizeof(arr[0]); 3 | 4 | #include 5 | #include "Build.hpp" 6 | #include "Structure.hpp" 7 | #include "Upgrade.hpp" 8 | #define HIGH 264 9 | 10 | int main() { 11 | int a[HIGH]; 12 | for (int t=0;tleft); 5 | cout << root->data << " "; 6 | printTree(root->right); 7 | } 8 | int Query(Node *N, int st, int ed, int Qst, int Qed) { 9 | if (Qst > ed || Qed < st || st > ed) 10 | return 0; 11 | if (Qst >= st && Qed <= ed) 12 | return N->data; 13 | 14 | int mid = (st + ed) / 2; 15 | return min(Query(N->left, st, mid, Qst, Qed), Query(N->right, mid+1, ed, Qst, Qed)); 16 | } 17 | 18 | void Upgrade(Node *prevVersion, Node *currentVersion, int st, int ed, int in, int value) { 19 | if (st == ed) { 20 | currentVersion->data = value; 21 | return; 22 | } 23 | int mid = (st + ed) / 2; 24 | if (in <= mid) { 25 | currentVersion->right = prevVersion->right; 26 | 27 | currentVersion->left = new Node(nullptr, nullptr, 0); 28 | Upgrade(prevVersion, currentVersion->left, st, mid, in, value); 29 | } else { 30 | currentVersion->left = prevVersion->left; 31 | 32 | currentVersion->right = new Node(nullptr, nullptr, 0); 33 | Upgrade(prevVersion, currentVersion->right, mid+1, ed, in, value); 34 | } 35 | // currentVersion->data = currentVersion->left->data + currentVersion->right->data; 36 | 37 | currentVersion->data = min(currentVersion->left->data, currentVersion->right->data); 38 | } 39 | -------------------------------------------------------------------------------- /Persistant-Segment-Tree/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Persistant-Segment-Tree/a.out -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structures. 2 | 3 | ### 1. [Trees](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree) 4 | 5 | - [Basic Functions Header File.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/basicTreeTemplate.h) 6 | - [Inorder Iterative](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/inorderIterative.cpp) 7 | - [Number of Full Nodes.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/fullNodes.cpp) 8 | - [Height of a Tree.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/heightOfATree.cpp) 9 | - [Is Given Tree a BST ?](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/isBST2.cpp) 10 | - [Are Two Trees Isomorphic ?](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/isomorphicOrNot.cpp) 11 | - [Number of Leaf Nodes.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/leafNodesCount.cpp) 12 | - [Least Common Ancestor.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/leastCommonAncestor.cpp) 13 | - [Sum of Left Sub-Tree.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/leftSubTreeSum.cpp) 14 | - [Sum of Right Sub-Tree.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/rightSubTreeSum.cpp) 15 | - [Sum of Left Leaf Nodes.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Tree/leftLeavesSum.cpp) 16 | - [Path with Maximum Sum.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/maxSumPath.cpp) 17 | - [Print the Mirror of the Tree.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/mirrorTree.cpp) 18 | - [Print Nodes At Distance K from Root.](https://github.com/manosriram/Data-Structures/blob/master/trees/nodesAtDistanceK.cpp) 19 | - [Zig Zag Traversal](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/zigZagTraversal.cpp) 20 | - [Vertical Sum of Nodes.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/verticalSum.cpp) 21 | - [Kth Largest Element in a BST.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/kthLargestElement.cpp) 22 | - [Second Largest Element in a BST.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/secondLargest.cpp) 23 | - [Odd Even Level Difference](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Search_Tree/oddEvenLevelDifference.cpp) 24 | - [Boundary Traversal Iterative](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Tree/boundaryTraversal.cpp) 25 | - [Boundary Traversal Recursive](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Tree/boundaryTraversalRecursive.cpp) 26 | - [Populate Right Pointers](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Tree/populateRightPointers.cpp) 27 | - [Shortest Leaf Path.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Tree/shortestRootToLeafPath.cpp) 28 | - [Boundary Traversal Recursive](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Tree/boundaryTraversalRecursive.cpp) 29 | - [Boundary Traversal Iterative](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Tree/boundaryTraversal.cpp) 30 | - [Nodes at a Distance D from Target Node](https://github.com/manosriram/Data-Structures/blob/master/Trees/Binary_Tree/nodesAtDistanceD.cpp) 31 | - [Build Segment Tree.](https://github.com/manosriram/Data-Structures/blob/master/Trees/Segment_Trees/BuildHelper.h) 32 | - [BTree Node Structure.](https://github.com/manosriram/Data-Structures/blob/master/Trees/BTrees/NodeStructure.hpp) 33 | - [BTree Basic Functions Template.](https://github.com/manosriram/Data-Structures/blob/master/Trees/BTrees/basicTemplate.cpp) 34 | - [Implementation of Radix Tree.](https://github.com/manosriram/Radix-Tree) 35 | 36 | 37 | ### 2. [Graphs](https://github.com/manosriram/Data-Structures/blob/master/Graphs) 38 | 39 | - [Intro.](https://github.com/manosriram/Data-Structures/blob/master/Graphs/Intro.hpp) 40 | - [BFS Traversal](https://github.com/manosriram/Data-Structures/blob/master/Graphs/BFS.cpp) 41 | - [DFS Traversal](https://github.com/manosriram/Data-Structures/blob/master/Graphs/DFS.cpp) 42 | - [Weighted Graph](https://github.com/manosriram/Data-Structures/blob/master/Graphs/weightedGraph.cpp) 43 | - [No of Ways to reach From Source to Destination](https://github.com/manosriram/Data-Structures/blob/master/Graphs/noOfWays.cpp) 44 | - [Remove Nodes Less than K](https://github.com/manosriram/Data-Structures/blob/master/Graphs/removeLessK.cpp) 45 | 46 | ### 3. [Linked Lists](https://github.com/manosriram/Data-Structures/blob/master/linkedLists) 47 | 48 | - [Basic Linked List Function Header File.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/basicActions.h) 49 | - [Swap Pairs.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/swapPairs.cpp) 50 | - [Difference in Two Linked Lists.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/difference.cpp) 51 | - [Detect and Remove Loop.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/detectLoop.cpp) 52 | - [Reverse a Linked List.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/reverseLinkedList.cpp) 53 | - [Remove Node without Head Pointer.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/pointersCon.cpp) 54 | - [Reverse First K Nodes.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/reverseFirstKNodes.cpp) 55 | - [Even Odd Nodes.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/oddEven.cpp) 56 | - [Skip List.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/skipList.cpp) 57 | - [Delete Key.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/deleteKeys.cpp) 58 | - [Sum of 0's Nodes.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/sumOfNode0s.cpp) 59 | - [Palindrome or Not.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/palindrome.cpp) 60 | - [Reverse K Node Pairs.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/reverseKPairs.cpp) 61 | - [Add Two Lists.](https://github.com/manosriram/Data-Structures/blob/master/linkedLists/addNumbers.cpp) 62 | 63 | 64 | ### 4. [Trie](https://github.com/manosriram/Data-Structures/blob/master/Trie) 65 | - [Basic Trie Template.](https://github.com/manosriram/Data-Structures/blob/master/Trie/BaseTemplate.h) 66 | - [Search Word in a Trie.](https://github.com/manosriram/Data-Structures/blob/master/Trie/searchWord.cpp) 67 | - [Count Frequency of Words.](https://github.com/manosriram/Data-Structures/blob/master/Trie/maxFreq.cpp) 68 | - [Count Number of Words with given Prefix.](https://github.com/manosriram/Data-Structures/blob/master/Trie/countStrings.cpp) 69 | - [Replace String](https://github.com/manosriram/Data-Structures/blob/master/LeetCode/replaceString.cpp) 70 | 71 | 72 | ### 5. [Heaps](https://github.com/manosriram/Data-Structures/blob/master/Heaps) 73 | - [Basic Functions.](https://github.com/manosriram/Data-Structures/blob/master/Heaps/basicHeapTemplate.h) 74 | - [Max Heap](https://github.com/manosriram/Data-Structures/blob/master/Heaps/MaxHeap.h) 75 | - [Min Heap.](https://github.com/manosriram/Data-Structures/blob/master/Heaps/MinHeap.cpp) 76 | - [K Largest Elements.](https://github.com/manosriram/Data-Structures/blob/master/Heaps/KLargestElements.cpp) 77 | 78 | ### 6. [Hashing Techniques](https://github.com/manosriram/Data-Structures/blob/master/Hashing) 79 | 80 | - [Basic Hash.](https://github.com/manosriram/Data-Structures/blob/master/Hashing/basicHash.cpp) 81 | - [Basic Hashing using STL.](https://github.com/manosriram/Data-Structures/blob/master/Topics/hashTable/hashTable.h) 82 | - [Chained Hashing.](https://github.com/manosriram/Data-Structures/blob/master/Hashing/chainedHash.cpp) 83 | - [Linear Probing.](https://github.com/manosriram/Data-Structures/blob/master/Hashing/linearProbing.cpp) 84 | - [Check Free Index and Place.](https://github.com/manosriram/Data-Structures/blob/master/Hashing/tester.cpp) 85 | 86 | ### 7. [Bloom Filter](https://github.com/manosriram/Data-Structures/blob/master/Bloom-Filter) 87 | - [Hash Functions.](https://github.com/manosriram/Data-Structures/blob/master/Bloom-Filter/HashFunctions.hpp) 88 | - [Insertion,](https://github.com/manosriram/Data-Structures/blob/master/Bloom-Filter/Insert.hpp) 89 | - [Check Word Presence.](https://github.com/manosriram/Data-Structures/blob/master/Bloom-Filter/Check.hpp) 90 | - [Driver File.](https://github.com/manosriram/Data-Structures/blob/master/Bloom-Filter/src.hpp) 91 | 92 | ### 7. [Queue](https://github.com/manosriram/Data-Structures/tree/master/queue) 93 | - [Basic Queue Function Header File.](https://github.com/manosriram/Data-Structures/blob/master/queue/basicActions.h) 94 | - [Queue with linked list implementation.](https://github.com/manosriram/Data-Structures/blob/master/queue/queues_LL.cpp) 95 | - [Priority Queue.](https://github.com/manosriram/Data-Structures/blob/master/queue/priority_queue.cpp) 96 | 97 | ### 8. [Stack](https://github.com/manosriram/Data-Structures/blob/master/stacks) 98 | - [Basic Stack Function Header File.](https://github.com/manosriram/Data-Structures/tree/master/stacks/basicActions.h) 99 | - [Reverse Words in a String.](https://github.com/manosriram/Data-Structures/blob/master/stacks/reverseString.cpp) 100 | 101 | ### 9. [Segment Tree](https://github.com/manosriram/Data-Structures/tree/master/Segment-Tree) 102 | - [Build Tree.](https://github.com/manosriram/Data-Structures/blob/master/Segment-Tree/buildTree.hpp) 103 | - [Min-Range Query.](https://github.com/manosriram/Data-Structures/blob/master/Segment-Tree/minRangeQuery.cpp) 104 | - [Max-Range Query.](https://github.com/manosriram/Data-Structures/blob/master/Segment-Tree/maxRangeQuery.cpp) 105 | 106 | ### 10. [Disjoint Sets](https://github.com/manosriram/Data-Structures/tree/master/Disjoint-Sets) 107 | - [Naive](https://github.com/manosriram/Data-Structures/blob/master/Disjoint-Sets/Naive.cpp) 108 | - [Compressed](https://github.com/manosriram/Data-Structures/blob/master/Disjoint-Sets/Compressed.cpp) 109 | 110 | ### 11. [XOR Linked List](https://github.com/manosriram/Data-Structures/tree/master/XOR-Linked-List) 111 | - [Driver File](https://github.com/manosriram/Data-Structures/blob/master/XOR-Linked-List/Src.cpp) 112 | - [Node Structure](https://github.com/manosriram/Data-Structures/blob/master/XOR-Linked-List/Structure.hpp) 113 | -------------------------------------------------------------------------------- /Segment-Tree/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Segment-Tree/.DS_Store -------------------------------------------------------------------------------- /Segment-Tree/Lazy-Propogation/BuildTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX_ 1000 3 | using namespace std; 4 | int tree[MAX_], lazy[MAX_] = {0}; 5 | 6 | // Update using Lazy Propagation. 7 | void lazyUpdate(int *arr, int st, int ed, int qs, int qe, int in, int diff) { 8 | if (lazy[in] != 0) { // If there's some update to be done. 9 | tree[in] += lazy[in]; 10 | 11 | if (st != ed) { // If the node isn't a Leaf Node, then propagate the update value to it's children. 12 | lazy[2 * in] += diff; 13 | lazy[(2*in) + 1] += diff; 14 | } 15 | lazy[in] = 0; 16 | } 17 | // If out-of-range, return/ 18 | if (st > qe || ed < qs) 19 | return; 20 | 21 | // If there's a complete overlap, then add the update value to the current node. 22 | if (st >= qs && ed <= qe) { 23 | tree[in] += diff; 24 | 25 | if (st != ed) { // If the node isn't a Leaf Node, then propagate the update value to it's children. 26 | lazy[2 * in] += diff; 27 | lazy[(2 * in) + 1] += diff; 28 | } 29 | return; 30 | } 31 | // If there's an Partial overlap, Recur for children. 32 | int mid = (st + ed)/2; 33 | lazyUpdate(arr, st, mid, qs, qe, 2 * in, diff); 34 | lazyUpdate(arr, mid+1, ed, qs, qe, (2 * in) + 1, diff); 35 | 36 | // Current Node value is equal to minimum of it's children's Node value. 37 | tree[in] = min(tree[2 * in], tree[(2 * in) + 1]); 38 | } 39 | 40 | int rangeQuery(int *arr, int st, int ed, int qs, int qe, int in) { 41 | if (st >= qs && ed <= qe) 42 | return tree[in]; 43 | 44 | if (st > qe || ed < qs) 45 | return INT_MAX; 46 | 47 | int mid = (st + ed)/2; 48 | 49 | return min( 50 | rangeQuery(arr, st, mid, qs, qe, 2 * in), 51 | rangeQuery(arr, mid+1, ed, qs, qe, (2 * in) + 1) 52 | ); 53 | } 54 | 55 | void constructTree(int *arr, int st, int ed, int ind) { 56 | if (st > ed) 57 | return; 58 | 59 | if (st == ed) { 60 | tree[ind] = arr[st]; 61 | return; 62 | } 63 | 64 | int mid = (st + ed) / 2; 65 | constructTree(arr, st, mid, (2 * ind)); 66 | constructTree(arr, mid+1, ed, (2 * ind) + 1); 67 | 68 | tree[ind] = min(tree[2 * ind], tree[(2 * ind) + 1]); 69 | } 70 | 71 | int main() { 72 | int arr[] = {1, 3, 5, 7, 9, 11}; 73 | int n = sizeof(arr)/sizeof(arr[0]); 74 | 75 | constructTree(arr, 0, n-1, 1); 76 | 77 | for (int t=1;t<=2*n;++t) 78 | cout << tree[t] << " "; 79 | 80 | lazyUpdate(arr, 0, n-1, 2, 3, 1, 3); 81 | cout << endl; 82 | 83 | cout << rangeQuery(arr, 0, n-1, 2, 4, 1) << endl; 84 | } 85 | -------------------------------------------------------------------------------- /Segment-Tree/Lazy-Propogation/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Segment-Tree/Lazy-Propogation/a.out -------------------------------------------------------------------------------- /Segment-Tree/Problems/CF197D.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | static int ht = INT_MIN; 5 | 6 | void Update(int *tree, int cI, int level) { 7 | if (cI == 0) 8 | return; 9 | 10 | if (level % 2 != 0) 11 | tree[cI] = tree[2 * cI] | tree[2 * cI + 1]; 12 | else 13 | tree[cI] = tree[2 * cI] ^ tree[2 * cI + 1]; 14 | 15 | Update(tree, cI/2, level-1); 16 | } 17 | 18 | void buildTree(int *tree, int a[], int st, int ed, int treeNode, int level) { 19 | if (st == ed) { 20 | tree[treeNode] = a[st]; 21 | return; 22 | } 23 | 24 | int mid = (st + ed) / 2; 25 | buildTree(tree, a, st, mid, 2 * treeNode, level+1); 26 | buildTree(tree, a, mid+1, ed, 2 * treeNode + 1, level+1); 27 | if (level > ht) 28 | ht = level; 29 | if (level % 2 == 0) 30 | tree[treeNode] = tree[2 * treeNode] | tree[2 * treeNode + 1]; 31 | else 32 | tree[treeNode] = tree[2 * treeNode] ^ tree[2 * treeNode + 1]; 33 | } 34 | 35 | int main() { 36 | int n, q; 37 | cin >> n >> q; 38 | n = pow(2, n); 39 | int a[n]; 40 | for (int t=0;t> a[t]; 42 | 43 | int *tree = new int[(2 * n) + 1]; 44 | buildTree(tree, a, 0, n-1, 1, 0); 45 | 46 | int hght = ht; 47 | int p, b; 48 | for (int t=0;t> p >> b; 51 | --p; 52 | int in = n + p; 53 | tree[in] = b; 54 | Update(tree, (in)/2, ht); 55 | 56 | cout << tree[1] << '\n'; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Segment-Tree/Problems/DIVMAC.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Problem Link: www.codechef.com/problems/DIVMAC 3 | */ 4 | 5 | #include 6 | #define MAX_ 1000 7 | using namespace std; 8 | int tree[MAX_]; 9 | 10 | int leastPrimeDivisor(int n) { 11 | if (n % 2 == 0) 12 | return 2; 13 | 14 | for (int t=3;t*t<=n;t+=2) { 15 | if (n % t == 0) 16 | return t; 17 | } 18 | return n; 19 | } 20 | 21 | void Update(int st, int ed, int in) { 22 | } 23 | 24 | void Build(int *arr, int st, int ed, int in) { 25 | if (st == ed) { 26 | tree[in] = leastPrimeDivisor(arr[st]); 27 | return; 28 | } 29 | 30 | int mid = (st + ed) / 2; 31 | Build(arr, st, mid, 2 * in); 32 | Build(arr, mid + 1, ed, (2 * in) + 1); 33 | 34 | tree[in] = max(tree[2 * in], tree[(2 * in) + 1]); 35 | } 36 | 37 | int Query(int st, int ed, int qs, int qe, int in) { 38 | if (st > qe || ed < qs) 39 | return INT_MIN; 40 | if (st >= qs && ed <= qe) 41 | return tree[in]; 42 | 43 | int mid = (st + ed) / 2; 44 | Query(st, mid, qs, qe, 2 * in); 45 | Query(mid+1, ed, qs, qe, (2 * in) + 1); 46 | 47 | return max(tree[2*in], tree[(2*in) + 1]); 48 | } 49 | 50 | void Update(int st, int ed, int qs, int qe, int in) { 51 | if (st > qe || ed < qs) 52 | return; 53 | if (st == ed) { 54 | tree[in] /= leastPrimeDivisor(tree[in]); 55 | return; 56 | } 57 | int mid = (st + ed) / 2; 58 | 59 | Update(st, mid, qs, qe, 2 * in); 60 | Update(mid+1, ed, qs, qe, (2 * in) + 1); 61 | 62 | tree[in] = max(tree[2 * in], tree[(2 * in) + 1]); 63 | } 64 | 65 | int main() { 66 | int T, n, m; 67 | cin >> T; 68 | while (T--) { 69 | cin >> n >> m; 70 | int a[n+1]; 71 | 72 | for (int t=1;t<=n;t++) 73 | cin >> a[t]; 74 | 75 | Build(a, 0, n-1, 1); 76 | 77 | int type, l, r; 78 | while(m--) { 79 | cin >> type >> l >> r; 80 | 81 | if (type == 0) 82 | Update(0, n-1, l, r, 1); 83 | if (type == 1) 84 | cout << Query(0, n-1, l, r, 1); 85 | 86 | cout << " "; 87 | } 88 | cout << '\n'; 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Segment-Tree/Problems/Distinct.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | set *sg; 6 | 7 | void buildTree(int a[], int st, int ed, int treeNode) { 8 | if (st == ed) { 9 | sg[treeNode].insert(a[st]); 10 | return; 11 | } 12 | 13 | int mid = (st + ed)/2; 14 | buildTree(a, st, mid, 2 * treeNode); 15 | buildTree(a, mid+1, ed, 2 * treeNode + 1); 16 | 17 | sg[treeNode].insert(sg[2 * treeNode].begin(), sg[2 * treeNode].end()); 18 | sg[treeNode].insert(sg[2 * treeNode + 1].begin(), sg[2 * treeNode + 1].end()); 19 | } 20 | 21 | set Query(int a[], int st, int ed, int inSt, int inEd, int treeNode) { 22 | set lf, rg, res; 23 | if (ed < inSt || st > inEd) 24 | return res; 25 | 26 | if (inSt <= st && inEd >= ed) 27 | return sg[treeNode]; 28 | 29 | int mid = (st + ed) / 2; 30 | lf = Query(a, st, mid, inSt, inEd, 2 * treeNode); 31 | rg = Query(a, mid+1, ed, inSt, inEd, 2 * treeNode + 1); 32 | 33 | res.insert(lf.begin(), lf.end()); 34 | res.insert(rg.begin(), rg.end()); 35 | 36 | return res; 37 | } 38 | 39 | int QuerySolver(int a[], int st, int ed, int inSt, int inEd, int treeNode) { 40 | return Query(a, st, ed, inSt, inEd, treeNode).size(); 41 | } 42 | 43 | int main() { 44 | int a[] = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6}; 45 | for (auto t : a) 46 | cout << t << " "; 47 | 48 | cout << endl; 49 | int n = sizeof(a)/sizeof(a[0]); 50 | 51 | int h = (int)(ceil(log2(n))); 52 | int sz = 2 * (int)pow(2, h) - 1; 53 | 54 | sg = new set[sz]; 55 | 56 | buildTree(a, 0, n-1, 1); 57 | cout << QuerySolver(a, 0, n-1, 0, 2, 1); 58 | } 59 | 60 | -------------------------------------------------------------------------------- /Segment-Tree/Problems/LCM.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int GCD(int a, int b) 7 | { 8 | if (a == 0) 9 | return b; 10 | 11 | return GCD((b % a), a); 12 | } 13 | 14 | int LCM(int a, int b) { 15 | return (a * b)/GCD(a,b); 16 | } 17 | 18 | void BuildTree(int *tree, int a[], int st, int ed, int treeNode) { 19 | if (st == ed) { 20 | tree[treeNode] = a[st]; 21 | return; 22 | } 23 | 24 | int mid = (st + ed) / 2; 25 | BuildTree(tree, a, st, mid, 2 * treeNode); 26 | BuildTree(tree, a, mid+1, ed, 2 * treeNode + 1); 27 | 28 | tree[treeNode] = LCM(tree[2 * treeNode], tree[2 * treeNode + 1]); 29 | } 30 | 31 | int Query(int *tree, int a[], int st, int ed, int inSt, int inEd, int treeNode) { 32 | 33 | if (ed < inSt || st > inEd) // No Overlap. 34 | return 1; 35 | 36 | if (inSt <= st && inEd >= ed) 37 | return tree[treeNode]; 38 | 39 | int mid = (st + ed)/2; 40 | int lf = Query(tree, a, st, mid, inSt, inEd, 2 * treeNode); 41 | int rt = Query(tree, a, mid+1, ed, inSt, inEd, 2 * treeNode + 1); 42 | 43 | return LCM(lf, rt); 44 | } 45 | 46 | int main() { 47 | int a[] = {5, 7, 5, 2, 10, 12, 11, 17, 14, 1, 44}; 48 | int n = sizeof(a)/sizeof(a[0]); 49 | 50 | int *tree = new int[2 * n + 1]; 51 | BuildTree(tree, a, 0, n-1, 1); 52 | 53 | cout << Query(tree, a, 0, n-1, 5, 10, 1); 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Segment-Tree/Problems/XeniaBitOp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void printTree(long long int *tree, long long int n) { 6 | for (long long int t=1;t<2*n;t++) 7 | cout << tree[t] << " "; 8 | 9 | return; 10 | } 11 | void buildTree(long long int *tree, long long int a[], long long int st, long long int ed, long long int treeNode, long long int lvl) { 12 | if (st == ed) { 13 | tree[treeNode] = a[st]; 14 | return; 15 | } 16 | 17 | long long int mid = (st + ed)/2; 18 | buildTree(tree, a, st, mid, 2 * treeNode, lvl+1); 19 | buildTree(tree, a, mid+1, ed, 2 * treeNode + 1, lvl+1); 20 | 21 | if (lvl % 2 != 0) 22 | tree[treeNode] = tree[2 * treeNode] | tree[2 * treeNode + 1]; 23 | else 24 | tree[treeNode] = tree[2 * treeNode] ^ tree[2 * treeNode + 1]; 25 | } 26 | 27 | void rangeUpdate(long long int *tree, long long int treeNode, long long int lvl) { 28 | if (treeNode == 0) 29 | return; 30 | 31 | if (lvl % 2 == 0) 32 | tree[treeNode] = tree[2 * treeNode] | tree[2 * treeNode + 1]; 33 | else 34 | tree[treeNode] = tree[2 * treeNode] ^ tree[2 * treeNode + 1]; 35 | 36 | rangeUpdate(tree, treeNode/2, lvl+1); 37 | } 38 | 39 | int main() { 40 | // freopen("in.txt", "r", stdin); 41 | long long int n, q; 42 | cin >> n >> q; 43 | n = pow(2, n); 44 | long long int a[n]; 45 | for (long long int t=0;t> a[t]; 47 | 48 | long long int *tree = new long long int[(2 * n)+1]; 49 | 50 | buildTree(tree, a, 0, n-1, 1, 0); 51 | 52 | long long int p, b; 53 | while (q--) { 54 | cin >> p >> b; 55 | --p; 56 | long long int tar = p; 57 | tar += n; 58 | tree[tar] = b; 59 | 60 | rangeUpdate(tree, tar/2, 0); 61 | 62 | cout << tree[1] << '\n'; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Segment-Tree/Problems/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Segment-Tree/Problems/a.out -------------------------------------------------------------------------------- /Segment-Tree/Problems/luckyQueries.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define MAX_ 1000 4 | using namespace std; 5 | int tree[MAX_] = {0}; 6 | int lazy[MAX_] = {-1}; 7 | 8 | int diff(int st, int ed, int x) { 9 | return (ed - x - (st - 1)); 10 | } 11 | 12 | void Build(string arr, int st, int ed, int treeNode) { 13 | if (st == ed) { 14 | if (arr[st] == '4') 15 | tree[treeNode] = 1; 16 | else 17 | tree[treeNode] = 0; 18 | 19 | return; 20 | } 21 | 22 | int mid = (st + ed)/2; 23 | Build(arr, st, mid, 2 * treeNode); 24 | Build(arr, mid+1, ed, (2*treeNode)+1); 25 | 26 | tree[treeNode] = tree[2 * treeNode] + tree[(2*treeNode)+1]; 27 | } 28 | 29 | void lazyUpdate(string arr, int st, int ed, int qs, int qe, int treeNode) { 30 | if (lazy[treeNode] != -1) { 31 | tree[treeNode] = lazy[treeNode]; 32 | 33 | if (st != ed) { 34 | tree[2*treeNode] = diff(st, ed, tree[2*treeNode]); 35 | tree[(2*treeNode)+1] = diff(st, ed, tree[(2*treeNode)+1]); 36 | } 37 | lazy[treeNode] = -1; 38 | } 39 | if (st > qe || ed < qs) return; 40 | 41 | if (st >= qs && ed <= qe) { 42 | tree[treeNode] = diff(st, ed, tree[treeNode]); 43 | 44 | if (st != ed) { 45 | tree[2 * treeNode] = diff(st, ed, tree[2 * treeNode]); 46 | tree[(2 * treeNode)+1] = diff(st, ed, tree[(2*treeNode)+1]); 47 | } 48 | return; 49 | } 50 | int mid = (st + ed)/2; 51 | lazyUpdate(arr, st, mid, qs, qe, 2 * treeNode); 52 | lazyUpdate(arr, mid+1, ed, qs, qe, (2 * treeNode)+1); 53 | 54 | tree[treeNode] = tree[2 * treeNode] + tree[(2*treeNode)+1]; 55 | } 56 | 57 | int main() { 58 | string arr = "47447747"; 59 | int n = arr.length(); 60 | 61 | Build(arr, 0, n-1, 1); 62 | 63 | for (int t=1;t<2*n;++t) 64 | cout << tree[t] << " "; 65 | 66 | cout << endl; 67 | lazyUpdate(arr, 0, n-1, 1, 4, 1); 68 | 69 | for (int t=1;t<2*n;++t) 70 | cout << tree[t] << " "; 71 | } 72 | -------------------------------------------------------------------------------- /Segment-Tree/README.md: -------------------------------------------------------------------------------- 1 | ### Segment Tree. 2 | 3 | ![](https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.codebycase.com%2Fassets%2Fimages%2Falgorithms%2Fsegment-tree.jpg&f=1&nofb=1) 4 | 5 | #### Intro. 6 | 7 | A segment tree also known as a statistic tree is a tree data structure used for storing 8 | information about intervals, or segments. It allows querying which of the stored segments 9 | contain a given point. It is, in principle, a static structure; that is, it's a structure 10 | that cannot be modified once it's built. 11 | 12 | #### Time Complexity. 13 | 14 | - Building a Tree: O(n) // One-time Process. 15 | - Query: O(logn) 16 | - Updation: O(logn) 17 | 18 | #### Cases. 19 | 20 | Let, 21 | "start" be the left range, 22 | "end" be the right range, 23 | "inStart" be the input left range, 24 | "inEnd" be the input right range. 25 | 26 | Then, 27 | - Completely Overlapping: (inStart <= start && inEnd >= end). 28 | - No Overlap: (end < inStart || start > inEnd). 29 | - Partial Overlap: If none of the above cases satisfy. 30 | 31 | #### Base Case. 32 | If (start == end), we have hit the bottom level and we return. 33 | 34 | #### Build Process. (May change according to the problem statement.) 35 | We traverse the array in left and right manner until the base condition is hit. When the base 36 | condition is hit, we equal the value of the tree at the current index to something we want 37 | which depends on the problem statement. After both of the left and right calls, we will 38 | be at a point where the current node's value is derived from the left and right nodes. 39 | For example, In sum-range, the value of a node is equal to the minimum value between the 40 | left and right nodes. 41 | 42 | Left Node = 2 * index; 43 | Right Node = 2 * index + 1; 44 | Mid = (start + end) / 2; 45 | 46 | #### Query Process. (May change according to the problem statement.) 47 | After building the tree, queries can be efficiently answered. The Tree is traversed in the following 48 | manner: 49 | - If the ranges are "Partially Overlapping", The node's children are explored. 50 | - If the ranges are "Not Overlapping", some extreme value is returned (MAX or MIN). 51 | - If the ranges are "Completely Overlapping", we return that node itself. 52 | -------------------------------------------------------------------------------- /Segment-Tree/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Segment-Tree/a.out -------------------------------------------------------------------------------- /Segment-Tree/buildTree.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void buildMinRangeTree(int *tree, int *arr, int st, int end, int treeNode) { 6 | if (st == end) { 7 | tree[treeNode] = arr[st]; 8 | return; 9 | } 10 | int mid = (st + end) / 2; 11 | buildMinRangeTree(tree, arr, st, mid, 2 * treeNode); 12 | buildMinRangeTree(tree, arr, mid+1, end, 2 * treeNode + 1); 13 | 14 | tree[treeNode] = min(tree[2 * treeNode], tree[2 * treeNode + 1]); 15 | } 16 | 17 | void buildMaxRangeTree(int *tree, int *arr, int st, int end, int treeNode) { 18 | if (st == end) { 19 | tree[treeNode] = arr[st]; 20 | return; 21 | } 22 | int mid = (st + end)/2; 23 | 24 | buildMaxRangeTree(tree, arr, st, mid, 2 * treeNode); 25 | buildMaxRangeTree(tree, arr, mid+1, end, 2 * treeNode + 1); 26 | 27 | tree[treeNode] = max(tree[2 * treeNode], tree[2 * treeNode + 1]); 28 | } 29 | -------------------------------------------------------------------------------- /Segment-Tree/maxRangeQuery.cpp: -------------------------------------------------------------------------------- 1 | #include "buildTree.hpp" 2 | 3 | int maxRangeQuery(int *tree, int st, int ed, int inSt, int inEd, int treeNode) { 4 | int mid = (st + ed)/2; 5 | 6 | if (inSt <= st && inEd >= ed) { 7 | return tree[treeNode]; 8 | } 9 | else if ((inSt >= st && inSt <= ed) || (inEd >= st && inEd <= ed)) { 10 | return max(maxRangeQuery(tree, st, mid, inSt, inEd, 2 * treeNode), 11 | (maxRangeQuery(tree, mid+1, ed, inSt, inEd, 2 * treeNode + 1))); 12 | } 13 | else 14 | return INT_MIN; 15 | } 16 | 17 | void Update(int *tree, int cI) { 18 | if (cI == 0) 19 | return; 20 | tree[cI] = max(tree[2 * cI], tree[2 * cI + 1]); 21 | 22 | Update(tree, cI/2); 23 | } 24 | 25 | int main() { 26 | int arr[] = {2, 3, 123, 555, 43, 139, -122, 332}; 27 | int n = sizeof(arr)/sizeof(arr[0]); 28 | 29 | int *tree = new int[32]; 30 | 31 | buildMaxRangeTree(tree, arr, 0, 7, 1); 32 | 33 | cout << maxRangeQuery(tree, 0, 7, 4, 7, 1); 34 | tree[n + 7] = 1996; 35 | int h = (int)(ceil(log2(n))); 36 | int sz = 2 * (int)pow(2, h) - 1; 37 | 38 | Update(tree, sz-1); 39 | cout << endl; 40 | cout << maxRangeQuery(tree, 0, 7, 4, 7, 1); 41 | } 42 | -------------------------------------------------------------------------------- /Segment-Tree/minRangeQuery.cpp: -------------------------------------------------------------------------------- 1 | #include "buildTree.hpp" 2 | 3 | int minRangeQuery(int *tree, int st, int ed, int inSt, int inEd, int treeNode) { 4 | int mid = (st + ed) / 2; 5 | if (inSt <= st && inEd >= ed) { 6 | return tree[treeNode]; 7 | } 8 | else if ((inSt >= st && inSt <= ed) || (inEd >= st && inEd <= ed)) { 9 | return min(minRangeQuery(tree, st, mid, inSt, inEd, 2 * treeNode), minRangeQuery(tree, mid+1, ed, inSt, inEd, 2 * treeNode + 1)); 10 | } 11 | else return INT_MAX; 12 | } 13 | 14 | int main() { 15 | int arr[]= {1, 12, 3, -6, -5, -25}; 16 | 17 | int *tree = new int[32]; 18 | 19 | buildMinRangeTreee(tree, arr, 0, 5, 1); 20 | 21 | cout << minRangeQuery(tree, 0, 5, 2, 4, 1); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Strings/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Strings/a.out -------------------------------------------------------------------------------- /Strings/lengthEncoding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | string encode(string s) 6 | { 7 | int cc, t; 8 | string dest = ""; 9 | 10 | for (t = 0; t < s.length() - 1; t++) 11 | { 12 | cc = 1; 13 | while (t < s.length() - 1 && s[t] == s[t + 1]) 14 | { 15 | t++; 16 | cc++; 17 | } 18 | dest += s[t]; 19 | dest += std::to_string(cc); 20 | } 21 | return dest; 22 | } 23 | 24 | int main() 25 | { 26 | string s; 27 | cin >> s; 28 | cout << encode(s) << endl; 29 | } -------------------------------------------------------------------------------- /Strings/reverseString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define max 100 4 | using namespace std; 5 | static string Rstr; 6 | static int top=-1; 7 | char stack[max]; 8 | 9 | void push(char value) { 10 | if (top < max) { 11 | top++; 12 | stack[top] = value; 13 | } 14 | return; 15 | } 16 | 17 | char pop() { 18 | char temp = stack[top]; 19 | top--; 20 | return temp; 21 | } 22 | 23 | void combineString() { 24 | while (top > -1) { 25 | Rstr += pop(); 26 | } 27 | Rstr += " "; 28 | return; 29 | } 30 | 31 | void reverseWords(char a[]) { 32 | int t; 33 | for (t=strlen(a)-1;t>=0;t--) { 34 | if (a[t] == ' ') { 35 | combineString(); 36 | } else { 37 | push(a[t]); 38 | } 39 | } 40 | combineString(); 41 | return; 42 | } 43 | 44 | int main(){ 45 | char a[40]; 46 | cin.getline(a,40); 47 | reverseWords(a); 48 | cout << Rstr << '\n'; 49 | } -------------------------------------------------------------------------------- /Strings/searchRowColumn.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void searchKey(int a[100][100], int key, int r, int c) { 5 | 6 | int row = 0, col = c-1; 7 | bool got = false; 8 | while (!got) { 9 | if (a[row][col] > key) { 10 | col--; 11 | } else if (a[row][col] < key) { 12 | row++; 13 | } else { 14 | cout << "Found at ( " << row << "," << col << " )" << '\n'; 15 | got = true; 16 | } 17 | } 18 | return; 19 | } 20 | 21 | int main() { 22 | int a[100][100]; 23 | int r,c,i,j; 24 | cin >> r >> c; 25 | 26 | for (i=0;i> a[i][j]; 29 | } 30 | } 31 | int key; 32 | cin >> key; 33 | searchKey(a, key,r,c); 34 | } -------------------------------------------------------------------------------- /Suffix-Arrays/Build.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | /* 6 | This is an Naive Implementation which takes O(n^2Logn) Time. 7 | */ 8 | 9 | struct Suffix { 10 | int index; 11 | char *suff; 12 | }; 13 | 14 | bool comperator(Suffix a, Suffix b) { 15 | return strcmp(a.suff, b.suff) < 0 ? 1 : 0; 16 | } 17 | 18 | void printSuffixArray(Suffix *Arr, int n) { 19 | for (int t=0;t 2 | using namespace std; 3 | 4 | struct Suffix { 5 | int index; 6 | int rank[2]; 7 | }; 8 | 9 | bool cmp(Suffix a, Suffix b) { 10 | return (a.rank[0] == b.rank[0]) ? (a.rank[1] < b.rank[1] ? 1 : 0) : (a.rank[0] < b.rank[0] ? 1 : 0); 11 | } 12 | 13 | int *buildEffSuffixArray(char *txt, int n) { 14 | Suffix suffix[n]; 15 | 16 | for (int t=0;t 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct SuffixTree { 8 | SuffixTree *branch[26]; 9 | bool EOS; 10 | }; 11 | 12 | SuffixTree *createNode() { 13 | SuffixTree *temp = new SuffixTree(); 14 | 15 | for (int t=0;t<26;t++) { 16 | temp->branch[t] = nullptr; 17 | } 18 | 19 | return temp; 20 | } 21 | 22 | #include "Insert.hpp" 23 | #include "PrintTree.hpp" 24 | -------------------------------------------------------------------------------- /Suffix-Trees/Insert.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Base.hpp" 3 | 4 | void Insert(string key, SuffixTree *root) { 5 | int n = key.end() - key.begin(); 6 | SuffixTree *temp = root; 7 | 8 | for (int t=0;tbranch[key[j] - 'a']) 12 | root->branch[key[j] - 'a'] = createNode(); 13 | 14 | root = root->branch[key[j] - 'a']; 15 | } 16 | root->EOS = true; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Suffix-Trees/Main.cpp: -------------------------------------------------------------------------------- 1 | #include "Base.hpp" 2 | 3 | int main() { 4 | SuffixTree *root = new SuffixTree(); 5 | Insert("banana", root); 6 | Print(root, ""); 7 | 8 | } 9 | -------------------------------------------------------------------------------- /Suffix-Trees/PrintTree.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Base.hpp" 3 | 4 | void Print(SuffixTree *root, string st) { 5 | if (root->EOS) 6 | cout << st << endl; 7 | 8 | for (int t=0;t<26;t++) { 9 | int in = t+97; 10 | if (root->branch[t]) { 11 | st.push_back(in); 12 | Print(root->branch[t], st); 13 | st.pop_back(); 14 | } 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Suffix-Trees/Problems/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Suffix-Trees/Problems/a.out -------------------------------------------------------------------------------- /Suffix-Trees/Problems/subString.cpp: -------------------------------------------------------------------------------- 1 | #include "../Base.hpp" 2 | 3 | bool isSubString(string qry, int in, SuffixTree *root) { 4 | if (in == qry.length()) 5 | return true; 6 | 7 | int ind = qry[in] - 'a'; 8 | if (root->branch[ind]) 9 | return isSubString(qry, ++in, root->branch[ind]); 10 | else 11 | return false; 12 | } 13 | 14 | int main() { 15 | SuffixTree *root = new SuffixTree(); 16 | Insert("banana", root); 17 | cout << isSubString("nt", 0, root); 18 | } 19 | -------------------------------------------------------------------------------- /Suffix-Trees/README.md: -------------------------------------------------------------------------------- 1 | ### Suffix Trees 2 | 3 | ![Suffix Tree](https://he-s3.s3.amazonaws.com/media/uploads/a55f8db.png) 4 | 5 | #### Intro 6 | The construction of such a tree for the string {\displaystyle S}S takes time and space linear in the length of S. 7 | Once constructed, several operations can be performed quickly, for instance locating a substring in S, 8 | locating a substring if a certain number of mistakes are allowed etc. 9 | Suffix trees also provide one of the first linear-time solutions for the longest common substring problem. 10 | These speedups come at a cost: storing a string's suffix tree typically requires significantly more space 11 | than storing the string itself. 12 | 13 | #### Building Suffix Tree. 14 | Building an Suffix Tree is same as building an Trie. We start inserting every character in the string 15 | into the tree. If there's already an Node present, go to that Node. Else, create that Node and go 16 | there. The only difference between a Trie and a Suffix Tree is that in Suffix Tree, we Build a Tree 17 | for all suffixes of the string. 18 | 19 | #### Printing Tree. 20 | For each Node, we check all of its 26 links (children) and if there's an link present, we go to that 21 | link recursively. The Base case is when there are no children and it is an End of String. 22 | 23 | #### Advantages 24 | Using Suffix Trees, we can solve problems really faster. There are Applications like: 25 | - Substring or Not. O(m), m = Length of the substring. 26 | - Longest Substring Palindrome. O(n), n = length of the string. 27 | - Longest Common Substring. O(n), n = Length of the string. 28 | - Searching All Patterns. O(z), z = Number of Occurences and m = Length of the Pattern. 29 | - Longest Repeated Substring. O(n), n = Length of the String. 30 | -------------------------------------------------------------------------------- /Suffix-Trees/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Suffix-Trees/a.out -------------------------------------------------------------------------------- /Treap/.gitignore: -------------------------------------------------------------------------------- 1 | a.out 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /Treap/Delete.hpp: -------------------------------------------------------------------------------- 1 | #include "Includes.hpp" 2 | #include "Structure.hpp" 3 | #include "Operations.hpp" 4 | 5 | #ifndef DEL 6 | #define DEL 7 | 8 | TreapNode *Delete(TreapNode *root, int key) { 9 | if (!root) return root; 10 | 11 | if (key < root->key) 12 | root->left = Delete(root->left, key); 13 | else if (key > root->key) 14 | root->right = Delete(root->right, key); 15 | 16 | else if (!root->left) { 17 | TreapNode *tempNode = root->right; 18 | delete(root); 19 | root = tempNode; 20 | } else if (!root->right) { 21 | TreapNode *tempNode = root->left; 22 | delete(root); 23 | root = tempNode; 24 | } 25 | 26 | else if (root->left->priority < root->right->priority) { 27 | root = rotateLeft(root); 28 | root->left = Delete(root->left, key); 29 | } else { 30 | root = rotateRight(root); 31 | root->right = Delete(root->right, key); 32 | } 33 | return root; 34 | } 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /Treap/Includes.hpp: -------------------------------------------------------------------------------- 1 | #ifndef INC 2 | #define INC 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | #endif 10 | -------------------------------------------------------------------------------- /Treap/Insert.hpp: -------------------------------------------------------------------------------- 1 | #include "Includes.hpp" 2 | #include "Structure.hpp" 3 | #include "Operations.hpp" 4 | 5 | #ifndef INS 6 | #define INS 7 | 8 | TreapNode *Insert(TreapNode *root, int key) { 9 | if (!root) 10 | return createNode(key); 11 | 12 | else if (root->key >= key) { 13 | root->left = Insert(root->left, key); 14 | 15 | if (root->left->priority > root->priority) 16 | root = rotateRight(root); 17 | } else { 18 | root->right = Insert(root->right, key); 19 | 20 | if (root->right->priority > root->priority) 21 | root = rotateLeft(root); 22 | } 23 | 24 | return root; 25 | } 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /Treap/Operations.hpp: -------------------------------------------------------------------------------- 1 | #include "Includes.hpp" 2 | #include "Structure.hpp" 3 | 4 | #ifndef OP 5 | #define OP 6 | 7 | TreapNode *createNode(int key) { 8 | TreapNode *newNode = new TreapNode(); 9 | newNode->left = nullptr, 10 | newNode->right = nullptr, 11 | newNode->key = key, 12 | newNode->priority = (rand() % 100); 13 | 14 | return newNode; 15 | } 16 | 17 | TreapNode *rotateRight(TreapNode *&y) { 18 | TreapNode *x = y->left, *Sub2 = x->right; 19 | 20 | x->right = y; 21 | y->left = Sub2; 22 | 23 | return x; 24 | } 25 | 26 | TreapNode *rotateLeft(TreapNode *&x) { 27 | TreapNode *y = x->right, *Sub2 = y->left; 28 | 29 | y->left = x; 30 | x->right = Sub2; 31 | 32 | return y; 33 | } 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /Treap/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Treap/README.md -------------------------------------------------------------------------------- /Treap/ShowTree.hpp: -------------------------------------------------------------------------------- 1 | void Inorder(TreapNode *root) { 2 | if (!root) return; 3 | 4 | Inorder(root->left); 5 | cout << root->key << " " << root->priority << endl; 6 | Inorder(root->right); 7 | } 8 | 9 | void Preorder(TreapNode *root) { 10 | if (!root) return; 11 | 12 | cout << root->key << " " << root->priority << endl; 13 | Preorder(root->left); 14 | Preorder(root->right); 15 | } 16 | 17 | void Postorder(TreapNode *root) { 18 | if (!root) return; 19 | 20 | Postorder(root->left); 21 | Postorder(root->right); 22 | cout << root->key << " " << root->priority << endl; 23 | } 24 | -------------------------------------------------------------------------------- /Treap/Src.cpp: -------------------------------------------------------------------------------- 1 | #include "Insert.hpp" 2 | #include "ShowTree.hpp" 3 | #include "Delete.hpp" 4 | 5 | int main() { 6 | TreapNode *root = nullptr; 7 | 8 | root = Insert(root, 50); 9 | root = Insert(root, 10); 10 | root = Insert(root, 5); 11 | root = Insert(root, 509); 12 | root = Insert(root, 510); 13 | 14 | Inorder(root); 15 | root = Delete(root, 10); 16 | Inorder(root); 17 | } 18 | -------------------------------------------------------------------------------- /Treap/Structure.hpp: -------------------------------------------------------------------------------- 1 | #include "Includes.hpp" 2 | 3 | #ifndef TRP 4 | #define TRP 5 | 6 | struct TreapNode { 7 | int key, priority; 8 | TreapNode *left, *right; 9 | }; 10 | 11 | #endif 12 | -------------------------------------------------------------------------------- /Trees/BTrees/NodeStructure.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class BTreeNode { 5 | int n; 6 | int t; 7 | int *keys; 8 | BTreeNode **children; 9 | bool leaf; 10 | 11 | public: 12 | BTreeNode(int _t, bool leaf); 13 | void insertNonFull(int k); 14 | void splitChild(int i, BTreeNode *y); 15 | void Traverse(); 16 | 17 | friend class BTree; 18 | }; -------------------------------------------------------------------------------- /Trees/BTrees/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Trees/BTrees/a.out -------------------------------------------------------------------------------- /Trees/BTrees/basicTemplate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "./NodeStructure.hpp" 3 | using namespace std; 4 | 5 | class BTree { 6 | public: 7 | int t; 8 | BTreeNode *root; 9 | BTree(int _t) { 10 | root = NULL; 11 | t = _t; 12 | } 13 | void Insert(int k); 14 | void Traverse() { 15 | if (root) 16 | root->Traverse(); 17 | } 18 | }; 19 | 20 | // Constructor of BTreeNode from "NodeStructure.hpp". 21 | BTreeNode::BTreeNode(int _t, bool leaf) { 22 | this->t = _t; 23 | this->leaf = leaf; 24 | this->keys = new int[(2 * t) - 1]; 25 | this->children = new BTreeNode *[2 * t]; 26 | this->n = 0; 27 | } 28 | 29 | // Driver function for Insertion of Data. 30 | void BTree::Insert(int k) { 31 | // If there is no Root. 32 | if (root == NULL) { 33 | root = new BTreeNode(t, true); 34 | root->keys[0] = k; 35 | root->n = 1; 36 | return; 37 | } else { 38 | if (root->n == (2 * t) - 1) { // If the Root is Full. 39 | BTreeNode *s = new BTreeNode(t, false); // Create a new Node as the root is full. 40 | s->children[0] = root; 41 | s->splitChild(0, root); // As we know, we have to split if the node is full. 42 | 43 | int i = 0; 44 | if (s->keys[0] < k) 45 | i++; 46 | 47 | s->children[1]->insertNonFull(k); // Insert Data. 48 | root = s; 49 | 50 | } else // If the Root is not full. 51 | root->insertNonFull(k); 52 | } 53 | } 54 | 55 | // Function which inserts data into node assuming that the space isn't full yet. 56 | void BTreeNode::insertNonFull(int k) { 57 | int i = n - 1; 58 | 59 | // If the node is a Leaf Node. 60 | if (leaf) { 61 | // Get the position of the key to be inserted. 62 | while (i >= 0 && keys[i] > k) { 63 | keys[i + 1] = keys[i]; 64 | i--; 65 | } 66 | // Insert the key. 67 | keys[i + 1] = k; 68 | // Increment number of keys. 69 | ++n; 70 | } else { // If the node is not a Leaf node. 71 | while (i >= 0 && keys[i] > k) // Get the position of the node to be inserted. 72 | i--; 73 | 74 | // if the node is full. 75 | if (children[i + 1]->n == (2 * t) - 1) { 76 | // Split the node. 77 | splitChild(i + 1, children[i + 1]); 78 | 79 | // As we have to decide the bias whether it is left-median or right-median. 80 | if (keys[i + 1] < k) 81 | i++; 82 | } 83 | // insert k to the child's node. 84 | children[i + 1]->insertNonFull(k); 85 | } 86 | return; 87 | } 88 | 89 | // Function for splitting a node. 90 | void BTreeNode::splitChild(int i, BTreeNode *y) { 91 | // As we're splitting a node into two, we need another node to accompany. 92 | BTreeNode *z = new BTreeNode(y->t, y->leaf); 93 | // Set number of keys for the new node equal to the degree. 94 | z->n = t - 1; 95 | 96 | // Copy the last t-1 nodes of 'y' to 'z'. 97 | for (int j = 0; j < t - 1; j++) 98 | z->keys[j] = y->keys[j + t]; 99 | 100 | // If Node 'y' isn't a leaf node. 101 | if (!y->leaf) { 102 | // Then, we must copy the node's children too. 103 | for (int j = 0; j < t; j++) 104 | z->children[j] = y->children[j + t]; 105 | } 106 | // decrease the number of nodes in 'y'. 107 | y->n = t - 1; 108 | 109 | // Create space for new child (split node). Remember, this is the children of the node that called this function. 110 | for (int j = n; j >= i + 1; j--) 111 | children[j + 1] = children[j]; 112 | 113 | // Insert our new node into that space we've created. 114 | children[i + 1] = z; 115 | 116 | // Create space for the new key as the median of the children comes to it's parent. 117 | for (int j = n - 1; j >= i; j--) 118 | keys[j + 1] = keys[j]; 119 | 120 | // Insert the key into that position. 121 | keys[i] = y->keys[t - 1]; 122 | // Increment the number of keys of this node (Root). 123 | ++n; 124 | } 125 | 126 | // Function for Traversing the Tree. 127 | void BTreeNode::Traverse() { 128 | int t; 129 | // Traverse 'n' children. 130 | for (t = 0; t < n; t++) { 131 | // If the current node isn't a leaf, then we're sure that it has children. So, we call them first. 132 | if (!leaf) 133 | children[t]->Traverse(); 134 | 135 | // Print the key. 136 | cout << keys[t] << " "; 137 | } 138 | // Subtree rooted with last child. 139 | if (!leaf) 140 | children[t]->Traverse(); 141 | } 142 | 143 | int main() { 144 | BTree *bt = new BTree(3); 145 | 146 | bt->Insert(10); 147 | bt->Insert(20); 148 | bt->Insert(5); 149 | bt->Insert(6); 150 | bt->Insert(12); 151 | bt->Insert(30); 152 | bt->Insert(7); 153 | bt->Insert(17); 154 | 155 | bt->Traverse(); 156 | cout << endl; 157 | } -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Trees/Binary_Search_Tree/.DS_Store -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/KthLargest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "basicTreeTemplate.h" 4 | using namespace std; 5 | static int top = -1; 6 | Node *a[100]; 7 | 8 | void push(Node *root) 9 | { 10 | top++; 11 | a[top] = root; 12 | } 13 | 14 | void pop() 15 | { 16 | top--; 17 | } 18 | 19 | Node *topElement() 20 | { 21 | return a[top]; 22 | } 23 | 24 | bool isEmpty() 25 | { 26 | return (top == -1) ? true : false; 27 | } 28 | 29 | void KLargestIterative(Node *root, int k) 30 | { 31 | int b[100]; 32 | int ind = 0; 33 | while (1) 34 | { 35 | while (root) 36 | { 37 | push(root); 38 | root = root->left; 39 | } 40 | if (isEmpty()) 41 | break; 42 | 43 | root = topElement(); 44 | b[ind] = root->data; 45 | ind++; 46 | pop(); 47 | root = root->right; 48 | } 49 | cout << b[ind - k] << '\n'; 50 | } 51 | 52 | int main() 53 | { 54 | Node *root = nullptr; 55 | insertNode(root, 50); 56 | insertNode(root, 30); 57 | insertNode(root, 20); 58 | insertNode(root, 40); 59 | insertNode(root, 70); 60 | insertNode(root, 60); 61 | insertNode(root, 80); 62 | int k; 63 | cin >> k; 64 | 65 | KLargestIterative(root, k); 66 | } 67 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/TreeOne.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int *queue = new int[40]; 6 | int findPath(Node *root) 7 | { 8 | if (!root) 9 | return 0; 10 | 11 | queue[ind] = root->data; 12 | ind++; 13 | 14 | if (!root->left && !root->right) 15 | { 16 | for (int t = 0; t < ind; t++) 17 | cout << queue[t] << " -> "; 18 | 19 | cout << endl; 20 | } 21 | findPath(root->left); 22 | findPath(root->right); 23 | ind--; 24 | } 25 | 26 | 27 | int main() 28 | { 29 | int *store = new int[20]; 30 | int *hash = new int[20]; 31 | Node *root = nullptr; 32 | insertNode(root, 10); 33 | insertNode(root, 5); 34 | insertNode(root, 3); 35 | insertNode(root, 8); 36 | insertNode(root, 20); 37 | insertNode(root, 15); 38 | insertNode(root, 30); 39 | 40 | root = getMirror(root); 41 | displayTree(root); 42 | } 43 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/a.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Trees/Binary_Search_Tree/a.exe -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Trees/Binary_Search_Tree/a.out -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/alternateCorners.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "basicTreeTemplate.h" 4 | using namespace std; 5 | 6 | static int front = -1, rear = -1; 7 | Node *queue[100]; 8 | 9 | void enQueue(Node *root) 10 | { 11 | if (front == -1) 12 | front = 0; 13 | 14 | rear++; 15 | queue[rear] = root; 16 | } 17 | 18 | Node *deQueue() 19 | { 20 | Node *temp = queue[front]; 21 | front++; 22 | return temp; 23 | } 24 | 25 | bool isEmpty() 26 | { 27 | return (front > rear) ? true : false; 28 | } 29 | #include 30 | void alternateCorners(Node *root) 31 | { 32 | vector *l; 33 | l = new vector[100]; 34 | 35 | enQueue(root); 36 | Node *temp; 37 | int ind = 1, indexed = 0; 38 | while (!isEmpty()) 39 | { 40 | if (ind == pow(2, indexed)) 41 | { 42 | indexed++; 43 | } 44 | 45 | temp = deQueue(); 46 | l[indexed].push_back(temp->data); 47 | ind++; 48 | 49 | if (temp->left) 50 | enQueue(temp->left); 51 | if (temp->right) 52 | enQueue(temp->right); 53 | } 54 | for (int c = 0; c <= indexed; c++) 55 | { 56 | bool flag = false; 57 | if (c % 2 == 0) 58 | { 59 | flag = true; 60 | } 61 | for (auto r = l[c].begin(); r != l[c].end(); r++) 62 | { 63 | if (flag) 64 | { 65 | cout << *r << " "; 66 | break; 67 | } 68 | else 69 | { 70 | if (r == l[c].end() - 1) 71 | { 72 | cout << *r << " "; 73 | break; 74 | } 75 | } 76 | } 77 | } 78 | } 79 | 80 | int main() 81 | { 82 | Node *root = nullptr; 83 | insertNode(root, 50); 84 | insertNode(root, 40); 85 | insertNode(root, 60); 86 | insertNode(root, 30); 87 | insertNode(root, 45); 88 | insertNode(root, 65); 89 | insertNode(root, 70); 90 | 91 | alternateCorners(root); 92 | } 93 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/basicTreeTemplate.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Node 6 | { 7 | int data; 8 | Node *right; 9 | Node *left; 10 | }; 11 | 12 | Node *insertNode(Node *&root, int data) 13 | { 14 | if (!root) 15 | { 16 | Node *temp = new Node(); 17 | temp->data = data; 18 | temp->left = temp->right = NULL; 19 | root = temp; 20 | return root; 21 | } 22 | else if (data > root->data) 23 | { 24 | insertNode(root->right, data); 25 | } 26 | else 27 | { 28 | insertNode(root->left, data); 29 | } 30 | return root; 31 | } 32 | 33 | void displayTreePreorder(Node *root) 34 | { 35 | if (root) 36 | { 37 | cout << root->data << " "; 38 | displayTreePreorder(root->left); 39 | displayTreePreorder(root->right); 40 | } 41 | } 42 | 43 | void displayTreePostorder(Node *root) 44 | { 45 | if (root) 46 | { 47 | displayTreePostorder(root->left); 48 | displayTreePostorder(root->right); 49 | cout << root->data << " "; 50 | } 51 | } 52 | 53 | void displayTreeInorder(Node *root) 54 | { 55 | if (root) 56 | { 57 | displayTreeInorder(root->left); 58 | cout << root->data << " "; 59 | displayTreeInorder(root->right); 60 | } 61 | } -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/classicIterative/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Trees/Binary_Search_Tree/classicIterative/a.out -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/classicIterative/inOrderIterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../basicTreeTemplate.h" 4 | using namespace std; 5 | 6 | void preorderTraversalIterative(Node *root, stack st) 7 | { 8 | while (true) 9 | { 10 | while (root) 11 | { 12 | st.push(root); 13 | root = root->left; 14 | } 15 | if (st.empty()) 16 | break; 17 | root = st.top(); 18 | cout << root->data << " "; 19 | st.pop(); 20 | root = root->right; 21 | } 22 | return; 23 | } 24 | 25 | int main() 26 | { 27 | stack s1; 28 | Node *root = nullptr; 29 | insertNode(root, 50); 30 | insertNode(root, 60); 31 | insertNode(root, 55); 32 | insertNode(root, 57); 33 | insertNode(root, 61); 34 | insertNode(root, 63); 35 | insertNode(root, 40); 36 | insertNode(root, 45); 37 | insertNode(root, 47); 38 | insertNode(root, 30); 39 | 40 | preorderTraversalIterative(root, s1); 41 | cout << endl; 42 | } 43 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/classicIterative/leafNodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "../basicTreeTemplate.h" 5 | using namespace std; 6 | 7 | int countLeafNodes(Node *root) 8 | { 9 | stack st; 10 | vector vec; 11 | int leaves = 0; 12 | 13 | while (true) 14 | { 15 | while (root) 16 | { 17 | if (!root->left && !root->right) 18 | { 19 | cout << root->data << " "; 20 | leaves++; 21 | vec.push_back(root->data); 22 | } 23 | st.push(root); 24 | root = root->left; 25 | } 26 | if (st.empty()) 27 | break; 28 | 29 | root = st.top(); 30 | st.pop(); 31 | root = root->right; 32 | } 33 | cout << endl; 34 | return leaves; 35 | } 36 | 37 | int main() 38 | { 39 | Node *root = NULL; 40 | insertNode(root, 50); 41 | insertNode(root, 30); 42 | insertNode(root, 20); 43 | insertNode(root, 40); 44 | insertNode(root, 70); 45 | insertNode(root, 60); 46 | insertNode(root, 80); 47 | insertNode(root, 100); 48 | 49 | cout << countLeafNodes(root) << endl; 50 | } -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/classicIterative/levelOrderIterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../basicTreeTemplate.h" 4 | using namespace std; 5 | queue q; 6 | 7 | void levelOrderIterative(Node *root) 8 | { 9 | q.push(root); 10 | Node *node; 11 | while (!q.empty()) 12 | { 13 | node = q.front(); 14 | cout << node->data << " "; 15 | q.pop(); 16 | 17 | if (node->left) 18 | q.push(node->left); 19 | 20 | if (node->right) 21 | q.push(node->right); 22 | } 23 | return; 24 | } 25 | 26 | int main() 27 | { 28 | Node *root = NULL; 29 | insertNode(root, 50); 30 | insertNode(root, 60); 31 | insertNode(root, 55); 32 | insertNode(root, 57); 33 | insertNode(root, 61); 34 | insertNode(root, 63); 35 | insertNode(root, 40); 36 | insertNode(root, 45); 37 | insertNode(root, 47); 38 | insertNode(root, 30); 39 | 40 | levelOrderIterative(root); 41 | } -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/classicIterative/maximumElement_BST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "../basicTreeTemplate.h" 5 | using namespace std; 6 | 7 | int maximumElement(Node *root) 8 | { 9 | Node *prev; 10 | while (root) 11 | { 12 | prev = root; 13 | root = root->right; 14 | } 15 | return prev->data; 16 | } 17 | 18 | int main() 19 | { 20 | Node *root = NULL; 21 | 22 | insertNode(root, 50); 23 | insertNode(root, 30); 24 | insertNode(root, 20); 25 | insertNode(root, 120); 26 | insertNode(root, 40); 27 | insertNode(root, 70); 28 | insertNode(root, 60); 29 | insertNode(root, 80); 30 | insertNode(root, 100); 31 | 32 | cout << maximumElement(root) << endl; 33 | } -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/classicIterative/postOrderIterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../basicTreeTemplate.h" 4 | using namespace std; 5 | 6 | void postOrderIterative(Node *root) 7 | { 8 | stack s1, s2; 9 | 10 | s1.push(root); 11 | Node *node; 12 | while (!s1.empty()) 13 | { 14 | node = s1.top(); 15 | s2.push(node); 16 | s1.pop(); 17 | 18 | if (node->left) 19 | s1.push(node->left); 20 | 21 | if (node->right) 22 | s1.push(node->right); 23 | } 24 | 25 | while (!s2.empty()) 26 | { 27 | node = s2.top(); 28 | cout << node->data << " "; 29 | s2.pop(); 30 | } 31 | 32 | return; 33 | } 34 | 35 | int main() 36 | { 37 | Node *root = NULL; 38 | insertNode(root, 50); 39 | insertNode(root, 60); 40 | insertNode(root, 55); 41 | insertNode(root, 57); 42 | insertNode(root, 61); 43 | insertNode(root, 63); 44 | insertNode(root, 40); 45 | insertNode(root, 45); 46 | insertNode(root, 47); 47 | insertNode(root, 30); 48 | 49 | postOrderIterative(root); 50 | } -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/classicIterative/preOrderIterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "../basicTreeTemplate.h" 4 | using namespace std; 5 | 6 | void preorderTraversalIterative(Node *root, stack st) 7 | { 8 | while (true) 9 | { 10 | while (root) 11 | { 12 | cout << root->data << " "; 13 | st.push(root); 14 | root = root->left; 15 | } 16 | if (st.empty()) 17 | break; 18 | root = st.top(); 19 | st.pop(); 20 | root = root->right; 21 | } 22 | return; 23 | } 24 | 25 | int main() 26 | { 27 | stack s1, s2; 28 | Node *root = NULL; 29 | insertNode(root, 50); 30 | insertNode(root, 60); 31 | insertNode(root, 55); 32 | insertNode(root, 57); 33 | insertNode(root, 61); 34 | insertNode(root, 63); 35 | insertNode(root, 40); 36 | insertNode(root, 45); 37 | insertNode(root, 47); 38 | insertNode(root, 30); 39 | 40 | preorderTraversalIterative(root); 41 | cout << endl; 42 | } -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/consecutiveCount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | #include 4 | using namespace std; 5 | 6 | vector v; 7 | 8 | void countConsecutive(Node *root) 9 | { 10 | if (!root) 11 | return; 12 | 13 | countConsecutive(root->left); 14 | v.push_back(root->data); 15 | countConsecutive(root->right); 16 | return; 17 | } 18 | 19 | int main() 20 | { 21 | Node *root = nullptr; 22 | 23 | insertNode(root, 50); 24 | insertNode(root, 40); 25 | insertNode(root, 39); 26 | insertNode(root, 41); 27 | insertNode(root, 42); 28 | insertNode(root, 43); 29 | insertNode(root, 60); 30 | insertNode(root, 55); 31 | insertNode(root, 70); 32 | insertNode(root, 71); 33 | 34 | countConsecutive(root); 35 | 36 | int count = 0, maxim = INT_MIN; 37 | for (int t = 0; t < v.size(); t++) 38 | { 39 | if (v[t] == v[t + 1] - 1) 40 | { 41 | count++; 42 | if (count > maxim) 43 | maxim = count; 44 | } 45 | else 46 | count = 0; 47 | } 48 | 49 | cout << maxim << endl; 50 | } 51 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/correctTheBST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | Node *temp1 = nullptr, *temp2 = NULL; 6 | bool correctBST(Node *root, int min, int max) 7 | { 8 | if (!root) 9 | return false; 10 | 11 | if (root->data <= min || root->data > max) 12 | { 13 | if (temp1 != nullptr) 14 | temp2 = root; 15 | else 16 | temp1 = root; 17 | 18 | if (temp1 != nullptr && temp2 != NULL) 19 | { 20 | Node *t = temp1; 21 | temp1 = temp2; 22 | temp2 = t; 23 | } 24 | return true; 25 | } 26 | return correctBST(root->left, min, root->data) && correctBST(root->right, root->data, max); 27 | } 28 | 29 | int main() 30 | { 31 | Node *root = nullptr; 32 | insertNode(root, 10); 33 | insertNode(root, 5); 34 | insertNode(root, 8); 35 | insertNode(root, 2); 36 | insertNode(root, 20); 37 | correctBST(root, INT_MIN, INT_MAX); 38 | displayTree(root); 39 | } 40 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/countRange.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int countRange(Node *root, int l, int h) 6 | { 7 | if (!root) 8 | return 0; 9 | 10 | if (root->data == l && root->data == h) 11 | return 1; 12 | 13 | if (root->data >= l && root->data <= h) 14 | { 15 | return 1 + countRange(root->left, l, h) + countRange(root->right, l, h); 16 | } 17 | 18 | if (root->data < l) 19 | return countRange(root->right, l, h); 20 | 21 | else 22 | return countRange(root->left, l, h); 23 | } 24 | 25 | int main() 26 | { 27 | Node *root = nullptr; 28 | 29 | insertNode(root, 50); 30 | insertNode(root, 40); 31 | insertNode(root, 30); 32 | insertNode(root, 25); 33 | insertNode(root, 35); 34 | insertNode(root, 45); 35 | insertNode(root, 60); 36 | insertNode(root, 55); 37 | insertNode(root, 70); 38 | insertNode(root, 65); 39 | insertNode(root, 80); 40 | insertNode(root, 75); 41 | insertNode(root, 90); 42 | // insertNode(root, 10); 43 | // insertNode(root, 5); 44 | // insertNode(root, 50); 45 | // insertNode(root, 1); 46 | // insertNode(root, 40); 47 | // insertNode(root, 100); 48 | int got = countRange(root, 35, 70); 49 | cout << got << endl; 50 | // cout << cnt << '\n'; 51 | // displayTreeInorder(root); 52 | } 53 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/deepestNode.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int deepestNode(Node *root, int i) 6 | { 7 | static int depthNode, cnt = INT_MIN; 8 | if (!root) 9 | { 10 | i--; 11 | return 0; 12 | } 13 | 14 | deepestNode(root->left, i + 1); 15 | if (i > cnt) 16 | { 17 | cnt = i; 18 | depthNode = root->data; 19 | cout << depthNode << " "; 20 | } 21 | deepestNode(root->right, i + 1); 22 | 23 | return depthNode; 24 | } 25 | 26 | int main() 27 | { 28 | Node *root = nullptr; 29 | insertNode(root, 50); 30 | insertNode(root, 60); 31 | insertNode(root, 70); 32 | insertNode(root, 80); 33 | insertNode(root, 90); 34 | insertNode(root, 55); 35 | insertNode(root, 10); 36 | insertNode(root, 5); 37 | insertNode(root, 40); 38 | cout << deepestNode(root, 0) << endl; 39 | } 40 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/fullNodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int findFullNodes(Node *root) 6 | { 7 | static int cnt; 8 | // If No node is present, return 1 9 | if (!root) 10 | return 1; 11 | 12 | // Go to the left. 13 | findFullNodes(root->left); 14 | 15 | // If there are two children for a node, then increase the count. 16 | if (root->left && root->right) 17 | cnt++; 18 | 19 | // Go to the right. 20 | findFullNodes(root->right); 21 | 22 | // Return the count. 23 | return cnt; 24 | } 25 | 26 | int main() 27 | { 28 | Node *root = nullptr; 29 | insertNode(root, 50); 30 | insertNode(root, 60); 31 | insertNode(root, 70); 32 | insertNode(root, 80); 33 | insertNode(root, 90); 34 | insertNode(root, 55); 35 | insertNode(root, 10); 36 | insertNode(root, 5); 37 | insertNode(root, 40); 38 | 39 | cout << findFullNodes(root) << "\n"; 40 | } 41 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/heightOfATree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int heightOfTree(Node *root) 6 | { 7 | int leftH, rightH; 8 | if (!root) 9 | return 0; 10 | else 11 | { 12 | leftH = heightOfTree(root->left); 13 | rightH = heightOfTree(root->right); 14 | 15 | if (leftH > rightH) 16 | return leftH + 1; 17 | else 18 | return rightH + 1; 19 | } 20 | } 21 | 22 | int main() 23 | { 24 | Node *root = nullptr; 25 | insertNode(root, 50); 26 | insertNode(root, 60); 27 | insertNode(root, 70); 28 | insertNode(root, 80); 29 | insertNode(root, 90); 30 | insertNode(root, 55); 31 | insertNode(root, 10); 32 | insertNode(root, 5); 33 | insertNode(root, 40); 34 | cout << heightOfTree(root) << endl; 35 | } 36 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/inorderIterative.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | void inorderIterative(Node *root) 6 | { 7 | Node *p = root; 8 | stack q; 9 | 10 | while (1) 11 | { 12 | while (root) 13 | { 14 | q.push(root); 15 | root = root->left; 16 | } 17 | if (q.empty()) 18 | break; 19 | 20 | root = q.top(); 21 | cout << root->data << " "; 22 | q.pop(); 23 | root = root->right; 24 | } 25 | } 26 | 27 | int main() 28 | { 29 | Node *root = nullptr; 30 | 31 | insertNode(root, 1); 32 | insertNode(root, 2); 33 | insertNode(root, 3); 34 | insertNode(root, 4); 35 | insertNode(root, 5); 36 | insertNode(root, 6); 37 | 38 | inorderIterative(root); 39 | } 40 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/isBST2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | bool isBST(Node *root, int min, int max) 6 | { 7 | if (!root) 8 | return true; 9 | 10 | if (root->data <= min || root->data > max) 11 | return false; 12 | 13 | bool left = isBST(root->left, min, root->data); 14 | bool right = isBST(root->right, root->data, max); 15 | 16 | return (left && right) ? true : false; 17 | } 18 | 19 | int main() 20 | { 21 | Node *root = nullptr; 22 | 23 | insertNode(root, 50); 24 | insertNode(root, 60); 25 | insertNode(root, 55); 26 | insertNode(root, 80); 27 | insertNode(root, 95); 28 | insertNode(root, 40); 29 | insertNode(root, 6); 30 | insertNode(root, 2); 31 | insertNode(root, 7); 32 | insertNode(root, 8); 33 | 34 | cout << isBST(root, INT_MIN, INT_MAX) << endl; 35 | } 36 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/isBst1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | bool isBST(Node *root, int min, int max) 6 | { 7 | if (!root) 8 | return true; 9 | 10 | if (root->data <= min || root->data > max) 11 | return false; 12 | 13 | return isBST(root->left, min, root->data) && isBST(root->right, root->data, max); 14 | } 15 | 16 | int main() 17 | { 18 | Node *root = nullptr; 19 | insertNode(root, 50); 20 | insertNode(root, 60); 21 | insertNode(root, 55); 22 | insertNode(root, 80); 23 | insertNode(root, 95); 24 | insertNode(root, 40); 25 | insertNode(root, 6); 26 | insertNode(root, 2); 27 | insertNode(root, 7); 28 | insertNode(root, 8); 29 | 30 | cout << isBST(root, INT_MIN, INT_MAX) << endl; 31 | } 32 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/isomorphicOrNot.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | bool isIsomorphic(Node *root1, Node *root2) 6 | { 7 | if (!root1 && !root2) 8 | return true; 9 | 10 | if ((!root1 && root2) || (root1 && !root2)) 11 | return false; 12 | 13 | return isIsomorphic(root1->left, root2->left) && isIsomorphic(root1->right, root2->right); 14 | } 15 | 16 | int main() 17 | { 18 | Node *root1 = nullptr; 19 | Node *root2 = nullptr; 20 | 21 | // Tree 1 22 | insertNode(root1, 100); 23 | insertNode(root1, 200); 24 | insertNode(root1, 3); 25 | insertNode(root1, 2); 26 | insertNode(root1, 7); 27 | 28 | // Tree 2 29 | insertNode(root2, 200); 30 | insertNode(root2, 300); 31 | insertNode(root2, 3); 32 | insertNode(root2, 2); 33 | insertNode(root2, 7); 34 | 35 | (isIsomorphic(root1, root2)) ? cout << "Are Isomorphic.." << '\n' : cout << "Not Isomorphic" << '\n'; 36 | } 37 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/kthLargestElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "basicTreeTemplate.h" 4 | using namespace std; 5 | 6 | int kthLargest(Node *root, vector &store) { 7 | if (!root) return 0; 8 | 9 | kthLargest(root->left,store); 10 | store.push_back(root->data); 11 | kthLargest(root->right,store); 12 | } 13 | 14 | 15 | int main() { 16 | Node *root = nullptr; 17 | vector store; 18 | 19 | insertNode(root, 50); 20 | insertNode(root, 60); 21 | insertNode(root, 55); 22 | insertNode(root, 40); 23 | insertNode(root, 20); 24 | insertNode(root, 30); 25 | int k; 26 | cin >> k; 27 | 28 | kthLargest(root,store); 29 | cout << "Kth Largest Element : "; 30 | cout << store[store.size()-k] << '\n'; 31 | } 32 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/leafNodesCount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | 4 | int leafNodes(Node *root) 5 | { 6 | if (!root) 7 | return 0; 8 | 9 | if (!root->left && !root->right) 10 | { 11 | return 1; 12 | } 13 | return leafNodes(root->right) + leafNodes(root->left); 14 | } 15 | 16 | int main() 17 | { 18 | Node *root = nullptr; 19 | insertNode(root, 50); 20 | insertNode(root, 60); 21 | insertNode(root, 70); 22 | insertNode(root, 80); 23 | insertNode(root, 90); 24 | insertNode(root, 55); 25 | insertNode(root, 10); 26 | insertNode(root, 5); 27 | insertNode(root, 40); 28 | 29 | cout << leafNodes(root) << endl; 30 | } 31 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/leastCommonAncestor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int leastCommonAncestor(Node *root, int d1, int d2) 6 | { 7 | if (!root) 8 | return 0; 9 | 10 | int left = leastCommonAncestor(root->left, d1, d2); 11 | 12 | if (root->data == d1 || root->data == d2) 13 | return root->data; 14 | 15 | int right = leastCommonAncestor(root->right, d1, d2); 16 | 17 | if (left != 0 && right != 0) 18 | return root->data; 19 | 20 | if (left == 0 && right == 0) 21 | return 0; 22 | 23 | if (left != 0) 24 | return left; 25 | else 26 | return right; 27 | } 28 | 29 | int main() 30 | { 31 | Node *root = nullptr; 32 | insertNode(root, 50); 33 | insertNode(root, 60); 34 | insertNode(root, 55); 35 | insertNode(root, 80); 36 | insertNode(root, 95); 37 | insertNode(root, 40); 38 | insertNode(root, 6); 39 | insertNode(root, 7); 40 | insertNode(root, 2); 41 | insertNode(root, 8); 42 | 43 | cout << "Least Common Ancestor is : " << leastCommonAncestor(root, 2, 8) << endl; 44 | } 45 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/leftSubTreeSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int leftTreeSum(Node *root) 6 | { 7 | static int sum; 8 | 9 | if (!root) 10 | return 0; 11 | 12 | leftTreeSum(root->left); 13 | sum += root->data; 14 | leftTreeSum(root->right); 15 | 16 | return sum; 17 | } 18 | 19 | int main() 20 | { 21 | Node *root = nullptr; 22 | insertNode(root, 50); 23 | insertNode(root, 40); 24 | insertNode(root, 6); 25 | insertNode(root, 2); 26 | insertNode(root, 7); 27 | insertNode(root, 8); 28 | insertNode(root, 60); 29 | insertNode(root, 55); 30 | insertNode(root, 80); 31 | insertNode(root, 95); 32 | 33 | cout << leftTreeSum(root->left) << endl; 34 | } 35 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/leftTreeView.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | #define max 50 4 | using namespace std; 5 | 6 | int *visited = new int[max]; 7 | void printLeftView(Node *root) { 8 | static int level; 9 | 10 | if (!root) return; 11 | 12 | if (!visited[level]) { 13 | cout << root->data << " "; 14 | visited[level] = true; 15 | } 16 | 17 | level++; 18 | printLeftView(root->left); 19 | printLeftView(root->right); 20 | level--; 21 | 22 | return; 23 | } 24 | 25 | int main() { 26 | Node *root = nullptr; 27 | int i; 28 | 29 | for (int i=0;i 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | static int max1 = INT_MIN; 6 | Node *maxInPath(Node *root, int a, int b) 7 | { 8 | if (!root) 9 | return nullptr; 10 | 11 | if (root->data > max1) 12 | max1 = root->data; 13 | 14 | if (root->data > a && root->data > b) 15 | { 16 | return maxInPath(root->left, a, b); 17 | } 18 | if (root->data < a && root->data < b) 19 | { 20 | return maxInPath(root->right, a, b); 21 | } 22 | return root; 23 | } 24 | 25 | int main() 26 | { 27 | Node *root = nullptr; 28 | 29 | insertNode(root, 18); 30 | insertNode(root, 36); 31 | insertNode(root, 37); 32 | insertNode(root, 35); 33 | insertNode(root, 9); 34 | insertNode(root, 12); 35 | insertNode(root, 10); 36 | insertNode(root, 6); 37 | insertNode(root, 1); 38 | insertNode(root, 8); 39 | 40 | root = maxInPath(root, 1, 10); 41 | max1 = INT_MIN; 42 | root = maxInPath(root->left, root->data, 1); 43 | root = maxInPath(root->right, root->data, 10); 44 | cout << max1 << endl; 45 | } 46 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/maxSumPath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | 4 | // Prints the path from the node to the Target node. 5 | void getPath(Node *root, int target) 6 | { 7 | if (!root) 8 | return; 9 | 10 | // If cuurent node value if lesser than target node value, print node value and then go right 11 | if (target > root->data) 12 | { 13 | cout << root->data << " "; 14 | getPath(root->right, target); 15 | } 16 | 17 | // else , print node value and then go left 18 | else 19 | { 20 | cout << root->data << " "; 21 | getPath(root->left, target); 22 | } 23 | } 24 | 25 | Node *maxSumPath(Node *root) 26 | { 27 | // Varible initializations.. 'static' as we want them to be unchanged throughout the recursive tree calls. 28 | static Node *target; 29 | static int index; 30 | static int count, trackPathSum = INT_MIN; 31 | static int *path = new int[30]; 32 | 33 | if (!root) 34 | return 0; 35 | 36 | // Storing the Data nodes in an array. 37 | path[index] = root->data; 38 | index++; 39 | 40 | // Increasing the sum. 41 | count += root->data; 42 | 43 | // If it is a leaf node. 44 | if (!root->left && !root->right) 45 | { 46 | // If the Current sum is greater than previous sum, then set this node as the target node. 47 | if (count > trackPathSum) 48 | { 49 | trackPathSum = count; 50 | target = root; 51 | } 52 | } 53 | 54 | maxSumPath(root->left); 55 | maxSumPath(root->right); 56 | 57 | // Decreasing the sum by the node's value when backtracking. 58 | count -= root->data; 59 | index--; 60 | 61 | // Return the Target Node. 62 | return target; 63 | } 64 | 65 | int main() 66 | { 67 | Node *root = nullptr; 68 | insertNode(root, 50); 69 | insertNode(root, 60); 70 | insertNode(root, 70); 71 | insertNode(root, 80); 72 | insertNode(root, 90); 73 | insertNode(root, 55); 74 | insertNode(root, 10); 75 | insertNode(root, 5); 76 | insertNode(root, 40); 77 | 78 | // Create a Temporary Node to store the resultant node.. 79 | Node *temp; 80 | temp = maxSumPath(root); 81 | 82 | // Shows the Path from the root to that Temp node. 83 | getPath(root, temp->data); 84 | cout << '\n'; 85 | } 86 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/mirrorTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | 4 | int *left, *right; 5 | Node *getMirror(Node *root) 6 | { 7 | Node *temp; 8 | if (!root) 9 | return 0; 10 | else 11 | { 12 | temp = root->left; 13 | root->left = root->right; 14 | root->right = temp; 15 | } 16 | return root; 17 | } 18 | 19 | int main() { 20 | Node *root = nullptr; 21 | insertNode(root, 50); 22 | insertNode(root, 60); 23 | insertNode(root, 70); 24 | insertNode(root, 80); 25 | insertNode(root, 90); 26 | insertNode(root, 55); 27 | insertNode(root, 10); 28 | insertNode(root, 5); 29 | insertNode(root, 40); 30 | 31 | cout << getMirror(root) << endl; 32 | } 33 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/nodesAtDistanceK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | void nodesAtDistanceK(Node *root, int K) 6 | { 7 | static int level; 8 | 9 | if (!root) 10 | return; 11 | 12 | if (level > K) 13 | return; 14 | 15 | if (K == level) 16 | cout << root->data << " "; 17 | 18 | level++; 19 | nodesAtDistanceK(root->left, K); 20 | nodesAtDistanceK(root->right, K); 21 | level--; 22 | } 23 | 24 | int main() 25 | { 26 | Node *root = nullptr; 27 | insertNode(root, 50); 28 | insertNode(root, 60); 29 | insertNode(root, 55); 30 | insertNode(root, 80); 31 | insertNode(root, 95); 32 | insertNode(root, 40); 33 | insertNode(root, 6); 34 | insertNode(root, 2); 35 | insertNode(root, 7); 36 | insertNode(root, 8); 37 | 38 | nodesAtDistanceK(root, 2); 39 | cout << '\n'; 40 | } 41 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/oddEvenLevelDifference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | #define max 50 4 | using namespace std; 5 | 6 | int *store = new int[max]; 7 | static int level; 8 | static int even, odd; 9 | 10 | int oddEvenDifference(Node *root) 11 | { 12 | if (!root) 13 | return 0; 14 | 15 | if (level % 2 == 0) even += root->data; 16 | else odd += root->data; 17 | 18 | store[level] += root->data; 19 | level++; 20 | oddEvenDifference(root->left); 21 | oddEvenDifference(root->right); 22 | level--; 23 | return 0; 24 | } 25 | 26 | int main() 27 | { 28 | Node *root = nullptr; 29 | 30 | for (int t=0;t 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int rightSubTree(Node *root) 6 | { 7 | static int sum; 8 | 9 | if (!root) 10 | return 0; 11 | 12 | rightSubTree(root->left); 13 | sum += root->data; 14 | rightSubTree(root->right); 15 | 16 | return sum; 17 | } 18 | 19 | int main() 20 | { 21 | Node *root = nullptr; 22 | insertNode(root, 50); 23 | insertNode(root, 40); 24 | insertNode(root, 6); 25 | insertNode(root, 2); 26 | insertNode(root, 7); 27 | insertNode(root, 8); 28 | insertNode(root, 60); 29 | insertNode(root, 55); 30 | insertNode(root, 80); 31 | insertNode(root, 95); 32 | 33 | cout << rightSubTree(root->right) << endl; 34 | } 35 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/secondLargest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "basicTreeTemplate.h" 4 | using namespace std; 5 | 6 | int secondLargest(Node *root, vector &store) 7 | { 8 | static int ind; 9 | if (!root) 10 | return 0; 11 | 12 | secondLargest(root->left, store); 13 | store.push_back(root->data); 14 | secondLargest(root->right, store); 15 | } 16 | int main() 17 | { 18 | Node *root = nullptr; 19 | static vector store; 20 | 21 | insertNode(root, 50); 22 | insertNode(root, 60); 23 | insertNode(root, 55); 24 | insertNode(root, 40); 25 | insertNode(root, 20); 26 | insertNode(root, 30); 27 | secondLargest(root, store); 28 | cout << store[store.size() - 2] << endl; 29 | } 30 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/sumOfAllNodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | 4 | 5 | int sumOfAllNodes(Node *root) 6 | { 7 | if (!root) 8 | return 0; 9 | 10 | return (sumOfAllNodes(root->left) + sumOfAllNodes(root->right) + root->data); 11 | } 12 | 13 | int main() { 14 | Node *root = nullptr; 15 | insertNode(root, 50); 16 | insertNode(root, 60); 17 | insertNode(root, 70); 18 | insertNode(root, 80); 19 | insertNode(root, 90); 20 | insertNode(root, 55); 21 | insertNode(root, 10); 22 | insertNode(root, 5); 23 | insertNode(root, 40); 24 | 25 | cout << sumOfAllNodes(root) << endl; 26 | } 27 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/swapOddLevelNodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | #include 4 | using namespace std; 5 | 6 | list store; 7 | void swapOddLevel(Node *root) 8 | { 9 | static int cnt; 10 | if (!root) 11 | return; 12 | 13 | if (cnt % 2 != 0) 14 | { 15 | store.push_back(root->data); 16 | } 17 | cnt++; 18 | swapOddLevel(root->left); 19 | swapOddLevel(root->right); 20 | cnt--; 21 | return; 22 | } 23 | 24 | int main() 25 | { 26 | Node *root = nullptr; 27 | 28 | insertNode(root, 50); 29 | insertNode(root, 30); 30 | insertNode(root, 35); 31 | insertNode(root, 55); 32 | insertNode(root, 60); 33 | insertNode(root, 66); 34 | insertNode(root, 59); 35 | insertNode(root, 10); 36 | insertNode(root, 23); 37 | insertNode(root, 90); 38 | insertNode(root, 88); 39 | 40 | swapOddLevel(root); 41 | 42 | list::iterator i; 43 | 44 | // store.reverse(); 45 | for (i = store.begin(); i != store.end(); i++) 46 | { 47 | cout << *i << " "; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | Node *root = NULL; 8 | insertNode(root, 1); 9 | insertNode(root, 2); 10 | insertNode(root, 3); 11 | insertNode(root, 4); 12 | insertNode(root, 5); 13 | insertNode(root, 6); 14 | insertNode(root, 7); 15 | insertNode(root, 8); 16 | insertNode(root, 9); 17 | 18 | inorderIterative(root); 19 | } -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/verticalSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | static int col; 6 | static int ind; 7 | int verticalSum(Node *root, int col, int hash[], int store[]) 8 | { 9 | if (!root) 10 | return 0; 11 | 12 | verticalSum(root->left, col - 1, hash, store); 13 | hash[col] += root->data; 14 | store[ind] = col; 15 | ind++; 16 | verticalSum(root->right, col + 1, hash, store); 17 | } 18 | 19 | int main() { 20 | int *hash = new int[30]; 21 | int *store = new int[30]; 22 | Node *root = nullptr; 23 | insertNode(root, 50); 24 | insertNode(root, 60); 25 | insertNode(root, 70); 26 | insertNode(root, 80); 27 | insertNode(root, 90); 28 | insertNode(root, 55); 29 | insertNode(root, 10); 30 | insertNode(root, 5); 31 | insertNode(root, 40); 32 | 33 | // cout << verticalSum(root,col,hash,store) << endl; 34 | } 35 | -------------------------------------------------------------------------------- /Trees/Binary_Search_Tree/zigZagTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "basicTreeTemplate.h" 4 | using namespace std; 5 | 6 | list *adj = new list[10]; 7 | static int i; 8 | 9 | int zigZag(Node *root) 10 | { 11 | static int max = INT_MIN; 12 | if (!root) 13 | return 0; 14 | 15 | adj[i].push_back(root->data); 16 | i++; 17 | if (i > max) 18 | max = i; 19 | zigZag(root->left); 20 | zigZag(root->right); 21 | i--; 22 | return max; 23 | } 24 | 25 | int main() 26 | { 27 | Node *root = nullptr; 28 | insertNode(root, 100); 29 | insertNode(root, 200); 30 | insertNode(root, 250); 31 | insertNode(root, 150); 32 | insertNode(root, 50); 33 | insertNode(root, 20); 34 | insertNode(root, 75); 35 | insertNode(root, 10); 36 | insertNode(root, 30); 37 | insertNode(root, 60); 38 | insertNode(root, 125); 39 | insertNode(root, 175); 40 | insertNode(root, 225); 41 | insertNode(root, 300); 42 | 43 | int max = zigZag(root); 44 | 45 | list::iterator itr; 46 | 47 | for (int t = 0; t < max; t++) 48 | { 49 | if (t % 2 != 0) 50 | adj[t].reverse(); 51 | 52 | for (itr = adj[t].begin(); itr != adj[t].end(); itr++) 53 | { 54 | cout << *itr << " -- "; 55 | } 56 | cout << endl; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Trees/Binary_Tree/BFS_newLines.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "createDefaultTree.hpp" 4 | #include "basicTreeTemplate.h" 5 | using namespace std; 6 | 7 | void BFSNL(BNode *root) { 8 | queue q; 9 | q.push(root); 10 | int ct = q.size(); 11 | while (!q.empty()) { 12 | while (ct--) { 13 | BNode *now = q.front(); 14 | cout << now->data << " "; 15 | q.pop(); 16 | 17 | if (now->left) q.push(now->left); 18 | if (now->right) q.push(now->right); 19 | } 20 | 21 | ct = q.size(); 22 | cout << endl; 23 | } 24 | } 25 | 26 | int main() { 27 | BNode *root = createDefaultTree(); 28 | 29 | BFSNL(root); 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Trees/Binary_Tree/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Trees/Binary_Tree/a.out -------------------------------------------------------------------------------- /Trees/Binary_Tree/basicTreeTemplate.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | struct BNode 9 | { 10 | int data; 11 | BNode *left; 12 | BNode *right; 13 | }; 14 | 15 | BNode *createNode(int data) 16 | { 17 | BNode *temp = new BNode(); 18 | temp->data = data; 19 | temp->left = NULL; 20 | temp->right = NULL; 21 | 22 | return temp; 23 | } 24 | 25 | void insertNode(BNode *root, int data) 26 | { 27 | queue nq; 28 | nq.push(root); 29 | 30 | while (!nq.empty()) { 31 | root = nq.front(); 32 | nq.pop(); 33 | 34 | if (!root->left) { 35 | root->left = createNode(data); 36 | break; 37 | } else { 38 | nq.push(root->left); 39 | } 40 | 41 | if (!root->right) { 42 | root->right = createNode(data); 43 | break; 44 | } else { 45 | nq.push(root->right); 46 | } 47 | } 48 | return; 49 | } 50 | 51 | void inOrderTraversalRecursive(BNode *root) { 52 | if (!root) return; 53 | 54 | inOrderTraversalRecursive(root->left); 55 | cout << root->data << " "; 56 | inOrderTraversalRecursive(root->right); 57 | 58 | return; 59 | } 60 | 61 | void preOrderTraversalRecursive(BNode *root) { 62 | if (!root) return; 63 | 64 | cout << root->data << " "; 65 | preOrderTraversalRecursive(root->left); 66 | preOrderTraversalRecursive(root->right); 67 | return; 68 | } 69 | 70 | void postOrderTraversalRecursive(BNode *root) { 71 | if (!root) return; 72 | 73 | postOrderTraversalRecursive(root->left); 74 | postOrderTraversalRecursive(root->right); 75 | cout << root->data << " "; 76 | return; 77 | } 78 | -------------------------------------------------------------------------------- /Trees/Binary_Tree/binarySum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | #include 4 | #include 5 | using namespace std; 6 | static int sum; 7 | vector< queue > store; 8 | queue path, temp; 9 | 10 | void printStore() { 11 | for (int t=0;tdata); 27 | 28 | if (!root->left && !root->right) 29 | store.push_back(path); 30 | 31 | findBinarySum(root->left); 32 | path.pop(); 33 | findBinarySum(root->right); 34 | printStore(); 35 | } 36 | 37 | 38 | int main() 39 | { 40 | BNode *root = createNode(1); 41 | root->left = createNode(1); 42 | root->right = createNode(0); 43 | root->left->left = createNode(0); 44 | root->left->right = createNode(1); 45 | root->right->left = createNode(1); 46 | root->right->right = createNode(0); 47 | 48 | findBinarySum(root); 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Trees/Binary_Tree/boundaryTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "basicTreeTemplate.h" 5 | using namespace std; 6 | vector *vc = new vector[30]; 7 | static int level, maxm = INT_MIN; 8 | 9 | void boundaryTrav(BNode *root) { 10 | if (!root) 11 | return; 12 | 13 | vc[level].push_back(root->data); 14 | level++; 15 | if (level > maxm) 16 | maxm = level; 17 | 18 | boundaryTrav(root->left); 19 | boundaryTrav(root->right); 20 | level--; 21 | } 22 | 23 | int main() { 24 | BNode *root = createNode(20); 25 | root->left = createNode(8); 26 | root->left->left = createNode(4); 27 | root->left->right = createNode(12); 28 | root->left->right->left = createNode(10); 29 | root->left->right->right = createNode(14); 30 | root->right = createNode(22); 31 | root->right->right = createNode(25); 32 | 33 | boundaryTrav(root); 34 | 35 | for (int t = 0; t < maxm; t++) { 36 | cout << vc[t].front() << " "; 37 | } 38 | for (int t = maxm - 1; t >= 1; t--) { 39 | cout << vc[t].back() << " "; 40 | } 41 | cout << endl; 42 | } -------------------------------------------------------------------------------- /Trees/Binary_Tree/boundaryTraversalRecursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | void printRightBoundary(BNode *root) 6 | { 7 | if (!root || (!root->left && !root->right)) 8 | return; 9 | 10 | printRightBoundary(root->right); 11 | cout << root->data << " "; 12 | } 13 | 14 | void printLeaves(BNode *root) 15 | { 16 | if (!root) 17 | return; 18 | 19 | printLeaves(root->left); 20 | 21 | if (!root->left && !root->right) 22 | cout << root->data << " "; 23 | 24 | printLeaves(root->right); 25 | } 26 | 27 | void printLeftBoundary(BNode *root) 28 | { 29 | if (!root || (!root->left && !root->right)) 30 | return; 31 | 32 | cout << root->data << " "; 33 | printLeftBoundary(root->left); 34 | } 35 | 36 | void boundaryTrav(BNode *root) 37 | { 38 | printLeftBoundary(root); 39 | printLeaves(root); 40 | printRightBoundary(root->right); 41 | } 42 | 43 | int main() 44 | { 45 | BNode *root = createNode(20); 46 | root->left = createNode(8); 47 | root->left->left = createNode(4); 48 | root->left->right = createNode(12); 49 | root->left->right->left = createNode(10); 50 | root->left->right->right = createNode(14); 51 | root->right = createNode(22); 52 | root->right->right = createNode(25); 53 | 54 | boundaryTrav(root); 55 | } -------------------------------------------------------------------------------- /Trees/Binary_Tree/createDefaultTree.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | #include 4 | using namespace std; 5 | 6 | BNode *createDefaultTree() { 7 | BNode *root = new BNode(); 8 | root = createNode(1); 9 | root->left = createNode(2); 10 | root->right = createNode(3); 11 | root->left->left = createNode(4); 12 | root->left->right = createNode(5); 13 | root->right->left = createNode(6); 14 | root->right->right = createNode(7); 15 | 16 | return root; 17 | } 18 | -------------------------------------------------------------------------------- /Trees/Binary_Tree/diagnolTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | void diagnolTraversal(BNode *root) {} 8 | 9 | int main() { 10 | BNode *root = createNode(1); 11 | root->left = createNode(2); 12 | root->right = createNode(3); 13 | root->left->left = createNode(4); 14 | root->left->right = createNode(5); 15 | root->right->left = createNode(6); 16 | root->right->right = createNode(7); 17 | 18 | diagnolTraversal(root); 19 | } 20 | -------------------------------------------------------------------------------- /Trees/Binary_Tree/maximumElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | int maximumElementRecursive(BNode *root) { 5 | 6 | static int maxim = INT_MIN; 7 | if (!root) return 0; 8 | 9 | (root->data > maxim) ? maxim = root->data : NULL; 10 | 11 | maximumElementRecursive(root->left); 12 | maximumElementRecursive(root->right); 13 | 14 | return maxim; 15 | } 16 | 17 | int main() { 18 | BNode *root = createNode(0); 19 | 20 | insertNode(root, 1); 21 | insertNode(root, 2); 22 | insertNode(root, 10); 23 | insertNode(root, 21); 24 | insertNode(root, 123); 25 | insertNode(root, 22); 26 | insertNode(root, 11); 27 | 28 | cout << maximumElementRecursive(root) << endl; 29 | } 30 | -------------------------------------------------------------------------------- /Trees/Binary_Tree/mergeBinaryTrees.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | 5 | BNode *mergeTrees(BNode *root1, BNode *root2) { 6 | if (!root1) 7 | return root2; 8 | if (!root2) 9 | return root1; 10 | 11 | root1->data += root2->data; 12 | root1->left = mergeTrees(root1->left, root2->left); 13 | root1->right = mergeTrees(root1->right, root2->right); 14 | 15 | return root1; 16 | } 17 | 18 | int main() { 19 | BNode *root1 = createNode(1); 20 | root1->left = createNode(3); 21 | root1->right = createNode(2); 22 | root1->left->left = createNode(5); 23 | 24 | BNode *root2 = createNode(2); 25 | root2->left = createNode(1); 26 | root2->right = createNode(3); 27 | root2->left->right = createNode(4); 28 | root2->right->right = createNode(7); 29 | 30 | 31 | BNode *root3 = mergeTrees(root1, root2); 32 | preOrderTraversalRecursive(root3); 33 | cout << endl; 34 | } -------------------------------------------------------------------------------- /Trees/Binary_Tree/minimumElement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basicTreeTemplate.h" 3 | using namespace std; 4 | int maximumElementRecursive(BNode *root) { 5 | 6 | static int minim = INT_MAX; 7 | if (!root) return 0; 8 | 9 | (root->data < minim) ? minim = root->data : NULL; 10 | 11 | maximumElementRecursive(root->left); 12 | maximumElementRecursive(root->right); 13 | 14 | return minim; 15 | } 16 | 17 | int main() { 18 | BNode *root = createNode(0); 19 | 20 | insertNode(root, 1); 21 | insertNode(root, 2); 22 | insertNode(root, 10); 23 | insertNode(root, -10); 24 | insertNode(root, 21); 25 | insertNode(root, 123); 26 | insertNode(root, 22); 27 | insertNode(root, 11); 28 | 29 | cout << maximumElementRecursive(root) << endl; 30 | } 31 | -------------------------------------------------------------------------------- /Trees/Binary_Tree/nodesAtDistanceD.cpp: -------------------------------------------------------------------------------- 1 | #include "basicTreeTemplate.h" 2 | using namespace std; 3 | 4 | int getDistanceFromRoot(BNode *root, BNode *target, int dist) { 5 | static int trvDist = -1; 6 | if (!root) { 7 | return 0; 8 | } 9 | 10 | if (root == target) { 11 | trvDist = dist; 12 | return dist; 13 | } 14 | 15 | getDistanceFromRoot(root->left, target, ++dist); 16 | --dist; 17 | getDistanceFromRoot(root->right, target, ++dist); 18 | --dist; 19 | return trvDist; 20 | } 21 | 22 | void getNodesAtDistanceD(BNode *root, BNode *target, int d, int lvl) { 23 | if (!root) 24 | return; 25 | 26 | if ((lvl == d) && (root != target)) 27 | cout << root->data << " "; 28 | 29 | getNodesAtDistanceD(root->left, target, d, ++lvl); 30 | --lvl; 31 | getNodesAtDistanceD(root->right, target, d, ++lvl); 32 | --lvl; 33 | } 34 | 35 | int main() { 36 | BNode *root = createNode(10); 37 | BNode *target = root->left = createNode(20); 38 | root->right = createNode(30); 39 | root->left->left = createNode(35); 40 | root->left->right = createNode(38); 41 | root->right->left = createNode(40); 42 | root->right->right = createNode(47); 43 | root->left->left->left = createNode(50); 44 | root->left->right->left = createNode(44); 45 | root->right->left->left = createNode(60); 46 | 47 | getNodesAtDistanceD(target, target, 2, 0); 48 | int dist = getDistanceFromRoot(root, target, 0); 49 | getNodesAtDistanceD(root, target, (2 - dist), 0); 50 | } -------------------------------------------------------------------------------- /Trees/Binary_Tree/shortestRootToLeafPath.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "basicTreeTemplate.h" 4 | using namespace std; 5 | vector store, perStore; 6 | int findPathLength(BNode *root, int target) { 7 | static int length = -1, minLength = INT_MAX; 8 | if (!root) return 0; 9 | 10 | length++; 11 | store.push_back(root->data); 12 | findPathLength(root->left, target-(root->data)); 13 | findPathLength(root->right, target-(root->data)); 14 | 15 | if (target == root->data && !root->left && !root->right) { 16 | if (length < minLength) { 17 | minLength = length; 18 | perStore = store; 19 | } 20 | } 21 | length--; 22 | store.pop_back(); 23 | return (minLength == INT_MAX) ? -1 : minLength; 24 | 25 | } 26 | 27 | int main() { 28 | BNode *root = createNode(1); 29 | insertNode(root, 10); 30 | insertNode(root, 15); 31 | insertNode(root, 5); 32 | insertNode(root, 2); 33 | 34 | cout << findPathLength(root, 16) << endl; 35 | 36 | for (auto itr = perStore.begin(); itr != perStore.end(); itr++) 37 | if (itr != perStore.end() - 1) 38 | cout << *itr << " -> "; 39 | else 40 | cout << *itr; 41 | 42 | cout << endl; 43 | } -------------------------------------------------------------------------------- /Trie/BaseTemplate.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define alpha_size 26 4 | #define CHAR_TO_INDEX(c) ((int)c - (int)'a') 5 | using namespace std; 6 | string word; 7 | struct TrieNode { 8 | bool eOF; 9 | TrieNode *children[alpha_size]; 10 | int freq; 11 | }; 12 | 13 | // Create and Return a New Trie Node. 14 | struct TrieNode *createNode() { 15 | TrieNode *pNode = new TrieNode; 16 | pNode->eOF = false; 17 | 18 | for (int t = 0; t < alpha_size; t++) { 19 | pNode->children[t] = nullptr; 20 | } 21 | return pNode; 22 | } 23 | 24 | // Insert a word into a Trie. 25 | void insert(string key, TrieNode *root) { 26 | TrieNode *crawl = root; 27 | 28 | for (int t = 0; t < key.length(); t++) { 29 | int index = key[t] - 'a'; 30 | 31 | if (!crawl->children[index]) { 32 | crawl->children[index] = createNode(); 33 | } 34 | 35 | crawl = crawl->children[index]; 36 | // crawl->freq++; Uncomment for Count of every node hit count. 37 | } 38 | crawl->freq++; // For the count of word hit count. 39 | crawl->eOF = true; 40 | } 41 | 42 | // Search for a word in the Dictionary. 43 | bool search(string key, TrieNode *root) { 44 | TrieNode *crawl = root; 45 | 46 | for (int t = 0; t < key.length(); t++) { 47 | int index = key[t] - 'a'; 48 | 49 | if (!crawl->children[index]) 50 | return false; 51 | 52 | crawl = crawl->children[index]; 53 | } 54 | return (crawl != nullptr && crawl->eOF); 55 | } 56 | 57 | bool isLastNode(TrieNode *root) { 58 | for (int t = 0; t < alpha_size; t++) { 59 | if (root->children[t]) 60 | return false; 61 | } 62 | return true; 63 | } 64 | 65 | void suggestWords(string prefix, TrieNode *root) { 66 | if (root->eOF == true) 67 | cout << prefix << endl; 68 | 69 | if (isLastNode(root)) { 70 | return; 71 | } 72 | 73 | for (int t = 0; t < alpha_size; t++) { 74 | if (root->children[t]) { 75 | prefix.push_back(97 + t); 76 | suggestWords(prefix, root->children[t]); 77 | prefix.pop_back(); 78 | } 79 | } 80 | return; 81 | } 82 | 83 | int autoSuggest(TrieNode *root, const string query) { 84 | TrieNode *crawl = root; 85 | int level; 86 | int n = query.length(); 87 | 88 | for (level = 0; level < n; level++) { 89 | int ind = CHAR_TO_INDEX(query[level]); 90 | 91 | if (!crawl->children[ind]) 92 | return 0; 93 | 94 | crawl = crawl->children[ind]; 95 | } 96 | 97 | bool isWord = (crawl->eOF == true); 98 | bool isLast = isLastNode(crawl); 99 | 100 | if (isWord && isLast) { 101 | cout << query << endl; 102 | return -1; 103 | } 104 | 105 | if (!isLast) { 106 | string prefix = query; 107 | suggestWords(prefix, crawl); 108 | return 1; 109 | } 110 | return 0; 111 | } 112 | 113 | void printDictionary(TrieNode *root) { 114 | if (root->eOF) 115 | cout << word << endl; 116 | 117 | if (isLastNode(root)) 118 | return; 119 | 120 | for (int t = 0; t < alpha_size; t++) { 121 | if (root->children[t]) { 122 | word.push_back(97 + t); 123 | printDictionary(root->children[t]); 124 | word.pop_back(); 125 | } 126 | } 127 | return; 128 | } 129 | -------------------------------------------------------------------------------- /Trie/Dict.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "./BaseTemplate.hpp" 4 | #define clck high_resolution_clock::now(); 5 | #define differ duration_cast(stop - start); 6 | using namespace std; 7 | using namespace std::chrono; 8 | 9 | void takeUp(TrieNode *root, string prefix) { 10 | if (root->eOF) 11 | cout << prefix << " "; 12 | 13 | if (isLastNode(root)) 14 | return; 15 | 16 | for (int t = 0; t < 26; t++) { 17 | if (root->children[t]) { 18 | prefix.push_back(97 + t); 19 | takeUp(root->children[t], prefix); 20 | prefix.pop_back(); 21 | } 22 | } 23 | return; 24 | } 25 | 26 | void displayContacts(TrieNode *root, string qry) { 27 | int n = qry.length(), level; 28 | TrieNode *crawl = root; 29 | string word; 30 | 31 | for (level = 0; level < n; level++) { 32 | int ind = qry[level] - 'a'; 33 | if (!crawl->children[ind]) 34 | return; 35 | 36 | word.push_back(97 + ind); 37 | cout << "Suggestions for " << word << " "; 38 | crawl = crawl->children[ind]; 39 | takeUp(crawl, word); 40 | cout << endl; 41 | } 42 | } 43 | 44 | int main() { 45 | auto start = high_resolution_clock::now(); 46 | 47 | TrieNode *root = new TrieNode(); 48 | root = createNode(); 49 | insert("rubens", root); 50 | insert("romane", root); 51 | insert("romanus", root); 52 | insert("romulus", root); 53 | insert("ruber", root); 54 | insert("rubicon", root); 55 | insert("rubicundus", root); 56 | 57 | auto stop = high_resolution_clock::now(); 58 | auto duration = duration_cast(stop - start); 59 | cout << duration.count() << '\n'; 60 | } -------------------------------------------------------------------------------- /Trie/README.md: -------------------------------------------------------------------------------- 1 | ![Trie.](https://miro.medium.com/max/3264/1*sZOrNXzlQICVv5ePpav1-g.jpeg) 2 | 3 | 4 | ### Introduction. 5 | 6 | Trie (Prefix-Tree) is an Data-Structure used for Efficient string queries and manipulations. 7 | It is a bit hard to build, but after building the tree, It is really helpful in solving complicated problems. 8 | 9 | 10 | ### Structure. 11 | 12 | Each Node holds a character and many nodes are connected to form a string. 13 | Each node can have upto 26 children (As there are 26 characters). Also, Each Node has an EOS flag 14 | which indicates whether any string ends at this node or not. We can denote the character using an ASCII value. 15 | Small English letters start from 97 and range till (97+25). 16 | 17 | ### Build. 18 | 19 | Building a tree may be divided into following steps. Lets go with the example that you want to insert "hello". 20 | 21 | - From the root, Search for the letter 'h'. If not found, create that node and move root there. 22 | - From the current Node, search for the letter 'e'. If not found, create that node and move root there. 23 | - From the current Node, search for the letter 'l', If not found, create that node and move root there. 24 | - From the current Node, search for the letter 'l', If not found, create that node and move root there. 25 | - From the current Node, search for the letter 'o', If not found, create that node and move root there. 26 | - As we have reached the end of string, we mark the node 'o' as EOS = true as it indicates that the string 27 | "hello" ends here. 28 | 29 | Similarly, when inserting any other string, we may encounter that the current node may already have that child. 30 | In that case, just move to that node without creating any new node. 31 | 32 | ### Query 33 | 34 | Querying is similar to Building. Keep checking if there is child node at index (say i), If there is, move there. 35 | Else, say that the string isn't present in the tree. If you have reached the last index of string (i = n-1), 36 | Then check for the EOS flag of the last node. If its TRUE, String is present in the tree. Else its not. 37 | 38 | ### Time Complexity 39 | 40 | - Building a Trie: O(n*m), where n is total number of strings and m is the length(avg) of all strings combined. 41 | - Query: O(m), where m is the length of the string being queried. 42 | 43 | ### Conclusion 44 | This Trie may sometimes end up being costly, there is an optimized version of Trie called as "Compressed Trie". 45 | It compresses many letters into a single word to avoid un-necessary travel down. 46 | -------------------------------------------------------------------------------- /Trie/TrieFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BaseTemplate.h" 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | struct TrieNode *root = createNode(); 9 | string dictionary[100]; 10 | int ch; 11 | string word; 12 | 13 | while (true) 14 | { 15 | cout << "\n"; 16 | cout << "1. Add Word to Dictionary.\n2.Check if a Word is present in the Dictionary.\n3.Get all the words with the given Prefix.\n4.Exit" << '\n'; 17 | cout << "\n"; 18 | cin >> ch; 19 | 20 | switch (ch) 21 | { 22 | case 1: { 23 | cout << "Enter Word: "; 24 | cin >> word; 25 | insert(word,root); 26 | cout << "\n"; 27 | cout << "Word Inserted !" << '\n'; 28 | break; 29 | } 30 | case 2: { 31 | cout << "Enter Word: "; 32 | cin >> word; 33 | cout << "\n"; 34 | (search(word, root)) ? cout << "Word Found in the Dictionary!" << '\n' : cout << "Word not found in the Dictionary." << '\n'; 35 | cout << "\n"; 36 | break; 37 | } 38 | case 3: { 39 | cout << "Enter Prefix: "; 40 | cin >> word; 41 | cout << "\n"; 42 | int res = autoSuggest(root, word); 43 | if (res == -1) { 44 | cout << "No word other than the Prefix found in the Dictionary." << '\n'; 45 | } else if (!res) { 46 | cout << "No words found with this in the Dictionary." << '\n'; 47 | } 48 | break; 49 | } 50 | case 4: 51 | exit(0); 52 | 53 | default: 54 | cout << "Choice not available." << '\n'; 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /Trie/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/Trie/a.out -------------------------------------------------------------------------------- /Trie/countStrings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BaseTemplate.h" 3 | using namespace std; 4 | 5 | int getCountPrefix(TrieNode *root, int k, string str) 6 | { 7 | int t, count = 0; 8 | TrieNode *crawl = root; 9 | 10 | for (t = 0; t < k; t++) 11 | { 12 | int ind = str[t] - 'a'; 13 | 14 | if (!crawl->children[ind]) 15 | return 0; 16 | 17 | crawl = crawl->children[ind]; 18 | } 19 | return crawl->freq; 20 | } 21 | 22 | int main() 23 | { 24 | string arr[] = {"abba", "abbb", "abbc", "abbd", "abaa", "abca", "abba", "abba", "abba"}; 25 | int k = 3, n = (sizeof(arr) / sizeof(arr[0])), t; 26 | string str = "abbg"; 27 | 28 | TrieNode *root = createNode(); 29 | 30 | for (t = 0; t < n; t++) 31 | { 32 | insert(arr[t], root); 33 | } 34 | 35 | int count = getCountPrefix(root, k, str); 36 | cout << count << endl; 37 | } -------------------------------------------------------------------------------- /Trie/maxFreq.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BaseTemplate.h" 3 | #define ALPHA_SIZE 26 4 | using namespace std; 5 | static int min_ = INT_MIN; 6 | string baseWord, currentWord; 7 | 8 | 9 | void countMaxFreq(TrieNode *root) { 10 | int t; 11 | TrieNode *crawl = root; 12 | // cout << "Current Word : " << currentWord << " " << "Word's Frequency : " << crawl->freq << endl; 13 | 14 | if (crawl->eOF) { 15 | if (crawl->freq > min_) { 16 | min_ = crawl->freq; 17 | baseWord = currentWord; 18 | } 19 | } 20 | 21 | if (isLastNode(root)) 22 | return; 23 | 24 | for (t=0;tchildren[t]) { 26 | currentWord.push_back(97 + t); 27 | countMaxFreq(crawl->children[t]); 28 | currentWord.pop_back(); 29 | } 30 | } 31 | return; 32 | } 33 | 34 | int main() 35 | { 36 | int t; 37 | string dictionary[] = {"abba", "abbb", "abbc", "abbd", "abaa", "abca", "abba", "abba", "abba", "abbc"}; 38 | int n = sizeof(dictionary) / sizeof(dictionary[0]); 39 | 40 | TrieNode *root = createNode(); 41 | 42 | for (t = 0; t < n; t++) 43 | insert(dictionary[t], root); 44 | 45 | countMaxFreq(root); 46 | cout << baseWord << endl; 47 | } -------------------------------------------------------------------------------- /Trie/replaceWords.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | string a = "hey there from the earth"; 7 | string rep = "world"; 8 | 9 | cout << a << endl; 10 | a.replace(0, 3, rep); 11 | cout << a << endl; 12 | } -------------------------------------------------------------------------------- /Trie/searchWord.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BaseTemplate.h" 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | struct TrieNode *root = createNode(); 8 | 9 | string paragraph[] = {"hey" 10 | "there", 11 | "i", "am", "manosrira", "manosriram", "and", "this", "is", "an", "example", "of", "trie", "data", "structure", "manomano", "hello", "helium", "heart", "hate", "anyways"}; 12 | 13 | int n = sizeof(paragraph) / sizeof(paragraph[0]); 14 | for (int t = 0; t < n; t++) 15 | { 16 | insert(paragraph[t], root); 17 | } 18 | string key; 19 | // cin >> key; 20 | // search(key, root) ? cout << "Word found !" << '\n' : cout << "Word Not Found." << '\n'; 21 | printDictionary(root); 22 | } -------------------------------------------------------------------------------- /Trie/searchWordsWithGivenPrefix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "BaseTemplate.h" 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | struct TrieNode *root = createNode(); 8 | string paragraph[] = {"hey" 9 | "there", 10 | "i", "am", "manosrira", "manosriram", "master", "and", "this", "is", "an", "example", "of", "trie", "data", "structure", "manomano", "hello", "helium", "heart", "hate"}; 11 | 12 | int n = sizeof(paragraph) / sizeof(paragraph[0]); 13 | for (int t = 0; t < n; t++) 14 | { 15 | insert(paragraph[t], root); 16 | } 17 | string query; 18 | cin >> query; 19 | int res = autoSuggest(root, query); 20 | if (res == -1) 21 | cout << "No Other Words found other than the Prefix Itself !" << '\n'; 22 | 23 | if (!res) 24 | cout << "No Words found with this Prefix" << '\n'; 25 | } -------------------------------------------------------------------------------- /XOR-Linked-List/Includes.hpp: -------------------------------------------------------------------------------- 1 | #ifndef INC 2 | #define INC 3 | 4 | #include 5 | #include 6 | using std::cout; 7 | using std::cin; 8 | 9 | 10 | #endif 11 | -------------------------------------------------------------------------------- /XOR-Linked-List/Src.cpp: -------------------------------------------------------------------------------- 1 | #include "./Structure.hpp" 2 | 3 | /* 4 | * Next Node: XOR(prev, currentNode->npx); 5 | * Prev Node: XOR(next, currentNode->npx); 6 | */ 7 | 8 | Node *XOR(Node *A, Node *B) { 9 | return (Node *) ((uintptr_t)(A) ^ (uintptr_t)(B)); 10 | } 11 | 12 | Node *returnLastNode(Node *head) { 13 | Node *prev = nullptr, *current = head, *next; 14 | 15 | next = XOR(prev, current->npx); 16 | while (next) { 17 | next = XOR(prev, current->npx); 18 | prev = current; 19 | current = next; 20 | } 21 | return prev; 22 | } 23 | 24 | void Insert(Node **head, int data) { 25 | Node *newNode = new Node(); 26 | newNode->dt = data; 27 | 28 | newNode->npx = XOR(*head, nullptr); 29 | 30 | if (*head) { 31 | Node *next = XOR((*head)->npx, nullptr); 32 | (*head)->npx = XOR(newNode, next); 33 | } 34 | *head = newNode; 35 | } 36 | 37 | void printLLBackward(Node *head) { 38 | Node *next = nullptr, *current = head, *prev; 39 | 40 | while (current) { 41 | cout << current->dt << " "; 42 | 43 | prev = XOR(next, current->npx); 44 | next = current; 45 | current = prev; 46 | } 47 | return; 48 | } 49 | 50 | void printLLForward(Node *head) { 51 | Node *prev = nullptr, *current = head, *next; 52 | 53 | while (current) { 54 | cout << current->dt << " "; 55 | 56 | next = XOR(prev, current->npx); 57 | prev = current; 58 | current = next; 59 | } 60 | return; 61 | } 62 | 63 | int main() { 64 | Node *head = nullptr; 65 | 66 | Insert(&head, 5); 67 | Insert(&head, 8); 68 | Insert(&head, 2); 69 | 70 | 71 | printLLForward(head); // nullptr <-> 2 <-> 8 <-> 5 <-> nullptr 72 | 73 | printLLBackward(returnLastNode(head)); // nullptr <-> 5 <-> 8 <-> 2 <-> nullptr 74 | } 75 | -------------------------------------------------------------------------------- /XOR-Linked-List/Structure.hpp: -------------------------------------------------------------------------------- 1 | #include "./Includes.hpp" 2 | 3 | struct Node { 4 | int dt; 5 | Node *npx; 6 | }; 7 | 8 | -------------------------------------------------------------------------------- /XOR-Linked-List/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/XOR-Linked-List/a.out -------------------------------------------------------------------------------- /queue/README.md: -------------------------------------------------------------------------------- 1 | ### Queue Data-Structure. 2 | ``` 3 | Contributors: Mano Sriram and Viswalahari. 4 | ``` 5 | -------------------------------------------------------------------------------- /queue/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/queue/a.out -------------------------------------------------------------------------------- /queue/basicActions.h: -------------------------------------------------------------------------------- 1 | #include 2 | #define max 100 3 | using namespace std; 4 | 5 | int front = -1; 6 | int rear = -1; 7 | int *queue = new int[max]; 8 | 9 | void enQueue(int data) { 10 | if (front == -1) 11 | front = 0; 12 | rear++; 13 | queue[rear] = data; 14 | } 15 | 16 | void deQueue() { 17 | front++; 18 | } 19 | 20 | int getFront() { 21 | return queue[front]; 22 | } 23 | 24 | bool isEmpty() { 25 | return (front == rear+1) ? true : false; 26 | } 27 | 28 | void display() { 29 | for (int t = front; t <= rear; t++) 30 | cout << queue[t] << " -> "; 31 | 32 | cout << '\n'; 33 | } 34 | -------------------------------------------------------------------------------- /queue/priority_queue.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Title: Priority Queue with linked list implementation. 4 | * Author: Viswalahiri Swamy Hejeebu 5 | * GitHub: https://github.com/Viswalahiri 6 | * LinkedIn: https://in.linkedin.com/in/viswalahiri 7 | * 8 | */ 9 | 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | struct Node 15 | { 16 | int data; 17 | int priority; 18 | struct Node *next; 19 | }; 20 | struct Node *head=NULL; 21 | 22 | void dequeue() 23 | { 24 | if(head==NULL) 25 | { 26 | cout<<"Queue Underflow."<next==NULL) 30 | { 31 | struct Node *temp=head, *temp2; 32 | 33 | if(temp!=NULL) 34 | { 35 | temp2=temp; 36 | temp=temp->next; 37 | } 38 | // temp1=temp; 39 | head=NULL; 40 | cout<<"The dequeued value is "<data<next!=NULL) 48 | { 49 | temp2=temp; 50 | temp=temp->next; 51 | } 52 | temp2->next=NULL; 53 | cout<<"The dequeued value is "<data<>p; 64 | struct Node *new_node; 65 | new_node = (struct Node*)malloc(sizeof(struct Node)); 66 | new_node->priority = p; 67 | new_node->data=value; 68 | 69 | 70 | struct Node *temp=head,*temp2; 71 | if(head==NULL) 72 | { 73 | head=new_node; 74 | new_node->next=NULL; 75 | } 76 | else 77 | { 78 | int counter=0; 79 | 80 | // 81 | 82 | while(temp!=NULL && temp->priority > p) 83 | { 84 | counter=1; 85 | temp2=temp; 86 | temp=temp->next; 87 | } 88 | 89 | if(temp!=NULL) 90 | { 91 | // if temp not null 92 | if(counter==0) 93 | { 94 | new_node->next=head; 95 | head=new_node; 96 | } 97 | else 98 | { 99 | temp2->next= new_node; 100 | new_node->next=temp; 101 | } 102 | } 103 | else 104 | { 105 | temp2->next=new_node; 106 | new_node->next=NULL; 107 | } 108 | 109 | // new_node->next=head; 110 | // head=new_node; 111 | } 112 | cout<<"The value "<>choice; 126 | switch(choice) 127 | { 128 | case 1: 129 | cout<<"Push what?"<>to_push; 132 | enqueue(to_push); 133 | break; 134 | case 2: 135 | dequeue(); 136 | break; 137 | case 3: 138 | exit(0); 139 | break; 140 | default: 141 | cout<<"The option you have requested isn't present."< 10 | #include 11 | using namespace std; 12 | 13 | struct Node 14 | { 15 | int data; 16 | struct Node *next; 17 | }; 18 | struct Node *head=NULL; 19 | 20 | void dequeue() 21 | { 22 | if(head==NULL) 23 | { 24 | cout<<"Queue Underflow."<next==NULL) 28 | { 29 | struct Node *temp=head, *temp2; 30 | 31 | if(temp!=NULL) 32 | { 33 | temp2=temp; 34 | temp=temp->next; 35 | } 36 | // temp1=temp; 37 | head=NULL; 38 | cout<<"The dequeued value is "<data<next!=NULL) 46 | { 47 | temp2=temp; 48 | temp=temp->next; 49 | } 50 | temp2->next=NULL; 51 | cout<<"The dequeued value is "<data<data=value; 63 | new_node->next=head; 64 | head=new_node; 65 | 66 | } 67 | 68 | //Driver Program 69 | int main() 70 | { 71 | 72 | while(1) 73 | { 74 | cout<<"1 - enqueue"<>choice; 79 | switch(choice) 80 | { 81 | case 1: 82 | cout<<"Push what?"<>to_push; 85 | enqueue(to_push); 86 | break; 87 | case 2: 88 | dequeue(); 89 | break; 90 | case 3: 91 | exit(0); 92 | break; 93 | default: 94 | cout<<"The option you have requested isn't present."< @author A.Mano Sriram
@dateCreated 5th April, 2019

4 | 5 | ## Operations : 6 | 7 | - **push(data)** 8 | - **pop()** 9 | - **isEmpty()** 10 | - **isFull()** 11 | - **getTopElement()** 12 | 13 | ``` 14 | push(data) : Pushes Element to the Top. 15 | 16 | pop() : Removes the Top Most Element. 17 | 18 | isEmpty() : Returns True if the Stack is Empty, else False. 19 | 20 | isFull() : Returns True if the Stack if Full, else False. 21 | 22 | getTopElement() : Returns the Top Most Element in the Stack. 23 | 24 | ``` 25 | 26 | ### **More Problems on Stacks will be Added.** 27 | -------------------------------------------------------------------------------- /stacks/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manosriram/Data-Structures/1872932a199d24f0bb14f13e801b969c6dec0225/stacks/a.out -------------------------------------------------------------------------------- /stacks/basicActions.h: -------------------------------------------------------------------------------- 1 | #include 2 | #define max 1500 3 | using namespace std; 4 | 5 | static int top = -1; 6 | int *stack = new int[max]; 7 | 8 | void push(int data) 9 | { 10 | if (top == max) 11 | { 12 | cout << "Stack OverFlow!" << '\n'; 13 | return; 14 | } 15 | 16 | top++; 17 | stack[top] = data; 18 | return; 19 | } 20 | 21 | void pop() 22 | { 23 | if (top == -1) 24 | { 25 | cout << "Stack UnderFlow!" << '\n'; 26 | return; 27 | } 28 | top--; 29 | return; 30 | } 31 | 32 | bool isEmpty() 33 | { 34 | return (top == -1) ? true : false; 35 | } 36 | 37 | bool isFull() 38 | { 39 | return (top == max) ? true : false; 40 | } 41 | 42 | int getTopElement() 43 | { 44 | return top > -1 ? stack[top] : 0; 45 | } 46 | -------------------------------------------------------------------------------- /stacks/reverseString.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define max 100 4 | using namespace std; 5 | static string Rstr; 6 | static int top = -1; 7 | char stack[max]; 8 | 9 | void push(char value) 10 | { 11 | if (top < max) 12 | { 13 | top++; 14 | stack[top] = value; 15 | } 16 | return; 17 | } 18 | 19 | char pop() 20 | { 21 | char temp = stack[top]; 22 | top--; 23 | return temp; 24 | } 25 | 26 | void combineString() 27 | { 28 | while (top > -1) 29 | { 30 | Rstr += pop(); 31 | } 32 | Rstr += " "; 33 | return; 34 | } 35 | 36 | void reverseWords(char a[]) 37 | { 38 | int t; 39 | for (t = strlen(a) - 1; t >= 0; t--) 40 | { 41 | if (a[t] == ' ') 42 | { 43 | combineString(); 44 | } 45 | else 46 | { 47 | push(a[t]); 48 | } 49 | } 50 | combineString(); 51 | return; 52 | } 53 | 54 | int main() 55 | { 56 | char a[40]; 57 | cin.getline(a, 40); 58 | reverseWords(a); 59 | cout << Rstr << endl; 60 | } --------------------------------------------------------------------------------