code,space_complexity,time_complexity "// LCM of given range queries using Segment Tree #include using namespace std; #define MAX 1000 // allocate space for tree int tree[4 * MAX]; // declaring the array globally int arr[MAX]; // Function to return gcd of a and b int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } // utility function to find lcm int lcm(int a, int b) { return a * b / gcd(a, b); } // Function to build the segment tree // Node starts beginning index of current subtree. // start and end are indexes in arr[] which is global void build(int node, int start, int end) { // If there is only one element in current subarray if (start == end) { tree[node] = arr[start]; return; } int mid = (start + end) / 2; // build left and right segments build(2 * node, start, mid); build(2 * node + 1, mid + 1, end); // build the parent int left_lcm = tree[2 * node]; int right_lcm = tree[2 * node + 1]; tree[node] = lcm(left_lcm, right_lcm); } // Function to make queries for array range )l, r). // Node is index of root of current segment in segment // tree (Note that indexes in segment tree begin with 1 // for simplicity). // start and end are indexes of subarray covered by root // of current segment. int query(int node, int start, int end, int l, int r) { // Completely outside the segment, returning // 1 will not affect the lcm; if (end < l || start > r) return 1; // completely inside the segment if (l <= start && r >= end) return tree[node]; // partially inside int mid = (start + end) / 2; int left_lcm = query(2 * node, start, mid, l, r); int right_lcm = query(2 * node + 1, mid + 1, end, l, r); return lcm(left_lcm, right_lcm); } // driver function to check the above program int main() { // initialize the array arr[0] = 5; arr[1] = 7; arr[2] = 5; arr[3] = 2; arr[4] = 10; arr[5] = 12; arr[6] = 11; arr[7] = 17; arr[8] = 14; arr[9] = 1; arr[10] = 44; // build the segment tree build(1, 0, 10); // Now we can answer each query efficiently // Print LCM of (2, 5) cout << query(1, 0, 10, 2, 5) << endl; // Print LCM of (5, 10) cout << query(1, 0, 10, 5, 10) << endl; // Print LCM of (0, 10) cout << query(1, 0, 10, 0, 10) << endl; return 0; }",constant,linear "// C++ program to find minimum and maximum using segment // tree #include using namespace std; // Node for storing minimum and maximum value of given range struct node { int minimum; int maximum; }; // A utility function to get the middle index from corner // indexes. int getMid(int s, int e) { return s + (e - s) / 2; } /* A recursive function to get the minimum and maximum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ struct node MaxMinUntill(struct node* st, int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, // then return // the minimum and maximum node of the segment struct node tmp, left, right; if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) { tmp.minimum = INT_MAX; tmp.maximum = INT_MIN; return tmp; } // If a part of this segment overlaps with the given // range int mid = getMid(ss, se); left = MaxMinUntill(st, ss, mid, qs, qe, 2 * index + 1); right = MaxMinUntill(st, mid + 1, se, qs, qe, 2 * index + 2); tmp.minimum = min(left.minimum, right.minimum); tmp.maximum = max(left.maximum, right.maximum); return tmp; } // Return minimum and maximum of elements in range from // index qs (query start) to qe (query end). It mainly uses // MaxMinUtill() struct node MaxMin(struct node* st, int n, int qs, int qe) { struct node tmp; // Check for erroneous input values if (qs < 0 || qe > n - 1 || qs > qe) { printf(""Invalid Input""); tmp.minimum = INT_MIN; tmp.minimum = INT_MAX; return tmp; } return MaxMinUntill(st, 0, n - 1, qs, qe, 0); } // A recursive function that constructs Segment Tree for // array[ss..se]. si is index of current node in segment // tree st void constructSTUtil(int arr[], int ss, int se, struct node* st, int si) { // If there is one element in array, store it in current // node of segment tree and return if (ss == se) { st[si].minimum = arr[ss]; st[si].maximum = arr[ss]; return; } // If there are more than one elements, then recur for // left and right subtrees and store the minimum and // maximum of two values in this node int mid = getMid(ss, se); constructSTUtil(arr, ss, mid, st, si * 2 + 1); constructSTUtil(arr, mid + 1, se, st, si * 2 + 2); st[si].minimum = min(st[si * 2 + 1].minimum, st[si * 2 + 2].minimum); st[si].maximum = max(st[si * 2 + 1].maximum, st[si * 2 + 2].maximum); } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ struct node* constructST(int arr[], int n) { // Allocate memory for segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; struct node* st = new struct node[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n - 1, st, 0); // Return the constructed segment tree return st; } // Driver code int main() { int arr[] = { 1, 8, 5, 9, 6, 14, 2, 4, 3, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Build segment tree from given array struct node* st = constructST(arr, n); int qs = 0; // Starting index of query range int qe = 8; // Ending index of query range struct node result = MaxMin(st, n, qs, qe); // Function call printf(""Minimum = %d and Maximum = %d "", result.minimum, result.maximum); return 0; }",linear,logn "/* C++ Program to find LCA of u and v by reducing the problem to RMQ */ #include #define V 9 // number of nodes in input tree int euler[2*V - 1]; // For Euler tour sequence int level[2*V - 1]; // Level of nodes in tour sequence int firstOccurrence[V+1]; // First occurrences of nodes in tour int ind; // Variable to fill-in euler and level arrays // A Binary Tree node struct Node { int key; struct Node *left, *right; }; // Utility function creates a new binary tree node with given key Node * newNode(int k) { Node *temp = new Node; temp->key = k; temp->left = temp->right = NULL; return temp; } // log base 2 of x int Log2(int x) { int ans = 0 ; while (x>>=1) ans++; return ans ; } /* A recursive function to get the minimum value in a given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int RMQUtil(int index, int ss, int se, int qs, int qe, int *st) { // If segment of this node is a part of given range, then return // the min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range else if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = (ss + se)/2; int q1 = RMQUtil(2*index+1, ss, mid, qs, qe, st); int q2 = RMQUtil(2*index+2, mid+1, se, qs, qe, st); if (q1==-1) return q2; else if (q2==-1) return q1; return (level[q1] < level[q2]) ? q1 : q2; } // Return minimum of elements in range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() int RMQ(int *st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf(""Invalid Input""); return -1; } return RMQUtil(0, 0, n-1, qs, qe, st); } // A recursive function that constructs Segment Tree for array[ss..se]. // si is index of current node in segment tree st void constructSTUtil(int si, int ss, int se, int arr[], int *st) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se)st[si] = ss; else { // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = (ss + se)/2; constructSTUtil(si*2+1, ss, mid, arr, st); constructSTUtil(si*2+2, mid+1, se, arr, st); if (arr[st[2*si+1]] < arr[st[2*si+2]]) st[si] = st[2*si+1]; else st[si] = st[2*si+2]; } } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int *constructST(int arr[], int n) { // Allocate memory for segment tree // Height of segment tree int x = Log2(n)+1; // Maximum size of segment tree int max_size = 2*(1<key; // insert in euler array level[ind] = l; // insert l in level array ind++; // increment index /* if unvisited, mark first occurrence */ if (firstOccurrence[root->key] == -1) firstOccurrence[root->key] = ind-1; /* tour left subtree if exists, and remark euler and level arrays for parent on return */ if (root->left) { eulerTour(root->left, l+1); euler[ind]=root->key; level[ind] = l; ind++; } /* tour right subtree if exists, and remark euler and level arrays for parent on return */ if (root->right) { eulerTour(root->right, l+1); euler[ind]=root->key; level[ind] = l; ind++; } } } // Returns LCA of nodes n1, n2 (assuming they are // present in the tree) int findLCA(Node *root, int u, int v) { /* Mark all nodes unvisited. Note that the size of firstOccurrence is 1 as node values which vary from 1 to 9 are used as indexes */ memset(firstOccurrence, -1, sizeof(int)*(V+1)); /* To start filling euler and level arrays from index 0 */ ind = 0; /* Start Euler tour with root node on level 0 */ eulerTour(root, 0); /* construct segment tree on level array */ int *st = constructST(level, 2*V-1); /* If v before u in Euler tour. For RMQ to work, first parameter 'u' must be smaller than second 'v' */ if (firstOccurrence[u]>firstOccurrence[v]) std::swap(u, v); // Starting and ending indexes of query range int qs = firstOccurrence[u]; int qe = firstOccurrence[v]; // query for index of LCA in tour int index = RMQ(st, 2*V-1, qs, qe); /* return LCA node */ return euler[index]; } // Driver program to test above functions int main() { // Let us create the Binary Tree as shown in the diagram. Node * root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->right->left = newNode(8); root->left->right->right = newNode(9); int u = 4, v = 9; printf(""The LCA of node %d and node %d is node %d.\n"", u, v, findLCA(root, u, v)); return 0; }",linear,linear "// A Divide and Conquer Program to find maximum rectangular area in a histogram #include using namespace std; // A utility function to find minimum of three integers int max(int x, int y, int z) { return max(max(x, y), z); } // A utility function to get minimum of two numbers in hist[] int minVal(int *hist, int i, int j) { if (i == -1) return j; if (j == -1) return i; return (hist[i] < hist[j])? i : j; } // A utility function to get the middle index from corner indexes. int getMid(int s, int e) { return s + (e -s)/2; } /* A recursive function to get the index of minimum value in a given range of indexes. The following are parameters for this function. hist --> Input array for which segment tree is built st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int RMQUtil(int *hist, int *st, int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, then return the // min of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return -1; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return minVal(hist, RMQUtil(hist, st, ss, mid, qs, qe, 2*index+1), RMQUtil(hist, st, mid+1, se, qs, qe, 2*index+2)); } // Return index of minimum element in range from index qs (query start) to // qe (query end). It mainly uses RMQUtil() int RMQ(int *hist, int *st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { cout << ""Invalid Input""; return -1; } return RMQUtil(hist, st, 0, n-1, qs, qe, 0); } // A recursive function that constructs Segment Tree for hist[ss..se]. // si is index of current node in segment tree st int constructSTUtil(int hist[], int ss, int se, int *st, int si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) return (st[si] = ss); // If there are more than one elements, then recur for left and // right subtrees and store the minimum of two values in this node int mid = getMid(ss, se); st[si] = minVal(hist, constructSTUtil(hist, ss, mid, st, si*2+1), constructSTUtil(hist, mid+1, se, st, si*2+2)); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int *constructST(int hist[], int n) { // Allocate memory for segment tree int x = (int)(ceil(log2(n))); //Height of segment tree int max_size = 2*(int)pow(2, x) - 1; //Maximum size of segment tree int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(hist, 0, n-1, st, 0); // Return the constructed segment tree return st; } // A recursive function to find the maximum rectangular area. // It uses segment tree 'st' to find the minimum value in hist[l..r] int getMaxAreaRec(int *hist, int *st, int n, int l, int r) { // Base cases if (l > r) return INT_MIN; if (l == r) return hist[l]; // Find index of the minimum value in given range // This takes O(Logn)time int m = RMQ(hist, st, n, l, r); /* Return maximum of following three possible cases a) Maximum area in Left of min value (not including the min) a) Maximum area in right of min value (not including the min) c) Maximum area including min */ return max(getMaxAreaRec(hist, st, n, l, m-1), getMaxAreaRec(hist, st, n, m+1, r), (r-l+1)*(hist[m]) ); } // The main function to find max area int getMaxArea(int hist[], int n) { // Build segment tree from given array. This takes // O(n) time int *st = constructST(hist, n); // Use recursive utility function to find the // maximum area return getMaxAreaRec(hist, st, n, 0, n-1); } // Driver program to test above functions int main() { int hist[] = {6, 1, 5, 4, 5, 2, 6}; int n = sizeof(hist)/sizeof(hist[0]); cout << ""Maximum area is "" << getMaxArea(hist, n); return 0; }",linear,nlogn "// C++ program to print all words in the CamelCase // dictionary that matches with a given pattern #include using namespace std; // Alphabet size (# of upper-Case characters) #define ALPHABET_SIZE 26 // A Trie node struct TrieNode { TrieNode* children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf; // vector to store list of complete words // in leaf node list word; }; // Returns new Trie node (initialized to NULLs) TrieNode* getNewTrieNode(void) { TrieNode* pNode = new TrieNode; if (pNode) { pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode; } // Function to insert word into the Trie void insert(TrieNode* root, string word) { int index; TrieNode* pCrawl = root; for (int level = 0; level < word.length(); level++) { // consider only uppercase characters if (islower(word[level])) continue; // get current character position index = int(word[level]) - 'A'; if (!pCrawl->children[index]) pCrawl->children[index] = getNewTrieNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isLeaf = true; // push word into vector associated with leaf node (pCrawl->word).push_back(word); } // Function to print all children of Trie node root void printAllWords(TrieNode* root) { // if current node is leaf if (root->isLeaf) { for(string str : root->word) cout << str << endl; } // recurse for all children of root node for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode* child = root->children[i]; if (child) printAllWords(child); } } // search for pattern in Trie and print all words // matching that pattern bool search(TrieNode* root, string pattern) { int index; TrieNode* pCrawl = root; for (int level = 0; level < pattern.length(); level++) { index = int(pattern[level]) - 'A'; // Invalid pattern if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } // print all words matching that pattern printAllWords(pCrawl); return true; } // Main function to print all words in the CamelCase // dictionary that matches with a given pattern void findAllWords(vector dict, string pattern) { // construct Trie root node TrieNode* root = getNewTrieNode(); // Construct Trie from given dict for (string word : dict) insert(root, word); // search for pattern in Trie if (!search(root, pattern)) cout << ""No match found""; } // Driver function int main() { // dictionary of words where each word follows // CamelCase notation vector dict = { ""Hi"", ""Hello"", ""HelloWorld"", ""HiTech"", ""HiGeek"", ""HiTechWorld"", ""HiTechCity"", ""HiTechLab"" }; // pattern consisting of uppercase characters only string pattern = ""HT""; findAllWords(dict, pattern); return 0; }",linear,quadratic "// C++ program to construct an n x n // matrix such that every row and every // column has distinct values. #include #include using namespace std; const int MAX = 100; int mat[MAX][MAX]; // Fills non-one entries in column j // Given that there is a ""1"" at // position mat[i][j], this function // fills other entries of column j. void fillRemaining(int i, int j, int n) { // Initialize value to be filled int x = 2; // Fill all values below i as 2, 3, ...p for (int k = i + 1; k < n; k++) mat[k][j] = x++; // Fill all values above i // as p + 1, p + 2, .. n for (int k = 0; k < i; k++) mat[k][j] = x++; } // Fills entries in mat[][] // with the given set of rules void constructMatrix(int n) { // Alternatively fill 1s starting from // rightmost and leftmost columns. For // example for n = 3, we get { {_ _ 1}, // {1 _ _} {_ 1 _}} int right = n - 1, left = 0; for (int i = 0; i < n; i++) { // If i is even, then fill // next column from right if (i % 2 == 0) { mat[i][right] = 1; // After filling 1, fill remaining // entries of column ""right"" fillRemaining(i, right, n); // Move right one column back right--; } // Fill next column from left else { mat[i][left] = 1; // After filling 1, fill remaining // entries of column ""left"" fillRemaining(i, left, n); // Move left one column forward left++; } } } // Driver code int main() { int n = 5; // Passing n to constructMatrix function constructMatrix(n); // Printing the desired unique matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) printf(""%d "",mat[i][j]); printf (""\n""); } return 0; }",constant,quadratic "// Given a binary matrix of M X N of integers, // you need to return only unique rows of binary array #include using namespace std; #define ROW 4 #define COL 5 // The main function that prints // all unique rows in a given matrix. void findUniqueRows(int M[ROW][COL]) { //Traverse through the matrix for(int i=0; i using namespace std; #define ROW 4 #define COL 5 class BST { int data; BST *left, *right; public: // Default constructor. BST(); // Parameterized constructor. BST(int); // Insert function. BST* Insert(BST *, int); // Inorder traversal. void Inorder(BST *); }; //convert array to decimal int convert(int arr[]) { int sum=0; for(int i=0; idata) return root; // Insert data. if(value > root->data) { // Insert right node data, if the 'value' // to be inserted is greater than 'root' node data. // Process right nodes. root->right = Insert(root->right, value); } else { // Insert left node data, if the 'value' // to be inserted is greater than 'root' node data. // Process left nodes. root->left = Insert(root->left, value); } // Return 'root' node, after insertion. return root; } // Inorder traversal function. // This gives data in sorted order. void BST :: Inorder(BST *root) { if(!root) { return; } Inorder(root->left); print( root->data ); Inorder(root->right); } // The main function that prints // all unique rows in a given matrix. void findUniqueRows(int M[ROW][COL]) { BST b, *root = NULL; //Traverse through the matrix for(int i=0; i using namespace std; #define ROW 4 #define COL 5 // A Trie node class Node { public: bool isEndOfCol; Node *child[2]; // Only two children needed for 0 and 1 } ; // A utility function to allocate memory // for a new Trie node Node* newNode() { Node* temp = new Node(); temp->isEndOfCol = 0; temp->child[0] = temp->child[1] = NULL; return temp; } // Inserts a new matrix row to Trie. // If row is already present, // then returns 0, otherwise insets the row and // return 1 bool insert(Node** root, int (*M)[COL], int row, int col ) { // base case if (*root == NULL) *root = newNode(); // Recur if there are more entries in this row if (col < COL) return insert (&((*root)->child[M[row][col]]), M, row, col + 1); else // If all entries of this row are processed { // unique row found, return 1 if (!((*root)->isEndOfCol)) return (*root)->isEndOfCol = 1; // duplicate row found, return 0 return 0; } } // A utility function to print a row void printRow(int(*M)[COL], int row) { int i; for(i = 0; i < COL; ++i) cout << M[row][i] << "" ""; cout << endl; } // The main function that prints // all unique rows in a given matrix. void findUniqueRows(int (*M)[COL]) { Node* root = NULL; // create an empty Trie int i; // Iterate through all rows for (i = 0; i < ROW; ++i) // insert row to TRIE if (insert(&root, M, i, 0)) // unique row found, print it printRow(M, i); } // Driver Code int main() { int M[ROW][COL] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 0, 1, 0, 0}}; findUniqueRows(M); return 0; } // This code is contributed by rathbhupendra",quadratic,quadratic "// C++ code to print unique row in a // given binary matrix #include using namespace std; void printArray(int arr[][5], int row, int col) { unordered_set uset; for(int i = 0; i < row; i++) { string s = """"; for(int j = 0; j < col; j++) s += to_string(arr[i][j]); if(uset.count(s) == 0) { uset.insert(s); cout << s << endl; } } } // Driver code int main() { int arr[][5] = {{0, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {0, 1, 0, 0, 1}, {1, 1, 1, 0, 0}}; printArray(arr, 4, 5); } // This code is contributed by // rathbhupendra",linear,quadratic "// A C++ program to find the count of distinct substring // of a string using trie data structure #include #define MAX_CHAR 26 using namespace std; // A Suffix Trie (A Trie of all suffixes) Node class SuffixTrieNode { public: SuffixTrieNode *children[MAX_CHAR]; SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = NULL; } // A recursive function to insert a suffix of the s // in subtree rooted with this node void insertSuffix(string suffix); }; // A Trie of all suffixes class SuffixTrie { SuffixTrieNode *root; int _countNodesInTrie(SuffixTrieNode *); public: // Constructor (Builds a trie of suffies of the given text) SuffixTrie(string s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.length(); i++) root->insertSuffix(s.substr(i)); } // method to count total nodes in suffix trie int countNodesInTrie() { return _countNodesInTrie(root); } }; // A recursive function to insert a suffix of the s in // subtree rooted with this node void SuffixTrieNode::insertSuffix(string s) { // If string has more characters if (s.length() > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = s.at(0) - 'a'; // If there is no edge for this character, // add a new edge if (children[cIndex] == NULL) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex]->insertSuffix(s.substr(1)); } } // A recursive function to count nodes in trie int SuffixTrie::_countNodesInTrie(SuffixTrieNode* node) { // If all characters of pattern have been processed, if (node == NULL) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node->children[i] != NULL) count += _countNodesInTrie(node->children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count); } // Returns count of distinct substrings of str int countDistinctSubstring(string str) { // Construct a Trie of all suffixes SuffixTrie sTrie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie(); } // Driver program to test above function int main() { string str = ""ababa""; cout << ""Count of distinct substrings is "" << countDistinctSubstring(str); return 0; }",constant,linear "#include using namespace std; // Function to find minimum XOR pair int minXOR(int arr[], int n) { // Sort given array sort(arr, arr + n); int minXor = INT_MAX; int val = 0; // calculate min xor of consecutive pairs for (int i = 0; i < n - 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = min(minXor, val); } return minXor; } // Driver program int main() { int arr[] = { 9, 5, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minXOR(arr, n) << endl; return 0; }",constant,nlogn "// A simple C++ program to find max subarray XOR #include using namespace std; int maxSubarrayXOR(int arr[], int n) { int ans = INT_MIN; // Initialize result // Pick starting points of subarrays for (int i=0; i using namespace std; // Assumed int size #define INT_SIZE 32 // A Trie Node struct TrieNode { int value; // Only used in leaf nodes TrieNode *arr[2]; }; // Utility function to create a Trie node TrieNode *newNode() { TrieNode *temp = new TrieNode; temp->value = 0; temp->arr[0] = temp->arr[1] = NULL; return temp; } // Inserts pre_xor to trie with given root void insert(TrieNode *root, int pre_xor) { TrieNode *temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<arr[val] == NULL) temp->arr[val] = newNode(); temp = temp->arr[val]; } // Store value at leaf node temp->value = pre_xor; } // Finds the maximum XOR ending with last number in // prefix XOR 'pre_xor' and returns the XOR of this maximum // with pre_xor which is maximum XOR ending with last element // of pre_xor. int query(TrieNode *root, int pre_xor) { TrieNode *temp = root; for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<arr[1-val]!=NULL) temp = temp->arr[1-val]; // If there is no prefix with opposite // bit, then look for same bit. else if (temp->arr[val] != NULL) temp = temp->arr[val]; } return pre_xor^(temp->value); } // Returns maximum XOR value of a subarray in arr[0..n-1] int maxSubarrayXOR(int arr[], int n) { // Create a Trie and insert 0 into it TrieNode *root = newNode(); insert(root, 0); // Initialize answer and xor of current prefix int result = INT_MIN, pre_xor =0; // Traverse all input array element for (int i=0; i using namespace std; /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for which prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function assumes // that the array is preprocessed and partial sums of // array elements are stored in BITree[]. int getSum(int BITree[], int index) { int sum = 0; // Initialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum; } // Updates a node in Binary Index Tree (BITree) at given index // in BITree. The given value 'val' is added to BITree[i] and // all of its ancestors in tree. void updateBIT(int BITree[], int n, int index, int val) { // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); } } // Constructs and returns a Binary Indexed Tree for given // array of size n. int *constructBITree(int arr[], int n) { // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i x1<=x2 and y1<=y2 /\ y | | --------(x2,y2) | | | | | | | | | | --------- | (x1,y1) | |___________________________ (0, 0) x--> In this program we have assumed a square matrix. The program can be easily extended to a rectangular one. */ #include using namespace std; #define N 4 // N-->max_x and max_y // A structure to hold the queries struct Query { int x1, y1; // x and y co-ordinates of bottom left int x2, y2; // x and y co-ordinates of top right }; // A function to update the 2D BIT void updateBIT(int BIT[][N+1], int x, int y, int val) { for (; x <= N; x += (x & -x)) { // This loop update all the 1D BIT inside the // array of 1D BIT = BIT[x] for (int yy=y; yy <= N; yy += (yy & -yy)) BIT[x][yy] += val; } return; } // A function to get sum from (0, 0) to (x, y) int getSum(int BIT[][N+1], int x, int y) { int sum = 0; for(; x > 0; x -= x&-x) { // This loop sum through all the 1D BIT // inside the array of 1D BIT = BIT[x] for(int yy=y; yy > 0; yy -= yy&-yy) { sum += BIT[x][yy]; } } return sum; } // A function to create an auxiliary matrix // from the given input matrix void constructAux(int mat[][N], int aux[][N+1]) { // Initialise Auxiliary array to 0 for (int i=0; i<=N; i++) for (int j=0; j<=N; j++) aux[i][j] = 0; // Construct the Auxiliary Matrix for (int j=1; j<=N; j++) for (int i=1; i<=N; i++) aux[i][j] = mat[N-j][i-1]; return; } // A function to construct a 2D BIT void construct2DBIT(int mat[][N], int BIT[][N+1]) { // Create an auxiliary matrix int aux[N+1][N+1]; constructAux(mat, aux); // Initialise the BIT to 0 for (int i=1; i<=N; i++) for (int j=1; j<=N; j++) BIT[i][j] = 0; for (int j=1; j<=N; j++) { for (int i=1; i<=N; i++) { // Creating a 2D-BIT using update function // everytime we/ encounter a value in the // input 2D-array int v1 = getSum(BIT, i, j); int v2 = getSum(BIT, i, j-1); int v3 = getSum(BIT, i-1, j-1); int v4 = getSum(BIT, i-1, j); // Assigning a value to a particular element // of 2D BIT updateBIT(BIT, i, j, aux[i][j]-(v1-v2-v4+v3)); } } return; } // A function to answer the queries void answerQueries(Query q[], int m, int BIT[][N+1]) { for (int i=0; i 3 8 1 1 | 4 6 7 5 6 7 5 0 | 2 4 8 9 | --|------ 0 1 2 3 ----> x | Hence sum of the sub-matrix = 3+8+1+6+7+5 = 30 */ Query q[] = {{1, 1, 3, 2}, {2, 3, 3, 3}, {1, 1, 1, 1}}; int m = sizeof(q)/sizeof(q[0]); answerQueries(q, m, BIT); return(0); }",quadratic,nlogn "// A Simple C++ O(n^3) program to count inversions of size 3 #include using namespace std; // Returns counts of inversions of size three int getInvCount(int arr[],int n) { int invcount = 0; // Initialize result for (int i=0; iarr[j]) { for (int k=j+1; karr[k]) invcount++; } } } } return invcount; } // Driver program to test above function int main() { int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << ""Inversion Count : "" << getInvCount(arr, n); return 0; }",constant,cubic "// A O(n^2) C++ program to count inversions of size 3 #include using namespace std; // Returns count of inversions of size 3 int getInvCount(int arr[], int n) { int invcount = 0; // Initialize result for (int i=1; i arr[j]) small++; // Count all greater elements on left of arr[i] int great = 0; for (int j=i-1; j>=0; j--) if (arr[i] < arr[j]) great++; // Update inversion count by adding all inversions // that have arr[i] as middle of three elements invcount += great*small; } return invcount; } // Driver program to test above function int main() { int arr[] = {8, 4, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << ""Inversion Count : "" << getInvCount(arr, n); return 0; }",constant,quadratic "// C++ program to count the number of inversion // pairs in a 2D matrix #include using namespace std; // for simplicity, we are taking N as 4 #define N 4 // Function to update a 2D BIT. It updates the // value of bit[l][r] by adding val to bit[l][r] void update(int l, int r, int val, int bit[][N + 1]) { for (int i = l; i <= N; i += i & -i) for (int j = r; j <= N; j += j & -j) bit[i][j] += val; } // function to find cumulative sum upto // index (l, r) in the 2D BIT long long query(int l, int r, int bit[][N + 1]) { long long ret = 0; for (int i = l; i > 0; i -= i & -i) for (int j = r; j > 0; j -= j & -j) ret += bit[i][j]; return ret; } // function to count and return the number // of inversion pairs in the matrix long long countInversionPairs(int mat[][N]) { // the 2D bit array and initialize it with 0. int bit[N+1][N+1] = {0}; // v will store the tuple (-mat[i][j], i, j) vector > > v; // store the tuples in the vector v for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j) // Note that we are not using the pair // (0, 0) because BIT update and query // operations are not done on index 0 v.push_back(make_pair(-mat[i][j], make_pair(i+1, j+1))); // sort the vector v according to the // first element of the tuple, i.e., -mat[i][j] sort(v.begin(), v.end()); // inv_pair_cnt will store the number of // inversion pairs long long inv_pair_cnt = 0; // traverse all the tuples of vector v int i = 0; while (i < v.size()) { int curr = i; // 'pairs' will store the position of each element, // i.e., the pair (i, j) of each tuple of the vector v vector > pairs; // consider the current tuple in v and all its // adjacent tuples whose first value, i.e., the // value of –mat[i][j] is same while (curr < v.size() && (v[curr].first == v[i].first)) { // push the position of the current element in 'pairs' pairs.push_back(make_pair(v[curr].second.first, v[curr].second.second)); // add the number of elements which are // less than the current element and lie on the right // side in the vector v inv_pair_cnt += query(v[curr].second.first, v[curr].second.second, bit); curr++; } vector >::iterator it; // traverse the 'pairs' vector for (it = pairs.begin(); it != pairs.end(); ++it) { int x = it->first; int y = it->second; // update the position (x, y) by 1 update(x, y, 1, bit); } i = curr; } return inv_pair_cnt; } // Driver program int main() { int mat[N][N] = { { 4, 7, 2, 9 }, { 6, 4, 1, 7 }, { 5, 3, 8, 1 }, { 3, 2, 5, 6 } }; long long inv_pair_cnt = countInversionPairs(mat); cout << ""The number of inversion pairs are : "" << inv_pair_cnt << endl; return 0; }",quadratic,logn "// Naive algorithm for building suffix array of a given text #include #include #include using namespace std; // Structure to store information of a suffix struct suffix { int index; char *suff; }; // A comparison function used by sort() to compare two suffixes int cmp(struct suffix a, struct suffix b) { return strcmp(a.suff, b.suff) < 0? 1 : 0; } // This is the main function that takes a string 'txt' of size n as an // argument, builds and return the suffix array for the given string int *buildSuffixArray(char *txt, int n) { // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array of structures. // The structure is needed to sort the suffixes alphabetically // and maintain their old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].suff = (txt+i); } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // Store indexes of all sorted suffixes in the suffix array int *suffixArr = new int[n]; for (int i = 0; i < n; i++) suffixArr[i] = suffixes[i].index; // Return the suffix array return suffixArr; } // A utility function to print an array of given size void printArr(int arr[], int n) { for(int i = 0; i < n; i++) cout << arr[i] << "" ""; cout << endl; } // Driver program to test above functions int main() { char txt[] = ""banana""; int n = strlen(txt); int *suffixArr = buildSuffixArray(txt, n); cout << ""Following is suffix array for "" << txt << endl; printArr(suffixArr, n); return 0; }",linear,nlogn "// C++ program to insert a node in AVL tree #include using namespace std; // An AVL tree node class Node { public: int key; Node *left; Node *right; int height; }; // A utility function to get the // height of the tree int height(Node *N) { if (N == NULL) return 0; return N->height; } // A utility function to get maximum // of two integers int max(int a, int b) { return (a > b)? a : b; } /* Helper function that allocates a new node with the given key and NULL left and right pointers. */ Node* newNode(int key) { Node* node = new Node(); node->key = key; node->left = NULL; node->right = NULL; node->height = 1; // new node is initially // added at leaf return(node); } // A utility function to right // rotate subtree rooted with y // See the diagram given above. Node *rightRotate(Node *y) { Node *x = y->left; Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Return new root return x; } // A utility function to left // rotate subtree rooted with x // See the diagram given above. Node *leftRotate(Node *x) { Node *y = x->right; Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); } // Recursive function to insert a key // in the subtree rooted with node and // returns the new root of the subtree. Node* insert(Node* node, int key) { /* 1. Perform the normal BST insertion */ if (node == NULL) return(newNode(key)); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); else // Equal keys are not allowed in BST return node; /* 2. Update height of this ancestor node */ node->height = 1 + max(height(node->left), height(node->right)); /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then // there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // A utility function to print preorder // traversal of the tree. // The function also prints height // of every node void preOrder(Node *root) { if(root != NULL) { cout << root->key << "" ""; preOrder(root->left); preOrder(root->right); } } // Driver Code int main() { Node *root = NULL; /* Constructing tree given in the above figure */ root = insert(root, 10); root = insert(root, 20); root = insert(root, 30); root = insert(root, 40); root = insert(root, 50); root = insert(root, 25); /* The constructed AVL Tree would be 30 / \ 20 40 / \ \ 10 25 50 */ cout << ""Preorder traversal of the "" ""constructed AVL tree is \n""; preOrder(root); return 0; } // This code is contributed by // rathbhupendra",constant,nlogn "// C++ program to find N'th element in a set formed // by sum of two arrays #include using namespace std; //Function to calculate the set of sums int calculateSetOfSum(int arr1[], int size1, int arr2[], int size2, int N) { // Insert each pair sum into set. Note that a set // stores elements in sorted order and unique elements set s; for (int i=0 ; i < size1; i++) for (int j=0; j < size2; j++) s.insert(arr1[i]+arr2[j]); // If set has less than N elements if (s.size() < N) return -1; // Find N'tb item in set and return it set::iterator it = s.begin(); for (int count=1; count using namespace std; void constructLowerArray(int arr[], int* countSmaller, int n) { int i, j; // Initialize all the counts in // countSmaller array as 0 for (i = 0; i < n; i++) countSmaller[i] = 0; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if (arr[j] < arr[i]) countSmaller[i]++; } } } // Utility function that prints // out an array on a line void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) cout << arr[i] << "" ""; cout << ""\n""; } // Driver code int main() { int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int* low = (int*)malloc(sizeof(int) * n); constructLowerArray(arr, low, n); printArray(low, n); return 0; } // This code is contributed by Hemant Jain",constant,quadratic "#include using namespace std; void merge(vector >& v, vector& ans, int l, int mid, int h) { vector > t; // temporary array for merging both halves int i = l; int j = mid + 1; while (i < mid + 1 && j <= h) { // v[i].first is greater than all // the elements from j till h. if (v[i].first > v[j].first) { ans[v[i].second] += (h - j + 1); t.push_back(v[i]); i++; } else { t.push_back(v[j]); j++; } } // if any elements left in left array while (i <= mid) t.push_back(v[i++]); // if any elements left in right array while (j <= h) t.push_back(v[j++]); // putting elements back in main array in // descending order for (int k = 0, i = l; i <= h; i++, k++) v[i] = t[k]; } void mergesort(vector >& v, vector& ans, int i, int j) { if (i < j) { int mid = (i + j) / 2; // calling mergesort for left half mergesort(v, ans, i, mid); // calling mergesort for right half mergesort(v, ans, mid + 1, j); // merging both halves and generating answer merge(v, ans, i, mid, j); } } vector constructLowerArray(int* arr, int n) { vector > v; // inserting elements and corresponding index // as pair for (int i = 0; i < n; i++) v.push_back({ arr[i], i }); // answer array for keeping count // initialized by 0, vector ans(n, 0); // calling mergesort mergesort(v, ans, 0, n - 1); return ans; } // Driver Code Starts. int main() { int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; int n = sizeof(arr) / sizeof(arr[0]); auto ans = constructLowerArray(arr, n); for (auto x : ans) { cout << x << "" ""; } cout << ""\n""; return 0; } // Driver code ends. // This code is contributed by Manjeet Singh",linear,nlogn "#include using namespace std; #include #include // An AVL tree node struct node { int key; struct node* left; struct node* right; int height; // size of the tree rooted // with this node int size; }; // A utility function to get // maximum of two integers int max(int a, int b); // A utility function to get // height of the tree rooted with N int height(struct node* N) { if (N == NULL) return 0; return N->height; } // A utility function to size // of the tree of rooted with N int size(struct node* N) { if (N == NULL) return 0; return N->size; } // A utility function to // get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } // Helper function that allocates a // new node with the given key and // NULL left and right pointers. struct node* newNode(int key) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; // New node is initially added at leaf node->height = 1; node->size = 1; return (node); } // A utility function to right rotate // subtree rooted with y struct node* rightRotate(struct node* y) { struct node* x = y->left; struct node* T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right)) + 1; x->height = max(height(x->left), height(x->right)) + 1; // Update sizes y->size = size(y->left) + size(y->right) + 1; x->size = size(x->left) + size(x->right) + 1; // Return new root return x; } // A utility function to left rotate // subtree rooted with x struct node* leftRotate(struct node* x) { struct node* y = x->right; struct node* T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right)) + 1; y->height = max(height(y->left), height(y->right)) + 1; // Update sizes x->size = size(x->left) + size(x->right) + 1; y->size = size(y->left) + size(y->right) + 1; // Return new root return y; } // Get Balance factor of node N int getBalance(struct node* N) { if (N == NULL) return 0; return height(N->left) - height(N->right); } // Inserts a new key to the tree rotted with // node. Also, updates *count to contain count // of smaller elements for the new key struct node* insert(struct node* node, int key, int* count) { // 1. Perform the normal BST rotation if (node == NULL) return (newNode(key)); if (key < node->key) node->left = insert(node->left, key, count); else { node->right = insert(node->right, key, count); // UPDATE COUNT OF SMALLER ELEMENTS FOR KEY *count = *count + size(node->left) + 1; } // 2.Update height and size of this ancestor node node->height = max(height(node->left), height(node->right)) + 1; node->size = size(node->left) + size(node->right) + 1; // 3. Get the balance factor of this // ancestor node to check whether this // node became unbalanced int balance = getBalance(node); // If this node becomes unbalanced, // then there are 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } // Return the (unchanged) node pointer return node; } // The following function updates the // countSmaller array to contain count of // smaller elements on right side. void constructLowerArray(int arr[], int countSmaller[], int n) { int i, j; struct node* root = NULL; // Initialize all the counts in // countSmaller array as 0 for (i = 0; i < n; i++) countSmaller[i] = 0; // Starting from rightmost element, // insert all elements one by one in // an AVL tree and get the count of // smaller elements for (i = n - 1; i >= 0; i--) { root = insert(root, arr[i], &countSmaller[i]); } } // Utility function that prints out an // array on a line void printArray(int arr[], int size) { int i; cout << ""\n""; for (i = 0; i < size; i++) cout << arr[i] << "" ""; } // Driver code int main() { int arr[] = { 12, 1, 2, 3, 0, 11, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int* low = (int*)malloc(sizeof(int) * n); constructLowerArray(arr, low, n); printArray(low, n); return 0; } // This code is contributed by Hemant Jain",linear,nlogn "#include using namespace std; // BST node structure class Node { public: int val; int count; Node* left; Node* right; // Constructor Node(int num1, int num2) { this->val = num1; this->count = num2; this->left = this->right = NULL; } }; // Function to addNode and find the smaller // elements on the right side int addNode(Node*& root, int value, int countSmaller) { // Base case if (root == NULL) { root = new Node(value, 0); return countSmaller; } if (root->val < value) { return root->count + addNode(root->right, value, countSmaller + 1); } else { root->count++; return addNode(root->left, value, countSmaller); } } // Driver code int main() { ios_base::sync_with_stdio(false); cin.tie(0); int data[] = { 12, 1, 2, 3, 0, 11, 4 }; int size = sizeof(data) / sizeof(data[0]); int ans[size] = { 0 }; Node* root = NULL; for (int i = size - 1; i >= 0; i--) { ans[i] = addNode(root, data[i], 0); } for (int i = 0; i < size; i++) cout << ans[i] << "" ""; return 0; } // This code is contributed by divyanshu gupta",linear,quadratic "// C++ program to sort an array according absolute // difference with x. #include using namespace std; // Function to sort an array according absolute // difference with x. void rearrange(int arr[], int n, int x) { multimap m; multimap::iterator it; // Store values in a map with the difference // with X as key for (int i = 0; i < n; i++) m.insert(make_pair(abs(x - arr[i]), arr[i])); // Update the values of array int i = 0; for (it = m.begin(); it != m.end(); it++) arr[i++] = (*it).second; } // Function to print the array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Driver code int main() { int arr[] = { 10, 5, 3, 9, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; // Function call rearrange(arr, n, x); printArray(arr, n); return 0; }",linear,nlogn "// CPP program for the above approach #include using namespace std; void rearrange(int arr[], int n, int x) { /* We can send the value x into lambda expression as follows: [capture]() { //statements //capture value can be used inside } */ stable_sort(arr, arr + n, [x](int a, int b) { if (abs(a - x) < abs(b - x)) return true; else return false; }); } // Driver code int main() { int arr[] = { 10, 5, 3, 9, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; // Function call rearrange(arr, n, x); for (int i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; }",constant,nlogn "// C++ program to find maximum product of an increasing // subsequence of size 3 #include using namespace std; // Returns maximum product of an increasing subsequence of // size 3 in arr[0..n-1]. If no such subsequence exists, // then it returns INT_MIN long long int maxProduct(int arr[], int n) { int result = INT_MIN; // T.C : O(n^3) for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j + 1; k < n; k++) { result = max(result, arr[i] * arr[j] * arr[k]); } } } return result; } // Driver Program int main() { int arr[] = { 10, 11, 9, 5, 6, 1, 20 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxProduct(arr, n) << endl; return 0; }",constant,cubic "// C++ program to find maximum product of an increasing // subsequence of size 3 #include using namespace std; // Returns maximum product of an increasing subsequence of // size 3 in arr[0..n-1]. If no such subsequence exists, // then it returns INT_MIN long long int maxProduct(int arr[], int n) { // An array ti store closest smaller element on left // side of every element. If there is no such element // on left side, then smaller[i] be -1. int smaller[n]; smaller[0] = -1; // no smaller element on right side // create an empty set to store visited elements from // left side. Set can also quickly find largest smaller // of an element. set S; for (int i = 0; i < n; i++) { // insert arr[i] into the set S auto j = S.insert(arr[i]); auto itc = j.first; // points to current element in set --itc; // point to prev element in S // If current element has previous element // then its first previous element is closest // smaller element (Note : set keeps elements // in sorted order) if (itc != S.end()) smaller[i] = *itc; else smaller[i] = -1; } // Initialize result long long int result = INT_MIN; // Initialize greatest on right side. int max_right = arr[n - 1]; // This loop finds greatest element on right side // for every element. It also updates result when // required. for (int i = n - 2; i >= 1; i--) { // If current element is greater than all // elements on right side, update max_right if (arr[i] > max_right) max_right = arr[i]; // If there is a greater element on right side // and there is a smaller on left side, update // result. else if (smaller[i] != -1) result = max((long long int)(smaller[i] * arr[i] * max_right), result); } return result; } // Driver Program int main() { int arr[] = { 10, 11, 9, 5, 6, 1, 20 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxProduct(arr, n) << endl; return 0; }",linear,nlogn "// C++ Code for the above approach #include using namespace std; /* A binary tree node has data, a pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; }; // Function to return a new Node Node* newNode(int data) { Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Function to convert bst to // a doubly linked list void bstTodll(Node* root, Node*& head) { // if root is NULL if (!root) return; // Convert right subtree recursively bstTodll(root->right, head); // Update root root->right = head; // if head is not NULL if (head) { // Update left of the head head->left = root; } // Update head head = root; // Convert left subtree recursively bstTodll(root->left, head); } // Function to merge two sorted linked list Node* mergeLinkedList(Node* head1, Node* head2) { /*Create head and tail for result list*/ Node* head = NULL; Node* tail = NULL; while (head1 && head2) { if (head1->data < head2->data) { if (!head) head = head1; else { tail->right = head1; head1->left = tail; } tail = head1; head1 = head1->right; } else { if (!head) head = head2; else { tail->right = head2; head2->left = tail; } tail = head2; head2 = head2->right; } } while (head1) { tail->right = head1; head1->left = tail; tail = head1; head1 = head1->right; } while (head2) { tail->right = head2; head2->left = tail; tail = head2; head2 = head2->right; } // Return the created DLL return head; } // function to convert list to bst Node* sortedListToBST(Node*& head, int n) { // if no element is left or head is null if (n <= 0 || !head) return NULL; // Create left part from the list recursively Node* left = sortedListToBST(head, n / 2); Node* root = head; root->left = left; head = head->right; // Create left part from the list recursively root->right = sortedListToBST(head, n - (n / 2) - 1); // Return the root of BST return root; } // This function merges two balanced BSTs Node* mergeTrees(Node* root1, Node* root2, int m, int n) { // Convert BSTs into sorted Doubly Linked Lists Node* head1 = NULL; bstTodll(root1, head1); head1->left = NULL; Node* head2 = NULL; bstTodll(root2, head2); head2->left = NULL; // Merge the two sorted lists into one Node* head = mergeLinkedList(head1, head2); // Construct a tree from the merged lists return sortedListToBST(head, m + n); } void printInorder(Node* node) { // if current node is NULL if (!node) { return; } printInorder(node->left); // Print node of current data cout << node->data << "" ""; printInorder(node->right); } /* Driver code*/ int main() { /* Create following tree as first balanced BST 100 / \ 50 300 / \ 20 70 */ Node* root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \ 40 120 */ Node* root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); // Function Call Node* mergedTree = mergeTrees(root1, root2, 5, 3); cout << ""Following is Inorder traversal of the merged "" ""tree \n""; printInorder(mergedTree); return 0; } // This code is contributed by Tapesh(tapeshdua420)",constant,linear "/* CPP program to check if a tree is height-balanced or not */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; Node(int d) { int data = d; left = right = NULL; } }; // Function to calculate the height of a tree int height(Node* node) { // base case tree is empty if (node == NULL) return 0; // If tree is not empty then // height = 1 + max of left height // and right heights return 1 + max(height(node->left), height(node->right)); } // Returns true if binary tree // with root as root is height-balanced bool isBalanced(Node* root) { // for height of left subtree int lh; // for height of right subtree int rh; // If tree is empty then return true if (root == NULL) return 1; // Get the height of left and right sub trees lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; // If we reach here then tree is not height-balanced return 0; } // Driver code int main() { Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->left->left->left = new Node(8); if (isBalanced(root)) cout << ""Tree is balanced""; else cout << ""Tree is not balanced""; return 0; } // This code is contributed by rathbhupendra",linear,quadratic "// C++ code to implement the approach #include using namespace std; // Structure of a tree node struct Node { int key; struct Node* left; struct Node* right; Node(int k) { key = k; left = right = NULL; } }; // Function to check if tree is height balanced int isBalanced(Node* root) { if (root == NULL) return 0; int lh = isBalanced(root->left); if (lh == -1) return -1; int rh = isBalanced(root->right); if (rh == -1) return -1; if (abs(lh - rh) > 1) return -1; else return max(lh, rh) + 1; } // Driver code int main() { Node* root = new Node(10); root->left = new Node(5); root->right = new Node(30); root->right->left = new Node(15); root->right->right = new Node(20); if (isBalanced(root) > 0) cout << ""Balanced""; else cout << ""Not Balanced""; return 0; }",linear,linear "// C++ program to find number of islands // using Disjoint Set data structure. #include using namespace std; // Class to represent // Disjoint Set Data structure class DisjointUnionSets { vector rank, parent; int n; public: DisjointUnionSets(int n) { rank.resize(n); parent.resize(n); this->n = n; makeSet(); } void makeSet() { // Initially, all elements // are in their own set. for (int i = 0; i < n; i++) parent[i] = i; } // Finds the representative of the set // that x is an element of int find(int x) { if (parent[x] != x) { // if x is not the parent of itself, // then x is not the representative of // its set. // so we recursively call Find on its parent // and move i's node directly under the // representative of this set parent[x]=find(parent[x]); } return parent[x]; } // Unites the set that includes x and the set // that includes y void Union(int x, int y) { // Find the representatives(or the root nodes) // for x an y int xRoot = find(x); int yRoot = find(y); // Elements are in the same set, // no need to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank // Then move x under y so that // depth of tree remains less if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; // Else if y's rank is less than x's rank // Then move y under x so that depth of tree // remains less else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else // Else if their ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } } }; // Returns number of islands in a[][] int countIslands(vector>a) { int n = a.size(); int m = a[0].size(); DisjointUnionSets *dus = new DisjointUnionSets(n * m); /* The following loop checks for its neighbours and unites the indexes if both are 1. */ for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { // If cell is 0, nothing to do if (a[j][k] == 0) continue; // Check all 8 neighbours and do a Union // with neighbour's set if neighbour is // also 1 if (j + 1 < n && a[j + 1][k] == 1) dus->Union(j * (m) + k, (j + 1) * (m) + k); if (j - 1 >= 0 && a[j - 1][k] == 1) dus->Union(j * (m) + k, (j - 1) * (m) + k); if (k + 1 < m && a[j][k + 1] == 1) dus->Union(j * (m) + k, (j) * (m) + k + 1); if (k - 1 >= 0 && a[j][k - 1] == 1) dus->Union(j * (m) + k, (j) * (m) + k - 1); if (j + 1 < n && k + 1 < m && a[j + 1][k + 1] == 1) dus->Union(j * (m) + k, (j + 1) * (m) + k + 1); if (j + 1 < n && k - 1 >= 0 && a[j + 1][k - 1] == 1) dus->Union(j * m + k, (j + 1) * (m) + k - 1); if (j - 1 >= 0 && k + 1 < m && a[j - 1][k + 1] == 1) dus->Union(j * m + k, (j - 1) * m + k + 1); if (j - 1 >= 0 && k - 1 >= 0 && a[j - 1][k - 1] == 1) dus->Union(j * m + k, (j - 1) * m + k - 1); } } // Array to note down frequency of each set int *c = new int[n * m]; int numberOfIslands = 0; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if (a[j][k] == 1) { int x = dus->find(j * m + k); // If frequency of set is 0, // increment numberOfIslands if (c[x] == 0) { numberOfIslands++; c[x]++; } else c[x]++; } } } return numberOfIslands; } // Driver Code int main(void) { vector>a = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; cout << ""Number of Islands is: "" << countIslands(a) << endl; } // This code is contributed by ankush_953",quadratic,quadratic "// C++ program to find the height of the generic // tree(n-ary tree) if parent array is given #include using namespace std; // function to fill the height vector int rec(int i, int parent[], vector height) { // if we have reached root node the // return 1 as height of root node if (parent[i] == -1) { return 1; } // if we have calculated height of a // node then return if if (height[i] != -1) { return height[i]; } // height from root to a node = height // from root to nodes parent + 1 height[i] = rec(parent[i], parent, height) + 1; // return nodes height return height[i]; } // function to find the height of tree int findHeight(int* parent, int n) { int res = 0; // vector to store heights of all nodes vector height(n, -1); for (int i = 0; i < n; i++) { res = max(res, rec(i, parent, height)); } return res; } // Driver program int main() { int parent[] = { -1, 0, 1, 6, 6, 0, 0, 2, 7 }; int n = sizeof(parent) / sizeof(parent[0]); int height = findHeight(parent, n); cout << ""Height of the given tree is: "" << height << endl; return 0; }",linear,linear "// C++ program to find number // of children of given node #include using namespace std; // Represents a node of an n-ary tree class Node { public: int key; vector child; Node(int data) { key = data; } }; // Function to calculate number // of children of given node int numberOfChildren(Node* root, int x) { // initialize the numChildren as 0 int numChildren = 0; if (root == NULL) return 0; // Creating a queue and pushing the root queue q; q.push(root); while (!q.empty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // check if it is equal to x // If YES, then return number of children Node* p = q.front(); q.pop(); if (p->key == x) { numChildren = numChildren + p->child.size(); return numChildren; } // Enqueue all children of the dequeued item for (int i = 0; i < p->child.size(); i++) q.push(p->child[i]); n--; } } return numChildren; } // Driver program int main() { // Creating a generic tree Node* root = new Node(20); (root->child).push_back(new Node(2)); (root->child).push_back(new Node(34)); (root->child).push_back(new Node(50)); (root->child).push_back(new Node(60)); (root->child).push_back(new Node(70)); (root->child[0]->child).push_back(new Node(15)); (root->child[0]->child).push_back(new Node(20)); (root->child[1]->child).push_back(new Node(30)); (root->child[2]->child).push_back(new Node(40)); (root->child[2]->child).push_back(new Node(100)); (root->child[2]->child).push_back(new Node(20)); (root->child[0]->child[1]->child).push_back(new Node(25)); (root->child[0]->child[1]->child).push_back(new Node(50)); // Node whose number of // children is to be calculated int x = 50; // Function calling cout << numberOfChildren(root, x) << endl; return 0; }",linear,linear "// C++ program to find sum of all // elements in generic tree #include using namespace std; // Represents a node of an n-ary tree struct Node { int key; vector child; }; // Utility function to create a new tree node Node* newNode(int key) { Node* temp = new Node; temp->key = key; return temp; } // Function to compute the sum // of all elements in generic tree int sumNodes(Node* root) { // initialize the sum variable int sum = 0; if (root == NULL) return 0; // Creating a queue and pushing the root queue q; q.push(root); while (!q.empty()) { int n = q.size(); // If this node has children while (n > 0) { // Dequeue an item from queue and // add it to variable ""sum"" Node* p = q.front(); q.pop(); sum += p->key; // Enqueue all children of the dequeued item for (int i = 0; i < p->child.size(); i++) q.push(p->child[i]); n--; } } return sum; } // Driver program int main() { // Creating a generic tree Node* root = newNode(20); (root->child).push_back(newNode(2)); (root->child).push_back(newNode(34)); (root->child).push_back(newNode(50)); (root->child).push_back(newNode(60)); (root->child).push_back(newNode(70)); (root->child[0]->child).push_back(newNode(15)); (root->child[0]->child).push_back(newNode(20)); (root->child[1]->child).push_back(newNode(30)); (root->child[2]->child).push_back(newNode(40)); (root->child[2]->child).push_back(newNode(100)); (root->child[2]->child).push_back(newNode(20)); (root->child[0]->child[1]->child).push_back(newNode(25)); (root->child[0]->child[1]->child).push_back(newNode(50)); cout << sumNodes(root) << endl; return 0; }",linear,linear "// C++ program to create a tree with left child // right sibling representation. #include using namespace std; struct Node { int data; struct Node* next; struct Node* child; }; // Creating new Node Node* newNode(int data) { Node* newNode = new Node; newNode->next = newNode->child = NULL; newNode->data = data; return newNode; } // Adds a sibling to a list with starting with n Node* addSibling(Node* n, int data) { if (n == NULL) return NULL; while (n->next) n = n->next; return (n->next = newNode(data)); } // Add child Node to a Node Node* addChild(Node* n, int data) { if (n == NULL) return NULL; // Check if child list is not empty. if (n->child) return addSibling(n->child, data); else return (n->child = newNode(data)); } // Traverses tree in level order void traverseTree(Node* root) { // Corner cases if (root == NULL) return; cout << root->data << "" ""; if (root->child == NULL) return; // Create a queue and enqueue root queue q; Node* curr = root->child; q.push(curr); while (!q.empty()) { // Take out an item from the queue curr = q.front(); q.pop(); // Print next level of taken out item and enqueue // next level's children while (curr != NULL) { cout << curr->data << "" ""; if (curr->child != NULL) { q.push(curr->child); } curr = curr->next; } } } // Driver code int main() { Node* root = newNode(10); Node* n1 = addChild(root, 2); Node* n2 = addChild(root, 3); Node* n3 = addChild(root, 4); Node* n4 = addChild(n3, 6); Node* n5 = addChild(root, 5); Node* n6 = addChild(n5, 7); Node* n7 = addChild(n5, 8); Node* n8 = addChild(n5, 9); traverseTree(root); return 0; }",linear,linear "// C++ program to count number of nodes // which has more children than its parent #include using namespace std; // function to count number of nodes // which has more children than its parent int countNodes(vector adj[], int root) { int count = 0; // queue for applying BFS queue q; // BFS algorithm q.push(root); while (!q.empty()) { int node = q.front(); q.pop(); // traverse children of node for( int i=0;i adj[node].size()) count++; q.push(children); } } return count; } // Driver program to test above functions int main() { // adjacency list for n-ary tree vector adj[10]; // construct n ary tree as shown // in above diagram adj[1].push_back(2); adj[1].push_back(3); adj[2].push_back(4); adj[2].push_back(5); adj[2].push_back(6); adj[3].push_back(9); adj[5].push_back(7); adj[5].push_back(8); int root = 1; cout << countNodes(adj, root); return 0; }",linear,linear "// C++ program to generate short url from integer id and // integer id back from short url. #include #include #include using namespace std; // Function to generate a short url from integer ID string idToShortURL(long int n) { // Map to store 62 possible characters char map[] = ""abcdefghijklmnopqrstuvwxyzABCDEF"" ""GHIJKLMNOPQRSTUVWXYZ0123456789""; string shorturl; // Convert given integer id to a base 62 number while (n) { // use above map to store actual character // in short url shorturl.push_back(map[n%62]); n = n/62; } // Reverse shortURL to complete base conversion reverse(shorturl.begin(), shorturl.end()); return shorturl; } // Function to get integer ID back from a short url long int shortURLtoID(string shortURL) { long int id = 0; // initialize result // A simple base conversion logic for (int i=0; i < shortURL.length(); i++) { if ('a' <= shortURL[i] && shortURL[i] <= 'z') id = id*62 + shortURL[i] - 'a'; if ('A' <= shortURL[i] && shortURL[i] <= 'Z') id = id*62 + shortURL[i] - 'A' + 26; if ('0' <= shortURL[i] && shortURL[i] <= '9') id = id*62 + shortURL[i] - '0' + 52; } return id; } // Driver program to test above function int main() { int n = 12345; string shorturl = idToShortURL(n); cout << ""Generated short url is "" << shorturl << endl; cout << ""Id from url is "" << shortURLtoID(shorturl); return 0; }",constant,linear "// A C++ program to implement Cartesian Tree sort // Note that in this program we will build a min-heap // Cartesian Tree and not max-heap. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; // Creating a shortcut for int, Node* pair type typedef pair iNPair; // This function sorts by pushing and popping the // Cartesian Tree nodes in a pre-order like fashion void pQBasedTraversal(Node* root) { // We will use a priority queue to sort the // partially-sorted data efficiently. // Unlike Heap, Cartesian tree makes use of // the fact that the data is partially sorted priority_queue , greater> pQueue; pQueue.push (make_pair (root->data, root)); // Resembles a pre-order traverse as first data // is printed then the left and then right child. while (! pQueue.empty()) { iNPair popped_pair = pQueue.top(); printf(""%d "", popped_pair.first); pQueue.pop(); if (popped_pair.second->left != NULL) pQueue.push (make_pair(popped_pair.second->left->data, popped_pair.second->left)); if (popped_pair.second->right != NULL) pQueue.push (make_pair(popped_pair.second->right->data, popped_pair.second->right)); } return; } Node *buildCartesianTreeUtil(int root, int arr[], int parent[], int leftchild[], int rightchild[]) { if (root == -1) return NULL; Node *temp = new Node; temp->data = arr[root]; temp->left = buildCartesianTreeUtil(leftchild[root], arr, parent, leftchild, rightchild); temp->right = buildCartesianTreeUtil(rightchild[root], arr, parent, leftchild, rightchild); return temp ; } // A function to create the Cartesian Tree in O(N) time Node *buildCartesianTree(int arr[], int n) { // Arrays to hold the index of parent, left-child, // right-child of each number in the input array int parent[n], leftchild[n], rightchild[n]; // Initialize all array values as -1 memset(parent, -1, sizeof(parent)); memset(leftchild, -1, sizeof(leftchild)); memset(rightchild, -1, sizeof(rightchild)); // 'root' and 'last' stores the index of the root and the // last processed of the Cartesian Tree. // Initially we take root of the Cartesian Tree as the // first element of the input array. This can change // according to the algorithm int root = 0, last; // Starting from the second element of the input array // to the last on scan across the elements, adding them // one at a time. for (int i = 1; i <= n - 1; i++) { last = i-1; rightchild[i] = -1; // Scan upward from the node's parent up to // the root of the tree until a node is found // whose value is smaller than the current one // This is the same as Step 2 mentioned in the // algorithm while (arr[last] >= arr[i] && last != root) last = parent[last]; // arr[i] is the smallest element yet; make it // new root if (arr[last] >= arr[i]) { parent[root] = i; leftchild[i] = root; root = i; } // Just insert it else if (rightchild[last] == -1) { rightchild[last] = i; parent[i] = last; leftchild[i] = -1; } // Reconfigure links else { parent[rightchild[last]] = i; leftchild[i] = rightchild[last]; rightchild[last]= i; parent[i] = last; } } // Since the root of the Cartesian Tree has no // parent, so we assign it -1 parent[root] = -1; return (buildCartesianTreeUtil (root, arr, parent, leftchild, rightchild)); } // Sorts an input array int printSortedArr(int arr[], int n) { // Build a cartesian tree Node *root = buildCartesianTree(arr, n); printf(""The sorted array is-\n""); // Do pr-order traversal and insert // in priority queue pQBasedTraversal(root); } /* Driver program to test above functions */ int main() { /* Given input array- {5,10,40,30,28}, it's corresponding unique Cartesian Tree is- 5 \ 10 \ 28 / 30 / 40 */ int arr[] = {5, 10, 40, 30, 28}; int n = sizeof(arr)/sizeof(arr[0]); printSortedArr(arr, n); return(0); }",linear,nlogn "// C++ Program to search an element // in a sorted and pivoted array #include using namespace std; // Standard Binary Search function int binarySearch(int arr[], int low, int high, int key) { if (high < low) return -1; int mid = (low + high) / 2; if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); } // Function to get pivot. For array 3, 4, 5, 6, 1, 2 // it returns 3 (index of 6) int findPivot(int arr[], int low, int high) { // Base cases if (high < low) return -1; if (high == low) return low; // low + (high - low)/2; int mid = (low + high) / 2; if (mid < high && arr[mid] > arr[mid + 1]) return mid; if (mid > low && arr[mid] < arr[mid - 1]) return (mid - 1); if (arr[low] >= arr[mid]) return findPivot(arr, low, mid - 1); return findPivot(arr, mid + 1, high); } // Searches an element key in a pivoted // sorted array arr[] of size n int pivotedBinarySearch(int arr[], int n, int key) { int pivot = findPivot(arr, 0, n - 1); // If we didn't find a pivot, // then array is not rotated at all if (pivot == -1) return binarySearch(arr, 0, n - 1, key); // If we found a pivot, then first compare with pivot // and then search in two subarrays around pivot if (arr[pivot] == key) return pivot; if (arr[0] <= key) return binarySearch(arr, 0, pivot - 1, key); return binarySearch(arr, pivot + 1, n - 1, key); } // Driver program to check above functions int main() { // Let us search 3 in below array int arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 }; int n = sizeof(arr1) / sizeof(arr1[0]); int key = 3; // Function calling cout << ""Index of the element is : "" << pivotedBinarySearch(arr1, n, key); return 0; }",constant,logn "// Search an element in sorted and rotated // array using single pass of Binary Search #include using namespace std; // Returns index of key in arr[l..h] if // key is present, otherwise returns -1 int search(int arr[], int l, int h, int key) { if (l > h) return -1; int mid = (l + h) / 2; if (arr[mid] == key) return mid; /* If arr[l...mid] is sorted */ if (arr[l] <= arr[mid]) { /* As this subarray is sorted, we can quickly check if key lies in half or other half */ if (key >= arr[l] && key <= arr[mid]) return search(arr, l, mid - 1, key); /*If key not lies in first half subarray, Divide other half into two subarrays, such that we can quickly check if key lies in other half */ return search(arr, mid + 1, h, key); } /* If arr[l..mid] first subarray is not sorted, then arr[mid... h] must be sorted subarray */ if (key >= arr[mid] && key <= arr[h]) return search(arr, mid + 1, h, key); return search(arr, l, mid - 1, key); } // Driver program int main() { int arr[] = { 4, 5, 6, 7, 8, 9, 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 3; int i = search(arr, 0, n - 1, key); if (i != -1) cout << ""Index: "" << i << endl; else cout << ""Key not found""; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,logn "// C++ code to implement the approach #include using namespace std; // This function returns true if arr[0..n-1] // has a pair with sum equals to x. bool pairInSortedRotated(int arr[], int n, int x) { // Find the pivot element int i; for (i = 0; i < n - 1; i++) if (arr[i] > arr[i + 1]) break; // l is now index of smallest element int l = (i + 1) % n; // r is now index of largest element int r = i; // Keep moving either l or r till they meet while (l != r) { // If we find a pair with sum x, // we return true if (arr[l] + arr[r] == x) return true; // If current pair sum is less, // move to the higher sum if (arr[l] + arr[r] < x) l = (l + 1) % n; // Move to the lower sum side else r = (n + r - 1) % n; } return false; } // Driver code int main() { int arr[] = { 11, 15, 6, 8, 9, 10 }; int X = 16; int N = sizeof(arr) / sizeof(arr[0]); // Function call if (pairInSortedRotated(arr, N, X)) cout << ""true""; else cout << ""false""; return 0; }",constant,linear "// C++ program to find max value of i*arr[i] #include using namespace std; // Returns max possible value of i*arr[i] int maxSum(int arr[], int n) { // Find array sum and i*arr[i] with no rotation int arrSum = 0; // Stores sum of arr[i] int currVal = 0; // Stores sum of i*arr[i] for (int i = 0; i < n; i++) { arrSum = arrSum + arr[i]; currVal = currVal + (i * arr[i]); } // Initialize result as 0 rotation sum int maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (int j = 1; j < n; j++) { currVal = currVal + arrSum - n * arr[n - j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal; } // Driver program int main(void) { int arr[] = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""\nMax sum is "" << maxSum(arr, n); return 0; }",constant,linear "// A Naive C++ program to find maximum sum rotation #include using namespace std; // Returns maximum value of i*arr[i] int maxSum(int arr[], int n) { // Initialize result int res = INT_MIN; // Consider rotation beginning with i // for all possible values of i. for (int i=0; i using namespace std; int maxSum(int arr[], int n) { // Compute sum of all array elements int cum_sum = 0; for (int i=0; i using namespace std; // fun declaration int maxSum(int arr[], int n); int findPivot(int arr[], int n); // function definition int maxSum(int arr[], int n) { int sum = 0; int i; int pivot = findPivot(arr, n); // difference in pivot and index of // last element of array int diff = n - 1 - pivot; for(i = 0; i < n; i++) { sum = sum + ((i + diff) % n) * arr[i]; } return sum; } // function to find pivot int findPivot(int arr[], int n) { int i; for(i = 0; i < n; i++) { if(arr[i] > arr[(i + 1) % n]) return i; } } // Driver code int main(void) { // rotated input array int arr[] = {8, 13, 1, 2}; int n = sizeof(arr) / sizeof(int); int max = maxSum(arr, n); cout << max; return 0; } // This code is contributed by Shubhamsingh10",constant,linear "// C++ program for the above approach #include using namespace std; int* rotateArray(int A[], int start, int end) { while (start < end) { int temp = A[start]; A[start] = A[end]; A[end] = temp; start++; end--; } return A; } void leftRotate(int A[], int a, int k) { // if the value of k ever exceeds the length of the // array int c = k % a; // initializing array D so that we always // have a clone of the original array to rotate int D[a]; for (int i = 0; i < a; i++) D[i] = A[i]; rotateArray(D, 0, c - 1); rotateArray(D, c, a - 1); rotateArray(D, 0, a - 1); // printing the rotated array for (int i = 0; i < a; i++) cout << D[i] << "" ""; cout << ""\n""; } int main() { int A[] = { 1, 3, 5, 7, 9 }; int n = sizeof(A) / sizeof(A[0]); int k = 2; leftRotate(A, n, k); k = 3; leftRotate(A, n, k); k = 4; leftRotate(A, n, k); return 0; } // this code is contributed by aditya942003patil",linear,linear "// CPP implementation of left rotation of // an array K number of times #include using namespace std; // Fills temp[] with two copies of arr[] void preprocess(int arr[], int n, int temp[]) { // Store arr[] elements at i and i + n for (int i = 0; i < n; i++) temp[i] = temp[i + n] = arr[i]; } // Function to left rotate an array k times void leftRotate(int arr[], int n, int k, int temp[]) { // Starting position of array after k // rotations in temp[] will be k % n int start = k % n; // Print array after k rotations for (int i = start; i < start + n; i++) cout << temp[i] << "" ""; cout << endl; } // Driver program int main() { int arr[] = { 1, 3, 5, 7, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int temp[2 * n]; preprocess(arr, n, temp); int k = 2; leftRotate(arr, n, k, temp); k = 3; leftRotate(arr, n, k, temp); k = 4; leftRotate(arr, n, k, temp); return 0; }",linear,linear "// CPP implementation of left rotation of // an array K number of times #include using namespace std; // Function to left rotate an array k times void leftRotate(int arr[], int n, int k) { // Print array after k rotations for (int i = k; i < k + n; i++) cout << arr[i % n] << "" ""; } // Driver program int main() { int arr[] = { 1, 3, 5, 7, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; leftRotate(arr, n, k); cout << endl; k = 3; leftRotate(arr, n, k); cout << endl; k = 4; leftRotate(arr, n, k); cout << endl; return 0; }",constant,linear "// C++ code to implement the approach #include using namespace std; // Function to find the minimum value int findMin(int arr[], int n) { int min_ele = arr[0]; // Traversing over array to // find minimum element for (int i = 0; i < n; i++) { if (arr[i] < min_ele) { min_ele = arr[i]; } } return min_ele; } // Driver code int main() { int arr[] = { 5, 6, 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findMin(arr, N) << endl; return 0; }",constant,linear "// C++ program to find minimum // element in a sorted and rotated array #include using namespace std; int findMin(int arr[], int low, int high) { // This condition is needed to // handle the case when array is not // rotated at all if (high < low) return arr[0]; // If there is only one element left if (high == low) return arr[low]; // Find mid int mid = low + (high - low) / 2; /*(low + high)/2;*/ // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid + 1] < arr[mid]) return arr[mid + 1]; // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) return arr[mid]; // Decide whether we need to go to left half or right // half if (arr[high] > arr[mid]) return findMin(arr, low, mid - 1); return findMin(arr, mid + 1, high); } // Driver program to test above functions int main() { int arr[] = { 5, 6, 1, 2, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""The minimum element is "" << findMin(arr, 0, N - 1) << endl; return 0; } // This is code is contributed by rathbhupendra",constant,logn "// C++ program for right rotation of // an array (Reversal Algorithm) #include /*Function to reverse arr[] from index start to end*/ void reverseArray(int arr[], int start, int end) { while (start < end) { std::swap(arr[start], arr[end]); start++; end--; } } /* Function to right rotate arr[] of size n by d */ void rightRotate(int arr[], int d, int n) { // if in case d>n,this will give segmentation fault. d=d%n; reverseArray(arr, 0, n-1); reverseArray(arr, 0, d-1); reverseArray(arr, d, n-1); } /* function to print an array */ void printArray(int arr[], int size) { for (int i = 0; i < size; i++) std::cout << arr[i] << "" ""; } // driver code int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; rightRotate(arr, k, n); printArray(arr, n); return 0; }",constant,linear "// C++ Program to solve queries on Left and Right // Circular shift on array #include using namespace std; // Function to solve query of type 1 x. void querytype1(int* toRotate, int times, int n) { // Decreasing the absolute rotation (*toRotate) = ((*toRotate) - times) % n; } // Function to solve query of type 2 y. void querytype2(int* toRotate, int times, int n) { // Increasing the absolute rotation. (*toRotate) = ((*toRotate) + times) % n; } // Function to solve queries of type 3 l r. void querytype3(int toRotate, int l, int r, int preSum[], int n) { // Finding absolute l and r. l = (l + toRotate + n) % n; r = (r + toRotate + n) % n; // if l is before r. if (l <= r) cout << (preSum[r + 1] - preSum[l]) << endl; // If r is before l. else cout << (preSum[n] + preSum[r + 1] - preSum[l]) << endl; } // Wrapper Function solve all queries. void wrapper(int a[], int n) { int preSum[n + 1]; preSum[0] = 0; // Finding Prefix sum for (int i = 1; i <= n; i++) preSum[i] = preSum[i - 1] + a[i - 1]; int toRotate = 0; // Solving each query querytype1(&toRotate, 3, n); querytype3(toRotate, 0, 2, preSum, n); querytype2(&toRotate, 1, n); querytype3(toRotate, 1, 4, preSum, n); } // Driver Program int main() { int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); wrapper(arr, N); return 0; }",linear,linear "// C++ implementation of left rotation of // an array K number of times #include using namespace std; // Function to leftRotate array multiple times void leftRotate(int arr[], int n, int k) { /* To get the starting point of rotated array */ int mod = k % n; // Prints the rotated array from start position for (int i = 0; i < n; i++) cout << (arr[(mod + i) % n]) << "" ""; cout << ""\n""; } // Driver Code int main() { int arr[] = { 1, 3, 5, 7, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; // Function Call leftRotate(arr, n, k); k = 3; // Function Call leftRotate(arr, n, k); k = 4; // Function Call leftRotate(arr, n, k); return 0; }",constant,linear "#include using namespace std; int findElement(vector arr, int ranges[][2], int rotations, int index) { // Track of the rotation number int n1 = 1; // Track of the row index for the ranges[][] array int i = 0; // Initialize the left side of the ranges[][] array int leftRange = 0; // Initialize the right side of the ranges[][] array int rightRange = 0; // Initialize the key variable int key = 0; while (n1 <= rotations) { leftRange = ranges[i][0]; rightRange = ranges[i][1]; key = arr[rightRange]; for (int j = rightRange; j >= leftRange + 1; j--) { arr[j] = arr[j - 1]; } arr[leftRange] = key; n1++; i++; } // Return the element after all the rotations return arr[index]; } int main() { vector arr{ 1, 2, 3, 4, 5 }; // No. of rotations int rotations = 2; // Ranges according to 0-based indexing int ranges[][2] = { { 0, 2 }, { 0, 3 } }; int index = 1; cout << (findElement(arr, ranges, rotations, index)); } // This code is contributed by garg28harsh.",constant,quadratic "// CPP code to rotate an array // and answer the index query #include using namespace std; // Function to compute the element at // given index int findElement(int arr[], int ranges[][2], int rotations, int index) { for (int i = rotations - 1; i >= 0; i--) { // Range[left...right] int left = ranges[i][0]; int right = ranges[i][1]; // Rotation will not have any effect if (left <= index && right >= index) { if (index == left) index = right; else index--; } } // Returning new element return arr[index]; } // Driver int main() { int arr[] = { 1, 2, 3, 4, 5 }; // No. of rotations int rotations = 2; // Ranges according to 0-based indexing int ranges[rotations][2] = { { 0, 2 }, { 0, 3 } }; int index = 1; cout << findElement(arr, ranges, rotations, index); return 0; }",constant,constant "// CPP program to split array and move first // part to end. #include using namespace std; void splitArr(int arr[], int n, int k) { for (int i = 0; i < k; i++) { // Rotate array by 1. int x = arr[0]; for (int j = 0; j < n - 1; ++j) arr[j] = arr[j + 1]; arr[n - 1] = x; } } // Driver code int main() { int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = sizeof(arr) / sizeof(arr[0]); int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) cout <<"" ""<< arr[i]; return 0; } // This code is contributed by shivanisinghss2110",constant,quadratic "// CPP program to split array and move first // part to end. #include using namespace std; // Function to split array and // move first part to end void splitArr(int arr[], int length, int rotation) { int tmp[length * 2] = {0}; for(int i = 0; i < length; i++) { tmp[i] = arr[i]; tmp[i + length] = arr[i]; } for(int i = rotation; i < rotation + length; i++) { arr[i - rotation] = tmp[i]; } } // Driver code int main() { int arr[] = { 12, 10, 5, 6, 52, 36 }; int n = sizeof(arr) / sizeof(arr[0]); int position = 2; splitArr(arr, n, position); for (int i = 0; i < n; ++i) printf(""%d "", arr[i]); return 0; } // This code is contributed by YashKhandelwal8",linear,linear "// C++ program for above approach #include using namespace std; // Function to transform the array void fixArray(int ar[], int n) { int i, j, temp; // Iterate over the array for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for (i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output cout << ""Array after Rearranging"" << endl; for (i = 0; i < n; i++) { cout << ar[i] << "" ""; } } // Driver Code int main() { int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; n = sizeof(ar) / sizeof(ar[0]); // Function Call fixArray(ar, n); } // Code BY Tanmay Anand",constant,quadratic "// C++ program for rearrange an // array such that arr[i] = i. #include using namespace std; // Function to rearrange an array // such that arr[i] = i. void fixArray(int A[], int len) { for (int i = 0; i < len; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired place // is not vacate while (A[x] != -1 && A[x] != x) { // store the value from // desired place int y = A[x]; // place the x to its correct // position A[x] = x; // now y will become x, now // search the place for x x = y; } // place the x to its correct // position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 at // the vacated place A[i] = -1; } } } } // Driver code int main() { int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int len = sizeof(A) / sizeof(A[0]); // Function Call fixArray(A, len); // Print the output for (int i = 0; i < len; i++) cout << A[i] << "" ""; } // This code is contributed by Smitha Dinesh Semwal",constant,linear "#include #include using namespace std; void fixArray(int arr[], int n) { // a set unordered_set s; // Enter each element which is not -1 in set for(int i=0; i using namespace std; void fixArray(int arr[], int n) { int i = 0; while (i < n) { int correct = arr[i]; if (arr[i] != -1 && arr[i] != arr[correct]) { // if array element should be lesser than // size and array element should not be at // its correct position then only swap with // its correct position or index value swap(arr[i], arr[correct]); } else { // if element is at its correct position // just increment i and check for remaining // array elements i++; } } return arr; } // Driver Code int main() { int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call fixArray(arr, n); // Print output for (int i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; } // This Code is Contributed by kothavvsaakash",constant,linear "// C++ program to rearrange the array as per the given // condition #include using namespace std; // function to rearrange the array void rearrangeArr(int arr[], int n) { // total even positions int evenPos = n / 2; // total odd positions int oddPos = n - evenPos; int tempArr[n]; // copy original array in an auxiliary array for (int i = 0; i < n; i++) tempArr[i] = arr[i]; // sort the auxiliary array sort(tempArr, tempArr + n); int j = oddPos - 1; // fill up odd position in original array for (int i = 0; i < n; i += 2) arr[i] = tempArr[j--]; j = oddPos; // fill up even positions in original array for (int i = 1; i < n; i += 2) arr[i] = tempArr[j++]; // display array for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Driver code int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int size = sizeof(arr) / sizeof(arr[0]); rearrangeArr(arr, size); return 0; }",linear,nlogn "#include using namespace std; int main(){ int n,i,p,q; int a[]= {1, 2, 1, 4, 5, 6, 8, 8}; n=sizeof(a)/sizeof(a[0]); int b[n]; for(i=0;i=0;i--){ if(i%2!=0){ a[i]=b[q]; q--; } else{ a[i]=b[p]; p++; } } for(i=0;i #include using namespace std; // Utility function to right rotate all elements between // [outofplace, cur] void rightrotate(int arr[], int n, int outofplace, int cur) { char tmp = arr[cur]; for (int i = cur; i > outofplace; i--) arr[i] = arr[i - 1]; arr[outofplace] = tmp; } void rearrange(int arr[], int n) { int outofplace = -1; for (int index = 0; index < n; index++) { if (outofplace >= 0) { // find the item which must be moved into the // out-of-place entry if out-of-place entry is // positive and current entry is negative OR if // out-of-place entry is negative and current // entry is negative then right rotate // // [...-3, -4, -5, 6...] --> [...6, -3, -4, // -5...] // ^ ^ // | | // outofplace --> outofplace // if (((arr[index] >= 0) && (arr[outofplace] < 0)) || ((arr[index] < 0) && (arr[outofplace] >= 0))) { rightrotate(arr, n, outofplace, index); // the new out-of-place entry is now 2 steps // ahead if (index - outofplace >= 2) outofplace = outofplace + 2; else outofplace = -1; } } // if no entry has been flagged out-of-place if (outofplace == -1) { // check if current entry is out-of-place if (((arr[index] >= 0) && (!(index & 0x01))) || ((arr[index] < 0) && (index & 0x01))) { outofplace = index; } } } } // A utility function to print an array 'arr[]' of size 'n' void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; cout << endl; } // Driver code int main() { int arr[] = { -5, -2, 5, 2, 4, 7, 1, 8, 0, -8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Given array is \n""; printArray(arr, n); rearrange(arr, n); cout << ""Rearranged array is \n""; printArray(arr, n); return 0; }",constant,quadratic "// C++ Program to move all zeros to the end #include using namespace std; int main() { int A[] = { 5, 6, 0, 4, 6, 0, 9, 0, 8 }; int n = sizeof(A) / sizeof(A[0]); int j = 0; for (int i = 0; i < n; i++) { if (A[i] != 0) { swap(A[j], A[i]); // Partitioning the array j++; } } for (int i = 0; i < n; i++) { cout << A[i] << "" ""; // Print the array } return 0; }",constant,linear "# C++ program to shift all zeros # to right most side of array # without affecting order of non-zero # elements # Given list arr = [5, 6, 0, 4, 6, 0, 9, 0, 8] # Storing all non zero values nonZeroValues = [x for x in arr if x != 0] # Storing all zeroes zeroes = [j for j in arr if j == 0] # Updating the answer arr = nonZeroValues + zeroes # Printing the answer print( ""array after shifting zeros to right side: "" + arr)",constant,linear "// C++ implementation to move all zeroes at the end of array #include using namespace std; // function to move all zeroes at the end of array void moveZerosToEnd(int arr[], int n) { // Count of non-zero elements int count = 0; // Traverse the array. If arr[i] is non-zero, then // update the value of arr at index count to arr[i] for (int i = 0; i < n; i++) if (arr[i] != 0) arr[count++] = arr[i]; // Update all elements at index >=count with value 0 for (int i = count; i < n; i++) arr[i] = 0; } // function to print the array elements void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Driver program to test above int main() { int arr[] = { 0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Original array: ""; printArray(arr, n); moveZerosToEnd(arr, n); cout << ""\nModified array: ""; printArray(arr, n); return 0; }",constant,linear "// C++ program to find minimum swaps required // to club all elements less than or equals // to k together #include using namespace std; // Utility function to find minimum swaps // required to club all elements less than // or equals to k together int minSwap(int *arr, int n, int k) { // Find count of elements which are // less than equals to k int count = 0; for (int i = 0; i < n; ++i) if (arr[i] <= k) ++count; // Find unwanted elements in current // window of size 'count' int bad = 0; for (int i = 0; i < count; ++i) if (arr[i] > k) ++bad; // Initialize answer with 'bad' value of // current window int ans = bad; for (int i = 0, j = count; j < n; ++i, ++j) { // Decrement count of previous window if (arr[i] > k) --bad; // Increment count of current window if (arr[j] > k) ++bad; // Update ans if count of 'bad' // is less in current window ans = min(ans, bad); } return ans; } // Driver code int main() { int arr[] = {2, 1, 5, 6, 3}; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << minSwap(arr, n, k) << ""\n""; int arr1[] = {2, 7, 9, 5, 8, 7, 4}; n = sizeof(arr1) / sizeof(arr1[0]); k = 5; cout << minSwap(arr1, n, k); return 0; }",constant,linear "#include using namespace std; // Function for finding the minimum number of swaps // required to bring all the numbers less // than or equal to k together. int minSwap(int arr[], int n, int k) { // Initially snowBallsize is 0 int snowBallSize = 0; for (int i = 0; i < n; i++) { // Calculating the size of window required if (arr[i] <= k) { snowBallSize++; } } int swap = 0, ans_swaps = INT_MAX; for (int i = 0; i < snowBallSize; i++) { if (arr[i] > k) swap++; } ans_swaps = min(ans_swaps, swap); for (int i = snowBallSize; i < n; i++) { // Checking in every window no. of swaps required // and storing its minimum if (arr[i - snowBallSize] <= k && arr[i] > k) swap++; else if (arr[i - snowBallSize] > k && arr[i] <= k) swap--; ans_swaps = min(ans_swaps, swap); } return ans_swaps; } // Driver's code int main() { int arr1[] = { 2, 7, 9, 5, 8, 7, 4 }; int n = sizeof(arr1) / sizeof(arr1[0]); int k = 5; cout << minSwap(arr1, n, k) << ""\n""; return 0; } // This code is contributed by aditya942003patil",constant,linear "// C++ implementation of // the above approach #include void printArray(int array[], int length) { std::cout << ""[""; for(int i = 0; i < length; i++) { std::cout << array[i]; if(i < (length - 1)) std::cout << "", ""; else std::cout << ""]"" << std::endl; } } void reverse(int array[], int start, int end) { while(start < end) { int temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end--; } } // Rearrange the array with all negative integers // on left and positive integers on right // use recursion to split the array with first element // as one half and the rest array as another and then // merge it with head of the array in each step void rearrange(int array[], int start, int end) { // exit condition if(start == end) return; // rearrange the array except the first // element in each recursive call rearrange(array, (start + 1), end); // If the first element of the array is positive, // then right-rotate the array by one place first // and then reverse the merged array. if(array[start] >= 0) { reverse(array, (start + 1), end); reverse(array, start, end); } } // Driver code int main() { int array[] = {-12, -11, -13, -5, -6, 7, 5, 3, 6}; int length = (sizeof(array) / sizeof(array[0])); int countNegative = 0; for(int i = 0; i < length; i++) { if(array[i] < 0) countNegative++; } std::cout << ""array: ""; printArray(array, length); rearrange(array, 0, (length - 1)); reverse(array, countNegative, (length - 1)); std::cout << ""rearranged array: ""; printArray(array, length); return 0; }",quadratic,quadratic "// C++ program to print the array in given order #include using namespace std; // Function which arrange the array. void rearrangeArray(int arr[], int n) { // Sorting the array elements sort(arr, arr + n); int tempArr[n]; // To store modified array // Adding numbers from sorted array to // new array accordingly int ArrIndex = 0; // Traverse from begin and end simultaneously for (int i = 0, j = n - 1; i <= n / 2 || j > n / 2; i++, j--) { tempArr[ArrIndex] = arr[i]; ArrIndex++; tempArr[ArrIndex] = arr[j]; ArrIndex++; } // Modifying original array for (int i = 0; i < n; i++) arr[i] = tempArr[i]; } // Driver Code int main() { int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 }; int n = sizeof(arr) / sizeof(arr[0]); rearrangeArray(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; }",linear,nlogn "// C++ implementation to rearrange the array elements after // modification #include using namespace std; // function which pushes all zeros to end of an array. void pushZerosToEnd(int arr[], int n) { // Count of non-zero elements int count = 0; // Traverse the array. If element encountered is // non-zero, then replace the element at index 'count' // with this element for (int i = 0; i < n; i++) if (arr[i] != 0) // here count is incremented arr[count++] = arr[i]; // Now all non-zero elements have been shifted to front // and 'count' is set as index of first 0. Make all // elements 0 from count to end. while (count < n) arr[count++] = 0; } // function to rearrange the array elements after // modification void modifyAndRearrangeArr(int arr[], int n) { // if 'arr[]' contains a single element only if (n == 1) return; // traverse the array for (int i = 0; i < n - 1; i++) { // if true, perform the required modification if ((arr[i] != 0) && (arr[i] == arr[i + 1])) { // double current index value arr[i] = 2 * arr[i]; // put 0 in the next index arr[i + 1] = 0; // increment by 1 so as to move two indexes // ahead during loop iteration i++; } } // push all the zeros at the end of 'arr[]' pushZerosToEnd(arr, n); } // function to print the array elements void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Driver program to test above int main() { int arr[] = { 0, 2, 2, 2, 0, 6, 6, 0, 0, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Original array: ""; printArray(arr, n); modifyAndRearrangeArr(arr, n); cout << ""\nModified array: ""; printArray(arr, n); return 0; }",constant,linear "// C++ program to Rearrange positive and negative // numbers in a array #include using namespace std; // A utility function to print an array of size n void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout< l - 1; j--) { arr[j] = arr[j - 1]; } arr[l] = temp; } void moveNegative(int arr[], int n) { int last_negative_index = -1; for (int i = 0; i < n; i++) { if (arr[i] < 0) { last_negative_index += 1; int temp = arr[i]; arr[i] = arr[last_negative_index]; arr[last_negative_index] = temp; // Done to manage order too if (i - last_negative_index >= 2) rotateSubArray(arr, last_negative_index + 1, i); } } } // Driver Code int main() { int arr[] = { 5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); moveNegative(arr, n); printArray(arr, n); return 0; } // This code is contributed by Aarti_Rathi",constant,quadratic "// C++ program to Rearrange positive and negative // numbers in a array #include // A utility function to print an array of size n void printArray(int arr[], int n) { for (int i = 0; i < n; i++) printf(""%d "", arr[i]); printf(""\n""); } // Function to Rearrange positive and negative // numbers in a array void RearrangePosNeg(int arr[], int n) { int key, j; for (int i = 1; i < n; i++) { key = arr[i]; // if current element is positive // do nothing if (key > 0) continue; /* if current element is negative, shift positive elements of arr[0..i-1], to one position to their right */ j = i - 1; while (j >= 0 && arr[j] > 0) { arr[j + 1] = arr[j]; j = j - 1; } // Put negative element at its right position arr[j + 1] = key; } } /* Driver program to test above functions */ int main() { int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int n = sizeof(arr) / sizeof(arr[0]); RearrangePosNeg(arr, n); printArray(arr, n); return 0; }",constant,quadratic "// C++ program to Rearrange positive and negative // numbers in a array #include using namespace std; /* Function to print an array */ void printArray(int A[], int size) { for (int i = 0; i < size; i++) cout << A[i] << "" ""; cout << endl; } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray // Note the order of appearance of elements should // be maintained - we copy elements of left subarray // first followed by that of right subarray // copy negative elements of left subarray while (i < n1 && L[i] < 0) arr[k++] = L[i++]; // copy negative elements of right subarray while (j < n2 && R[j] < 0) arr[k++] = R[j++]; // copy positive elements of left subarray while (i < n1) arr[k++] = L[i++]; // copy positive elements of right subarray while (j < n2) arr[k++] = R[j++]; } // Function to Rearrange positive and negative // numbers in a array void RearrangePosNeg(int arr[], int l, int r) { if (l < r) { // Same as (l + r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); } } /* Driver program to test above functions */ int main() { int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int arr_size = sizeof(arr) / sizeof(arr[0]); RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); return 0; }",linear,nlogn "// C++ program to Rearrange positive and negative // numbers in a array #include using namespace std; /* Function to print an array */ void printArray(int A[], int size) { for (int i = 0; i < size; i++) cout << A[i] << "" ""; cout << endl; } /* Function to reverse an array. An array can be reversed in O(n) time and O(1) space. */ void reverse(int arr[], int l, int r) { if (l < r) { swap(arr[l], arr[r]); reverse(arr, ++l, --r); } } // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { int i = l; // Initial index of 1st subarray int j = m + 1; // Initial index of IInd while (i <= m && arr[i] < 0) i++; // arr[i..m] is positive while (j <= r && arr[j] < 0) j++; // arr[j..r] is positive // reverse positive part of // left sub-array (arr[i..m]) reverse(arr, i, m); // reverse negative part of // right sub-array (arr[m+1..j-1]) reverse(arr, m + 1, j - 1); // reverse arr[i..j-1] reverse(arr, i, j - 1); } // Function to Rearrange positive and negative // numbers in a array void RearrangePosNeg(int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves RearrangePosNeg(arr, l, m); RearrangePosNeg(arr, m + 1, r); merge(arr, l, m, r); } } /* Driver code */ int main() { int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int arr_size = sizeof(arr) / sizeof(arr[0]); RearrangePosNeg(arr, 0, arr_size - 1); printArray(arr, arr_size); return 0; }",logn,nlogn "#include using namespace std; void Rearrange(int arr[], int n) { stable_partition(arr,arr+n,[](int x){return x<0;}); } int main() { int n=4; int arr[n]={-3, 3, -2, 2}; Rearrange( arr, n); for (int i = 0; i < n; i++) cout << arr[i] << "" ""; cout << endl; }",linear,quadratic "#include using namespace std; void rearrangePosNegWithOrder(int *arr, int size) { int i = 0, j = 0; while (j < size) { if (arr[j] >= 0) { j++; } else { for (int k = j; k > i; k--) { int temp = arr[k]; arr[k] = arr[k - 1]; arr[k - 1] = temp; } i++; j++; } } } int main() { int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 }; int size = *(&arr + 1) - arr; rearrangePosNegWithOrder(arr, size); for (int i : arr) { cout << i; cout << "" ""; } return 0; }",constant,linear "// C++ program to rearrange an array in minimum // maximum form #include using namespace std; // Prints max at first position, min at second position // second max at third position, second min at fourth // position and so on. void rearrange(int arr[], int n) { // Auxiliary array to hold modified array int temp[n]; // Indexes of smallest and largest elements // from remaining array. int small = 0, large = n - 1; // To indicate whether we need to copy remaining // largest or remaining smallest at next position int flag = true; // Store result in temp[] for (int i = 0; i < n; i++) { if (flag) temp[i] = arr[large--]; else temp[i] = arr[small++]; flag = !flag; } // Copy temp[] to arr[] for (int i = 0; i < n; i++) arr[i] = temp[i]; } // Driver code int main() { int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Original Array\n""; for (int i = 0; i < n; i++) cout << arr[i] << "" ""; rearrange(arr, n); cout << ""\nModified Array\n""; for (int i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; }",linear,linear "#include #include #include using namespace std; void move(vector& arr){ sort(arr.begin(),arr.end()); } int main() { vector arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 }; move(arr); for (int e : arr) cout< using namespace std; void rearrange(int arr[], int n) { int j = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) { if (i != j) swap(arr[i], arr[j]); j++; } } } // A utility function to print an array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) printf(""%d "", arr[i]); } // Driver code int main() { int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); rearrange(arr, n); printArray(arr, n); return 0; }",constant,linear "// C++ program of the above // approach #include using namespace std; // Function to shift all the // negative elements on left side void shiftall(int arr[], int left, int right) { // Loop to iterate over the // array from left to the right while (left<=right) { // Condition to check if the left // and the right elements are // negative if (arr[left] < 0 && arr[right] < 0) left+=1; // Condition to check if the left // pointer element is positive and // the right pointer element is negative else if (arr[left]>0 && arr[right]<0) { int temp=arr[left]; arr[left]=arr[right]; arr[right]=temp; left+=1; right-=1; } // Condition to check if both the // elements are positive else if (arr[left]>0 && arr[right] >0) right-=1; else{ left += 1; right -= 1; } } } // Function to print the array void display(int arr[], int right){ // Loop to iterate over the element // of the given array for (int i=0;i<=right;++i){ cout< using namespace std; // Swap Function. void swap(int &a,int &b){ int temp =a; a=b; b=temp; } // Using Dutch National Flag Algorithm. void reArrange(int arr[],int n){ int low =0,high = n-1; while(low0){ high--; }else{ swap(arr[low],arr[high]); } } } void displayArray(int arr[],int n){ for(int i=0;i using namespace std; // Moves all -ve element to end of array in // same order. void segregateElements(int arr[], int n) { // Create an empty array to store result int temp[n]; // Traversal array and store +ve element in // temp array int j = 0; // index of temp for (int i = 0; i < n ; i++) if (arr[i] >= 0 ) temp[j++] = arr[i]; // If array contains all positive or all negative. if (j == n || j == 0) return; // Store -ve element in temp array for (int i = 0 ; i < n ; i++) if (arr[i] < 0) temp[j++] = arr[i]; // Copy contents of temp[] to arr[] memcpy(arr, temp, sizeof(temp)); } // Driver program int main() { int arr[] = {1 ,-1 ,-3 , -2, 7, 5, 11, 6 }; int n = sizeof(arr)/sizeof(arr[0]); segregateElements(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; }",linear,linear "// CPP code to rearrange an array such that // even index elements are smaller and odd // index elements are greater than their // next. #include using namespace std; void rearrange(int* arr, int n) { for (int i = 0; i < n - 1; i++) { if (i % 2 == 0 && arr[i] > arr[i + 1]) swap(arr[i], arr[i + 1]); if (i % 2 != 0 && arr[i] < arr[i + 1]) swap(arr[i], arr[i + 1]); } } /* Utility that prints out an array in a line */ void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << "" ""; cout << endl; } /* Driver function to test above functions */ int main() { int arr[] = { 6, 4, 2, 1, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Before rearranging: \n""; printArray(arr, n); rearrange(arr, n); cout << ""After rearranging: \n""; printArray(arr, n); return 0; }",constant,linear "// C++ program to rearrange positive and negative // numbers #include using namespace std; void rearrange(int a[], int size) { int positive = 0, negative = 1; while (true) { /* Move forward the positive pointer till negative number number not encountered */ while (positive < size && a[positive] >= 0) positive += 2; /* Move forward the negative pointer till positive number number not encountered */ while (negative < size && a[negative] <= 0) negative += 2; // Swap array elements to fix their position. if (positive < size && negative < size) swap(a[positive], a[negative]); /* Break from the while loop when any index exceeds the size of the array */ else break; } } // Driver code int main() { int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = (sizeof(arr) / sizeof(arr[0])); rearrange(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; }",constant,quadratic "// C++ program to rearrange positive // and negative numbers #include using namespace std; // Swap function void swap(int* a, int i , int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; return ; } // Print array function void printArray(int* a, int n) { for(int i = 0; i < n; i++) cout << a[i] << "" ""; cout << endl; return ; } // Driver code int main() { int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 }; int n = sizeof(arr)/sizeof(arr[0]); //before modification printArray(arr, n); for(int i = 0; i < n; i++) { if(arr[i] >= 0 && i % 2 == 1) { // out of order positive element for(int j = i + 1; j < n; j++) { if(arr[j] < 0 && j % 2 == 0) { // find out of order negative // element in remaining array swap(arr, i, j); break ; } } } else if(arr[i] < 0 && i % 2 == 0) { // out of order negative element for(int j = i + 1; j < n; j++) { if(arr[j] >= 0 && j % 2 == 1) { // find out of order positive // element in remaining array swap(arr, i, j); break; } } } } //after modification printArray(arr, n); return 0; } // This code is contributed by AnitAggarwal",constant,quadratic "// C++ program to update every array element with // multiplication of previous and next numbers in array #include using namespace std; void modify(int arr[], int n) { // Nothing to do when array size is 1 if (n <= 1) return; // store current value of arr[0] and update it int prev = arr[0]; arr[0] = arr[0] * arr[1]; // Update rest of the array elements for (int i=1; i #include #include using namespace std; // A utility function to swap to integers void swap (int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // A utility function to print an array void printArray (int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; cout << ""\n""; } // A function to generate a random // permutation of arr[] void randomize (int arr[], int n) { // Use a different seed value so that // we don't get same result each time // we run this program srand (time(NULL)); // Start from the last element and swap // one by one. We don't need to run for // the first element that's why i > 0 for (int i = n - 1; i > 0; i--) { // Pick a random index from 0 to i int j = rand() % (i + 1); // Swap arr[i] with the element // at random index swap(&arr[i], &arr[j]); } } // Driver Code int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr) / sizeof(arr[0]); randomize (arr, n); printArray(arr, n); return 0; } // This code is contributed by // rathbhupendra",constant,linear "// C++ Implementation of the above approach #include using namespace std; void arrayEvenAndOdd(int arr[], int n) { int a[n], index = 0; for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { a[index] = arr[i]; index++; } } for (int i = 0; i < n; i++) { cout << a[i] << "" ""; } cout << endl; } // Driver code int main() { int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = sizeof(arr) / sizeof(int); // Function call arrayEvenAndOdd(arr, n); return 0; }",linear,linear "// CPP code to segregate even odd // numbers in an array #include using namespace std; // Function to segregate even odd numbers void arrayEvenAndOdd(int arr[], int n) { int i = -1, j = 0; int t; while (j != n) { if (arr[j] % 2 == 0) { i++; // Swapping even and odd numbers swap(arr[i], arr[j]); } j++; } // Printing segregated array for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Driver code int main() { int arr[] = { 1, 3, 2, 4, 7, 6, 9, 10 }; int n = sizeof(arr) / sizeof(int); arrayEvenAndOdd(arr, n); return 0; }",constant,linear "// C++ program of above implementation #include using namespace std; // Standard partition process of QuickSort(). // It considers the last element as pivot and // oves all smaller element to left of it // and greater elements to right int partition(int* arr, int l, int r) { int x = arr[r], i = l; for (int j = l; j <= r - 1; j++) { if (arr[j] <= x) { swap(arr[i], arr[j]); i++; } } swap(arr[i], arr[r]); return i; } int randomPartition(int* arr, int l, int r) { int n = r - l + 1; int pivot = (rand() % 100 + 1) % n; swap(arr[l + pivot], arr[r]); return partition(arr, l, r); } // This function returns k'th smallest // element in arr[l..r] using // QuickSort based method. ASSUMPTION: // ALL ELEMENTS IN ARR[] ARE DISTINCT int kthSmallest(int* arr, int l, int r, int k) { // If k is smaller than number // of elements in array if (k > 0 && k <= r - l + 1) { // Partition the array around last // element and get position of pivot // element in sorted array int pos = randomPartition(arr, l, r); // If position is same as k if (pos - l == k - 1) { return arr[pos]; } // If position is more, recur // for left subarray if (pos - l > k - 1) { return kthSmallest(arr, l, pos - 1, k); } // Else recur for right subarray return kthSmallest(arr, pos + 1, r, k - pos + l - 1); } // If k is more than number of // elements in array return INT_MAX; } // Driver Code int main() { int arr[] = { 12, 3, 5, 7, 4, 19, 26 }; int n = sizeof(arr) / sizeof(arr[0]), k = 3; cout << ""K'th smallest element is "" << kthSmallest(arr, 0, n - 1, k); }",constant,nlogn "// STL based C++ program to find k-th smallest // element. #include using namespace std; int kthSmallest(int arr[], int n, int k) { // Insert all elements into the set set s; for (int i = 0; i < n; i++) s.insert(arr[i]); // Traverse set and print k-th element auto it = s.begin(); for (int i = 0; i < k - 1; i++) it++; return *it; } int main() { int arr[] = { 12, 3, 5, 7, 3, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 2; cout << ""K'th smallest element is "" << kthSmallest(arr, n, k); return 0; }",linear,nlogn "#include using namespace std; // Swap function to interchange // the value of variables x and y int swap(int& x, int& y) { int temp = x; x = y; y = temp; } // Min Heap Class // arr holds reference to an integer // array size indicate the number of // elements in Min Heap class MinHeap { int size; int* arr; public: // Constructor to initialize the size and arr MinHeap(int size, int input[]); // Min Heapify function, that assumes that // 2*i+1 and 2*i+2 are min heap and fix the // heap property for i. void heapify(int i); // Build the min heap, by calling heapify // for all non-leaf nodes. void buildHeap(); }; // Constructor to initialize data // members and creating mean heap MinHeap::MinHeap(int size, int input[]) { // Initializing arr and size this->size = size; this->arr = input; // Building the Min Heap buildHeap(); } // Min Heapify function, that assumes // 2*i+1 and 2*i+2 are min heap and // fix min heap property for i void MinHeap::heapify(int i) { // If Leaf Node, Simply return if (i >= size / 2) return; // variable to store the smallest element // index out of i, 2*i+1 and 2*i+2 int smallest; // Index of left node int left = 2 * i + 1; // Index of right node int right = 2 * i + 2; // Select minimum from left node and // current node i, and store the minimum // index in smallest variable smallest = arr[left] < arr[i] ? left : i; // If right child exist, compare and // update the smallest variable if (right < size) smallest = arr[right] < arr[smallest] ? right : smallest; // If Node i violates the min heap // property, swap current node i with // smallest to fix the min-heap property // and recursively call heapify for node smallest. if (smallest != i) { swap(arr[i], arr[smallest]); heapify(smallest); } } // Build Min Heap void MinHeap::buildHeap() { // Calling Heapify for all non leaf nodes for (int i = size / 2 - 1; i >= 0; i--) { heapify(i); } } void FirstKelements(int arr[],int size,int k){ // Creating Min Heap for given // array with only k elements MinHeap* m = new MinHeap(k, arr); // Loop For each element in array // after the kth element for (int i = k; i < size; i++) { // if current element is smaller // than minimum element, do nothing // and continue to next element if (arr[0] > arr[i]) continue; // Otherwise Change minimum element to // current element, and call heapify to // restore the heap property else { arr[0] = arr[i]; m->heapify(0); } } // Now min heap contains k maximum // elements, Iterate and print for (int i = 0; i < k; i++) { cout << arr[i] << "" ""; } } // Driver Program int main() { int arr[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int size = sizeof(arr) / sizeof(arr[0]); // Size of Min Heap int k = 3; FirstKelements(arr,size,k); return 0; } // This code is contributed by Ankur Goel",linear,nlogn "#include using namespace std; // picks up last element between start and end int findPivot(int a[], int start, int end) { // Selecting the pivot element int pivot = a[end]; // Initially partition-index will be at starting int pIndex = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { swap(a[i], a[pIndex]); // Incrementing pIndex for further swapping. pIndex++; } } // Lastly swapping or the correct position of pivot swap(a[pIndex], a[end]); return pIndex; } // THIS PART OF CODE IS CONTRIBUTED BY - rjrachit // Picks up random pivot element between start and end int findRandomPivot(int arr[], int start, int end) { int n = end - start + 1; // Selecting the random pivot index int pivotInd = random() % n; swap(arr[end], arr[start + pivotInd]); int pivot = arr[end]; // initialising pivoting point to start index pivotInd = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { swap(arr[i], arr[pivotInd]); // Incrementing pivotIndex for further swapping. pivotInd++; } } // Lastly swapping or the correct position of pivot swap(arr[pivotInd], arr[end]); return pivotInd; } // THIS PART OF CODE IS CONTRIBUTED BY - rjrachit void SmallestLargest(int a[], int low, int high, int k, int n) { if (low == high) return; else { int pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { cout << k << "" smallest elements are : ""; for (int i = 0; i < pivotIndex; i++) cout << a[i] << "" ""; cout << endl; cout << k << "" largest elements are : ""; for (int i = (n - pivotIndex); i < n; i++) cout << a[i] << "" ""; } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); } } // Driver Code int main() { int a[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = sizeof(a) / sizeof(a[0]); int low = 0; int high = n - 1; // Lets assume k is 3 int k = 3; // Function Call SmallestLargest(a, low, high, k, n); return 0; } // This code is contributed by Sania Kumari Gupta",constant,nlogn "// C++ code for k largest/ smallest elements in an array #include using namespace std; // Function to find k largest array element void kLargest(vector& v, int N, int K) { // Implementation using // a Priority Queue priority_queue, greater >pq; for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue pq.push(v[i]); // If size of the priority // queue exceeds k if (pq.size() > K) { pq.pop(); } } // Print the k largest element while(!pq.empty()) { cout << pq.top() <<"" ""; pq.pop(); } cout<& v, int N, int K) { // Implementation using // a Priority Queue priority_queue pq; for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue pq.push(v[i]); // If size of the priority // queue exceeds k if (pq.size() > K) { pq.pop(); } } // Print the k smallest element while(!pq.empty()) { cout << pq.top() <<"" ""; pq.pop(); } } // driver program int main() { // Given array vector arr = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; // Size of array int n = arr.size(); int k = 3; cout< using namespace std; struct Node{ int data; struct Node *left; struct Node *right; }; class Tree{ public: Node *root = NULL; void addNode(int data){ Node *newNode = new Node(); newNode->data = data; if (!root){ root = newNode; } else{ Node *cur = root; while (cur){ if (cur->data > data){ if (cur->left){ cur = cur->left; } else{ cur->left = newNode; return; } } else{ if (cur->right){ cur = cur->right; } else{ cur->right = newNode; return; } } } } } void printGreatest(int &K, vector /, Node* node){ if (!node || K == 0) return; printGreatest(K, sol, node->right); if (K <= 0) return; sol.push_back(node->data); K--; printGreatest(K, sol, node->left); } }; class Solution{ public: vector kLargest(int arr[], int n, int k) { vector sol; Tree tree = Tree(); for (int i = 0; i < n; i++){ tree.addNode(arr[i]); } tree.printGreatest(k, sol, tree.root); return sol; } }; int main() { int n = 5, k = 2; int arr[] = {12, 5, 787, 1, 23}; Solution ob; auto ans = ob.kLargest(arr, n, k); cout << ""Top "" << k << "" Elements: ""; for (auto x : ans) { cout << x << "" ""; } cout << ""\n""; return 0; }",linear,nlogn "// C++ program to find maximum // in arr[] of size n #include using namespace std; int largest(int arr[], int n) { int i; // Initialize maximum element int max = arr[0]; // Traverse array elements // from second and compare // every element with current max for (i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } // Driver Code int main() { int arr[] = {10, 324, 45, 90, 9808}; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Largest in given array is "" << largest(arr, n); return 0; } // This Code is contributed // by Shivi_Aggarwal",constant,linear "// C++ program to find maximum // in arr[] of size n #include using namespace std; int largest(int arr[], int n, int i) { // last index // return the element if (i == n - 1) { return arr[i]; } // find the maximum from rest of the array int recMax = largest(arr, n, i + 1); // compare with i-th element and return return max(recMax, arr[i]); } // Driver Code int main() { int arr[] = { 10, 324, 45, 90, 9808 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Largest in given array is "" << largest(arr, n, 0); return 0; } // This Code is contributed by Rajdeep Mallick",linear,linear "// C++ program to find maximum in arr[] of size n #include using namespace std; // returns maximum in arr[] of size n int largest(int arr[], int n) { return *max_element(arr, arr+n); } int main() { int arr[] = {10, 324, 45, 90, 9808}; int n = sizeof(arr)/sizeof(arr[0]); cout << largest(arr, n); return 0; }",constant,linear "// C++ program for find the largest // three elements in an array #include using namespace std; // Function to print three largest elements void print3largest(int arr[], int arr_size) { int first, second, third; // There should be atleast three elements if (arr_size < 3) { cout << "" Invalid Input ""; return; } third = first = second = INT_MIN; for(int i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second && arr[i] != first) { third = second; second = arr[i]; } else if (arr[i] > third && arr[i] != second) third = arr[i]; } cout << ""Three largest elements are "" << first << "" "" << second << "" "" << third << endl; } // Driver code int main() { int arr[] = { 12, 13, 1, 10, 34, 11 }; int n = sizeof(arr) / sizeof(arr[0]); print3largest(arr, n); return 0; } // This code is contributed by Anjali_Chauhan",constant,linear "// C++ code to find largest three elements in an array #include using namespace std; void find3largest(int arr[], int n) { sort(arr, arr + n); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) int check = 0, count = 1; for (int i = 1; i <= n; i++) { if (count < 4) { if (check != arr[n - i]) { // to handle duplicate values cout << arr[n - i] << "" ""; check = arr[n - i]; count++; } } else break; } } // Driver code int main() { int arr[] = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; int n = sizeof(arr) / sizeof(arr[0]); find3largest(arr, n); } // This code is contributed by Aditya Kumar (adityakumar129)",constant,nlogn "#include using namespace std; int main() { vector V = { 11, 65, 193, 36, 209, 664, 32 }; partial_sort(V.begin(), V.begin() + 3, V.end(), greater()); cout << ""first = "" << V[0] << ""\n""; cout << ""second = "" << V[1] << ""\n""; cout << ""third = "" << V[2] << ""\n""; return 0; }",constant,nlogn "// Simple C++ program to find // all elements in array which // have at-least two greater // elements itself. #include using namespace std; void findElements(int arr[], int n) { // Pick elements one by one and // count greater elements. If // count is more than 2, print // that element. for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) cout << arr[i] << "" ""; } } // Driver code int main() { int arr[] = { 2, -6 ,3 , 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0; }",constant,quadratic "// Sorting based C++ program to // find all elements in array // which have atleast two greater // elements itself. #include using namespace std; void findElements(int arr[], int n) { sort(arr, arr + n); for (int i = 0; i < n - 2; i++) cout << arr[i] << "" ""; } // Driver Code int main() { int arr[] = { 2, -6 ,3 , 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0; }",constant,nlogn "// C++ program to find all elements // in array which have atleast two // greater elements itself. #include using namespace std; void findElements(int arr[], int n) { int first = INT_MIN, second = INT_MIN; for (int i = 0; i < n; i++) { /* If current element is smaller than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for (int i = 0; i < n; i++) if (arr[i] < second) cout << arr[i] << "" ""; } // Driver code int main() { int arr[] = { 2, -6, 3, 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0; }",constant,linear "// CPP program to find mean and median of // an array #include using namespace std; // Function for calculating mean double findMean(int a[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n; } // Function for calculating median double findMedian(int a[], int n) { // First we sort the array sort(a, a + n); // check for even case if (n % 2 != 0) return (double)a[n / 2]; return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; } // Driver code int main() { int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; int N = sizeof(a) / sizeof(a[0]); // Function call cout << ""Mean = "" << findMean(a, N) << endl; cout << ""Median = "" << findMedian(a, N) << endl; return 0; }",constant,nlogn "// C++ program to find med in // stream of running integers #include using namespace std; // function to calculate med of stream void printMedians(double arr[], int n) { // max heap to store the smaller half elements priority_queue s; // min heap to store the greater half elements priority_queue,greater > g; double med = arr[0]; s.push(arr[0]); cout << med << endl; // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for (int i=1; i < n; i++) { double x = arr[i]; // case1(left side heap has more elements) if (s.size() > g.size()) { if (x < med) { g.push(s.top()); s.pop(); s.push(x); } else g.push(x); med = (s.top() + g.top())/2.0; } // case2(both heaps are balanced) else if (s.size()==g.size()) { if (x < med) { s.push(x); med = (double)s.top(); } else { g.push(x); med = (double)g.top(); } } // case3(right side heap has more elements) else { if (x > med) { s.push(g.top()); g.pop(); g.push(x); } else s.push(x); med = (s.top() + g.top())/2.0; } cout << med << endl; } } // Driver program to test above functions int main() { // stream of integers double arr[] = {5, 15, 10, 20, 3}; int n = sizeof(arr)/sizeof(arr[0]); printMedians(arr, n); return 0; }",linear,nlogn "// CPP program to find minimum product of // k elements in an array #include using namespace std; int minProduct(int arr[], int n, int k) { priority_queue, greater > pq; for (int i = 0; i < n; i++) pq.push(arr[i]); int count = 0, ans = 1; // One by one extract items from max heap while (pq.empty() == false && count < k) { ans = ans * pq.top(); pq.pop(); count++; } return ans; } // Driver code int main() { int arr[] = { 198, 76, 544, 123, 154, 675 }; int k = 2; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Minimum product is "" << minProduct(arr, n, k); return 0; }",linear,nlogn "// A simple C++ program to find N maximum // combinations from two arrays, #include using namespace std; // function to display first N maximum sum // combinations void KMaxCombinations(int A[], int B[], int N, int K) { // max heap. priority_queue pq; // insert all the possible combinations // in max heap. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) pq.push(A[i] + B[j]); // pop first N elements from max heap // and display them. int count = 0; while (count < K) { cout << pq.top() << endl; pq.pop(); count++; } } // Driver Code. int main() { int A[] = { 4, 2, 5, 1 }; int B[] = { 8, 0, 5, 3 }; int N = sizeof(A) / sizeof(A[0]); int K = 3; // Function call KMaxCombinations(A, B, N, K); return 0; }",quadratic,quadratic "// An efficient C++ program to find top K elements // from two arrays. #include using namespace std; // Function prints k maximum possible combinations void KMaxCombinations(vector& A, vector& B, int K) { // sort both arrays A and B sort(A.begin(), A.end()); sort(B.begin(), B.end()); int N = A.size(); // Max heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices does not repeat inside max heap. set > my_set; // initialize the heap with the maximum sum // combination ie (A[N - 1] + B[N - 1]) // and also push indices (N - 1, N - 1) along // with sum. pq.push(make_pair(A[N - 1] + B[N - 1], make_pair(N - 1, N - 1))); my_set.insert(make_pair(N - 1, N - 1)); // iterate upto K for (int count = 0; count < K; count++) { // tuple format (sum, (i, j)). pair > temp = pq.top(); pq.pop(); cout << temp.first << endl; int i = temp.second.first; int j = temp.second.second; int sum = A[i - 1] + B[j]; // insert (A[i - 1] + B[j], (i - 1, j)) // into max heap. pair temp1 = make_pair(i - 1, j); // insert only if the pair (i - 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } // insert (A[i] + B[j - 1], (i, j - 1)) // into max heap. sum = A[i] + B[j - 1]; temp1 = make_pair(i, j - 1); // insert only if the pair (i, j - 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } } } // Driver Code. int main() { vector A = { 1, 4, 2, 3 }; vector B = { 2, 5, 1, 6 }; int K = 4; // Function call KMaxCombinations(A, B, K); return 0; }",linear,nlogn "// CPP for printing smallest k numbers in order #include #include using namespace std; // Function to print smallest k numbers // in arr[0..n-1] void printSmall(int arr[], int n, int k) { // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (int i = k; i < n; ++i) { // find largest from first k-elements int max_var = arr[k - 1]; int pos = k - 1; for (int j = k - 2; j >= 0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // if largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { int j = pos; while (j < k - 1) { arr[j] = arr[j + 1]; j++; } // make arr[k-1] = arr[i] arr[k - 1] = arr[i]; } } // print result for (int i = 0; i < k; i++) cout << arr[i] << "" ""; } // Driver program int main() { int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 5; printSmall(arr, n, k); return 0; }",constant,quadratic "// C++ program to prints first k pairs with least sum from two // arrays. #include using namespace std; // Function to find k pairs with least sum such // that one element of a pair is from arr1[] and // other element is from arr2[] void kSmallestPair(int arr1[], int n1, int arr2[], int n2, int k) { if (k > n1*n2) { cout << ""k pairs don't exist""; return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. int index2[n1]; memset(index2, 0, sizeof(index2)); while (k > 0) { // Initialize current pair sum as infinite int min_sum = INT_MAX; int min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } cout << ""("" << arr1[min_index] << "", "" << arr2[index2[min_index]] << "") ""; index2[min_index]++; k--; } } // Driver code int main() { int arr1[] = {1, 3, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); return 0; }",linear,linear "// C++ program to Prints // first k pairs with // least sum from two arrays. #include using namespace std; // Function to find k pairs // with least sum such // that one element of a pair // is from arr1[] and // other element is from arr2[] void kSmallestPair(vector A, vector B, int K) { int n = A.size(); // Min heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue >, vector > >, greater > > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices does not repeat inside min heap. set > my_set; // initialize the heap with the minimum sum // combination i.e. (A[0] + B[0]) // and also push indices (0,0) along // with sum. pq.push(make_pair(A[0] + B[0], make_pair(0, 0))); my_set.insert(make_pair(0, 0)); // iterate upto K int flag = 1; for (int count = 0; count < K && flag; count++) { // tuple format (sum, i, j). pair > temp = pq.top(); pq.pop(); int i = temp.second.first; int j = temp.second.second; cout << ""("" << A[i] << "", "" << B[j] << "")"" << endl; // Extracting pair with least sum such // that one element is from arr1 and // another is from arr2 // check if i+1 is in the range of our first array A flag = 0; if (i + 1 < A.size()) { int sum = A[i + 1] + B[j]; // insert (A[i + 1] + B[j], (i + 1, j)) // into min heap. pair temp1 = make_pair(i + 1, j); // insert only if the pair (i + 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag = 1; } // check if j+1 is in the range of our second array // B if (j + 1 < B.size()) { // insert (A[i] + B[j + 1], (i, j + 1)) // into min heap. int sum = A[i] + B[j + 1]; pair temp1 = make_pair(i, j + 1); // insert only if the pair (i, j + 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag = 1; } } } // Driver Code. int main() { vector A = { 1 }; vector B = { 2, 4, 5, 9 }; int K = 8; kSmallestPair(A, B, K); return 0; } // This code is contributed by Dhairya.",linear,nlogn "// C++ program to find k-th absolute difference // between two elements #include using namespace std; // returns number of pairs with absolute difference // less than or equal to mid. int countPairs(int *a, int n, int mid) { int res = 0; for (int i = 0; i < n; ++i) // Upper bound returns pointer to position // of next higher number than a[i]+mid in // a[i..n-1]. We subtract (a + i + 1) from // this position to count res += upper_bound(a+i, a+n, a[i] + mid) - (a + i + 1); return res; } // Returns k-th absolute difference int kthDiff(int a[], int n, int k) { // Sort array sort(a, a+n); // Minimum absolute difference int low = a[1] - a[0]; for (int i = 1; i <= n-2; ++i) low = min(low, a[i+1] - a[i]); // Maximum absolute difference int high = a[n-1] - a[0]; // Do binary search for k-th absolute difference while (low < high) { int mid = (low+high)>>1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low; } // Driver code int main() { int k = 3; int a[] = {1, 2, 3, 4}; int n = sizeof(a)/sizeof(a[0]); cout << kthDiff(a, n, k); return 0; }",constant,nlogn "// C++ program to find second largest element in an array #include using namespace std; /* Function to print the second largest elements */ void print2largest(int arr[], int arr_size) { int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { printf("" Invalid Input ""); return; } // sort the array sort(arr, arr + arr_size); // start from second last element as the largest element // is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not equal to largest element if (arr[i] != arr[arr_size - 1]) { printf(""The second largest element is %d\n"",arr[i]); return; } } printf(""There is no second largest element\n""); } /* Driver program to test above function */ int main() { int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print2largest(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,nlogn "// C++ program to find the second largest element in the array #include using namespace std; int secondLargest(int arr[], int n) { int largest = 0, secondLargest = -1; // finding the largest element in the array for (int i = 1; i < n; i++) { if (arr[i] > arr[largest]) largest = i; } // finding the largest element in the array excluding // the largest element calculated above for (int i = 0; i < n; i++) { if (arr[i] != arr[largest]) { // first change the value of second largest // as soon as the next element is found if (secondLargest == -1) secondLargest = i; else if (arr[i] > arr[secondLargest]) secondLargest = i; } } return secondLargest; } int main() { int arr[] = {10, 12, 20, 4}; int n = sizeof(arr)/sizeof(arr[0]); int second_Largest = secondLargest(arr, n); if (second_Largest == -1) cout << ""Second largest didn't exit\n""; else cout << ""Second largest : "" << arr[second_Largest]; }",constant,linear "// C++ program to find the second largest element #include using namespace std; // returns the index of second largest // if second largest didn't exist return -1 int secondLargest(int arr[], int n) { int first = 0, second = -1; for (int i = 1; i < n; i++) { if (arr[i] > arr[first]) { second = first; first = i; } else if (arr[i] < arr[first]) { if (second == -1 || arr[second] < arr[i]) second = i; } } return second; } int main() { int arr[] = {10, 12, 20, 4}; int index = secondLargest(arr, sizeof(arr)/sizeof(arr[0])); if (index == -1) cout << ""Second Largest didn't exist""; else cout << ""Second largest : "" << arr[index]; }",constant,linear "// C++ implementation to find k numbers with most // occurrences in the given array #include using namespace std; // Comparison function to sort the 'freq_arr[]' bool compare(pair p1, pair p2) { // If frequencies of two elements are same // then the larger number should come first if (p1.second == p2.second) return p1.first > p2.first; // Sort on the basis of decreasing order // of frequencies return p1.second > p2.second; } // Function to print the k numbers with most occurrences void print_N_mostFrequentNumber(int arr[], int N, int K) { // unordered_map 'mp' implemented as frequency hash // table unordered_map mp; for (int i = 0; i < N; i++) mp[arr[i]]++; // store the elements of 'mp' in the vector 'freq_arr' vector > freq_arr(mp.begin(), mp.end()); // Sort the vector 'freq_arr' on the basis of the // 'compare' function sort(freq_arr.begin(), freq_arr.end(), compare); // display the top k numbers cout << K << "" numbers with most occurrences are:\n""; for (int i = 0; i < K; i++) cout << freq_arr[i].first << "" ""; } // Driver's code int main() { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; // Function call print_N_mostFrequentNumber(arr, N, K); return 0; }",linear,nlogn "// C++ program to find k numbers with most // occurrences in the given array #include using namespace std; // Function to print the k numbers with most occurrences void print_N_mostFrequentNumber(int arr[], int N, int K) { // HashMap to store count of the elements unordered_map elementCount; for (int i = 0; i < N; i++) { elementCount[arr[i]]++; } // Array to store the elements according // to their frequency vector > frequency(N + 1); // Inserting elements in the frequency array for (auto element : elementCount) { frequency[element.second].push_back(element.first); } int count = 0; cout << K << "" numbers with most occurrences are:\n""; for (int i = frequency.size() - 1; i >= 0; i--) { for (auto element : frequency[i]) { count++; cout << element << "" ""; } // if K elements have been printed if (count == K) return; } return; } // Driver's code int main() { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; // Function call print_N_mostFrequentNumber(arr, N, K); return 0; }",linear,linear "//C++ simple approach to print smallest //and second smallest element. #include using namespace std; int main() { int arr[]={111, 13, 25, 9, 34, 1}; int n=sizeof(arr)/sizeof(arr[0]); //sorting the array using //in-built sort function sort(arr,arr+n); //printing the desired element cout<<""smallest element is ""< using namespace std; /* For INT_MAX */ void print2Smallest(int arr[], int arr_size) { int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { cout<<"" Invalid Input ""; return; } first = second = INT_MAX; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == INT_MAX) cout << ""There is no second smallest element\n""; else cout << ""The smallest element is "" << first << "" and second "" ""Smallest element is "" << second << endl; } /* Driver code */ int main() { int arr[] = {12, 13, 1, 10, 34, 1}; int n = sizeof(arr)/sizeof(arr[0]); print2Smallest(arr, n); return 0; } // This is code is contributed by rathbhupendra",constant,linear "// C++ program to find the smallest elements // missing in a sorted array. #include using namespace std; int findFirstMissing(int array[], int start, int end) { if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements // from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid); } // Driver code int main() { int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); cout << ""Smallest missing element is "" << findFirstMissing(arr, 0, n-1) << endl; } // This code is contributed by // Shivi_Aggarwal",logn,logn "//C++ program for the above approach #include using namespace std; // Program to find missing element int findFirstMissing(vector arr , int start , int end,int first) { if (start < end) { int mid = (start + end) / 2; /** Index matches with value at that index, means missing element cannot be upto that po*/ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid , first); else return findFirstMissing(arr, mid + 1, end , first); } return start + first; } // Program to find Smallest // Missing in Sorted Array int findSmallestMissinginSortedArray(vector arr) { // Check if 0 is missing // in the array if(arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if(arr[arr.size() - 1] == arr.size() - 1) return arr.size(); int first = arr[0]; return findFirstMissing(arr, 0, arr.size() - 1, first); } // Driver program to test the above function int main() { vector arr = {0, 1, 2, 3, 4, 5, 7}; int n = arr.size(); // Function Call cout<<""First Missing element is : ""< using namespace std; // Function to find the maximum sum int findMaxSum(vector arr, int N) { // Declare dp array int dp[N][2]; if (N == 1) { return arr[0]; } // Initialize the values in dp array dp[0][0] = 0; dp[0][1] = arr[0]; // Loop to find the maximum possible sum for (int i = 1; i < N; i++) { dp[i][1] = dp[i - 1][0] + arr[i]; dp[i][0] = max(dp[i - 1][1], dp[i - 1][0]); } // Return the maximum sum return max(dp[N - 1][0], dp[N - 1][1]); } // Driver Code int main() { // Creating the array vector arr = { 5, 5, 10, 100, 10, 5 }; int N = arr.size(); // Function call cout << findMaxSum(arr, N) << endl; return 0; }",linear,linear "// C++ code to implement the above approach #include using namespace std; // Function to return max sum such that // no two elements are adjacent int FindMaxSum(vector arr, int n) { int incl = arr[0]; int excl = 0; int excl_new; int i; for (i = 1; i < n; i++) { // Current max excluding i excl_new = max(incl, excl); // Current max including i incl = excl + arr[i]; excl = excl_new; } // Return max of incl and excl return max(incl, excl); } // Driver code int main() { vector arr = { 5, 5, 10, 100, 10, 5 }; int N = arr.size(); // Function call cout << FindMaxSum(arr, N); return 0; } // This approach is contributed by Debanjan",constant,linear "// C++ program to demonstrate working of Square Root // Decomposition. #include ""iostream"" #include ""math.h"" using namespace std; #define MAXN 10000 #define SQRSIZE 100 int arr[MAXN]; // original array int block[SQRSIZE]; // decomposed array int blk_sz; // block size // Time Complexity : O(1) void update(int idx, int val) { int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val; } // Time Complexity : O(sqrt(n)) int query(int l, int r) { int sum = 0; while (l using namespace std; #define MAX 500 // lookup[i][j] is going to store minimum // value in arr[i..j]. Ideally lookup table // size should not be fixed and should be // determined using n Log n. It is kept // constant to keep code simple. int lookup[MAX][MAX]; // Fills lookup array lookup[][] in bottom up manner. void buildSparseTable(int arr[], int n) { // Initialize M for the intervals with length 1 for (int i = 0; i < n; i++) lookup[i][0] = arr[i]; // Compute values from smaller to bigger intervals for (int j = 1; (1 << j) <= n; j++) { // Compute minimum value for all intervals with // size 2^j for (int i = 0; (i + (1 << j) - 1) < n; i++) { // For arr[2][10], we compare arr[lookup[0][7]] // and arr[lookup[3][10]] if (lookup[i][j - 1] < lookup[i + (1 << (j - 1))][j - 1]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1]; } } } // Returns minimum of arr[L..R] int query(int L, int R) { // Find highest power of 2 that is smaller // than or equal to count of elements in given // range. For [2, 10], j = 3 int j = (int)log2(R - L + 1); // Compute minimum of last 2^j elements with first // 2^j elements in range. // For [2, 10], we compare arr[lookup[0][3]] and // arr[lookup[3][3]], if (lookup[L][j] <= lookup[R - (1 << j) + 1][j]) return lookup[L][j]; else return lookup[R - (1 << j) + 1][j]; } // Driver program int main() { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = sizeof(a) / sizeof(a[0]); buildSparseTable(a, n); cout << query(0, 4) << endl; cout << query(4, 7) << endl; cout << query(7, 8) << endl; return 0; }",nlogn,nlogn "// C++ program to do range minimum query // using sparse table #include using namespace std; #define MAX 500 // lookup[i][j] is going to store GCD of // arr[i..j]. Ideally lookup table // size should not be fixed and should be // determined using n Log n. It is kept // constant to keep code simple. int table[MAX][MAX]; // it builds sparse table. void buildSparseTable(int arr[], int n) { // GCD of single element is element itself for (int i = 0; i < n; i++) table[i][0] = arr[i]; // Build sparse table for (int j = 1; j <= log2(n); j++) for (int i = 0; i <= n - (1 << j); i++) table[i][j] = __gcd(table[i][j - 1], table[i + (1 << (j - 1))][j - 1]); } // Returns GCD of arr[L..R] int query(int L, int R) { // Find highest power of 2 that is smaller // than or equal to count of elements in given // range.For [2, 10], j = 3 int j = (int)log2(R - L + 1); // Compute GCD of last 2^j elements with first // 2^j elements in range. // For [2, 10], we find GCD of arr[lookup[0][3]] and // arr[lookup[3][3]], return __gcd(table[L][j], table[R - (1 << j) + 1][j]); } // Driver program int main() { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = sizeof(a) / sizeof(a[0]); buildSparseTable(a, n); cout << query(0, 2) << endl; cout << query(1, 3) << endl; cout << query(4, 5) << endl; return 0; }",nlogn,nlogn "// C++ program to find total count of an element // in a range #include using namespace std; // Returns count of element in arr[left-1..right-1] int findFrequency(int arr[], int n, int left, int right, int element) { int count = 0; for (int i=left-1; i<=right; ++i) if (arr[i] == element) ++count; return count; } // Driver Code int main() { int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Print frequency of 2 from position 1 to 6 cout << ""Frequency of 2 from 1 to 6 = "" << findFrequency(arr, n, 1, 6, 2) << endl; // Print frequency of 8 from position 4 to 9 cout << ""Frequency of 8 from 4 to 9 = "" << findFrequency(arr, n, 4, 9, 8); return 0; }",constant,linear "// C++ program to get updated array after many array range // add operation #include using namespace std; // Utility method to add value val, to range [lo, hi] void add(int arr[], int N, int lo, int hi, int val) { arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val; } // Utility method to get actual array from operation array void updateArray(int arr[], int N) { // convert array into prefix sum array for (int i = 1; i < N; i++) arr[i] += arr[i - 1]; } // method to print final updated array void printArr(int arr[], int N) { updateArray(arr, N); for (int i = 0; i < N; i++) cout << arr[i] << "" ""; cout << endl; } // Driver code int main() { int N = 6; int arr[N] = {0}; // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); return 0; }",constant,linear "// C++ program for queries of GCD excluding // given range of elements. #include using namespace std; // Filling the prefix and suffix array void FillPrefixSuffix(int prefix[], int arr[], int suffix[], int n) { // Filling the prefix array following relation // prefix(i) = __gcd(prefix(i-1), arr(i)) prefix[0] = arr[0]; for (int i=1 ;i=0 ;i--) suffix[i] = __gcd(suffix[i+1], arr[i]); } // To calculate gcd of the numbers outside range int GCDoutsideRange(int l, int r, int prefix[], int suffix[], int n) { // If l=0, we need to tell GCD of numbers // from r+1 to n if (l==0) return suffix[r+1]; // If r=n-1 we need to return the gcd of // numbers from 1 to l if (r==n-1) return prefix[l-1]; return __gcd(prefix[l-1], suffix[r+1]); } // Driver function int main() { int arr[] = {2, 6, 9}; int n = sizeof(arr)/sizeof(arr[0]); int prefix[n], suffix[n]; FillPrefixSuffix(prefix, arr, suffix, n); int l = 0, r = 0; cout << GCDoutsideRange(l, r, prefix, suffix, n) << endl; l = 1 ; r = 1; cout << GCDoutsideRange(l, r, prefix, suffix, n) << endl; l = 1 ; r = 2; cout << GCDoutsideRange(l, r, prefix, suffix, n) << endl; return 0; }",linear,nlogn "// C++ implementation of finding number // represented by binary subarray #include using namespace std; // Fills pre[] void precompute(int arr[], int n, int pre[]) { memset(pre, 0, n * sizeof(int)); pre[n - 1] = arr[n - 1] * pow(2, 0); for (int i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i)); } // returns the number represented by a binary // subarray l to r int decimalOfSubarr(int arr[], int l, int r, int n, int pre[]) { // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r)); } // Driver Function int main() { int arr[] = { 1, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int pre[n]; precompute(arr, n, pre); cout << decimalOfSubarr(arr, 2, 4, n, pre) << endl; cout << decimalOfSubarr(arr, 4, 5, n, pre) << endl; return 0; }",linear,linear "// CPP program to perform range queries over range // queries. #include #define max 10000 using namespace std; // For prefix sum array void update(int arr[], int l) { arr[l] += arr[l - 1]; } // This function is used to apply square root // decomposition in the record array void record_func(int block_size, int block[], int record[], int l, int r, int value) { // traversing first block in range while (l < r && l % block_size != 0 && l != 0) { record[l] += value; l++; } // traversing completely overlapped blocks in range while (l + block_size <= r + 1) { block[l / block_size] += value; l += block_size; } // traversing last block in range while (l <= r) { record[l] += value; l++; } } // Function to print the resultant array void print(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Driver code int main() { int n = 5, m = 5; int arr[n], record[m]; int block_size = sqrt(m); int block[max]; int command[5][3] = { { 1, 1, 2 }, { 1, 4, 5 }, { 2, 1, 2 }, { 2, 1, 3 }, { 2, 3, 4 } }; memset(arr, 0, sizeof arr); memset(record, 0, sizeof record); memset(block, 0, sizeof block); for (int i = m - 1; i >= 0; i--) { // If query is of type 2 then function // call to record_func if (command[i][0] == 2) { int x = i / (block_size); record_func(block_size, block, record, command[i][1] - 1, command[i][2] - 1, (block[x] + record[i] + 1)); } // If query is of type 1 then simply add // 1 to the record array else record[i]++; } // Merging the value of the block in the record array for (int i = 0; i < m; i++) { int check = (i / block_size); record[i] += block[check]; } for (int i = 0; i < m; i++) { // If query is of type 1 then the array // elements are over-written by the record // array if (command[i][0] == 1) { arr[command[i][1] - 1] += record[i]; if ((command[i][2] - 1) < n - 1) arr[(command[i][2])] -= record[i]; } } // The prefix sum of the array for (int i = 1; i < n; i++) update(arr, i); // Printing the resultant array print(arr, n); return 0; }",linear,logn "// CPP program to count the number of indexes // in range L R such that Ai = Ai+1 #include using namespace std; // function that answers every query in O(r-l) int answer_query(int a[], int n, int l, int r) { // traverse from l to r and count // the required indexes int count = 0; for (int i = l; i < r; i++) if (a[i] == a[i + 1]) count += 1; return count; } // Driver Code int main() { int a[] = { 1, 2, 2, 2, 3, 3, 4, 4, 4 }; int n = sizeof(a) / sizeof(a[0]); // 1-st query int L, R; L = 1; R = 8; cout << answer_query(a, n, L, R) << endl; // 2nd query L = 0; R = 4; cout << answer_query(a, n, L, R) << endl; return 0; }",constant,constant "// CPP program to count the number of indexes // in range L R such that Ai=Ai+1 #include using namespace std; const int N = 1000; // array to store count of index from 0 to // i that obey condition int prefixans[N]; // precomputing prefixans[] array int countIndex(int a[], int n) { // traverse to compute the prefixans[] array for (int i = 0; i < n; i++) { if (a[i] == a[i + 1]) prefixans[i] = 1; if (i != 0) prefixans[i] += prefixans[i - 1]; } } // function that answers every query in O(1) int answer_query(int l, int r) { if (l == 0) return prefixans[r - 1]; else return prefixans[r - 1] - prefixans[l - 1]; } // Driver Code int main() { int a[] = { 1, 2, 2, 2, 3, 3, 4, 4, 4 }; int n = sizeof(a) / sizeof(a[0]); // pre-computation countIndex(a, n); int L, R; // 1-st query L = 1; R = 8; cout << answer_query(L, R) << endl; // 2nd query L = 0; R = 4; cout << answer_query(L, R) << endl; return 0; }",linear,linear "// C++ program to print largest contiguous array sum #include using namespace std; int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } // Driver Code int main() { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = sizeof(a) / sizeof(a[0]); // Function Call int max_sum = maxSubArraySum(a, n); cout << ""Maximum contiguous sum is "" << max_sum; return 0; }",constant,linear "// C++ program to print largest contiguous array sum #include #include using namespace std; void maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0, start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } cout << ""Maximum contiguous sum is "" << max_so_far << endl; cout << ""Starting index "" << start << endl << ""Ending index "" << end << endl; } /*Driver program to test maxSubArraySum*/ int main() { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = sizeof(a) / sizeof(a[0]); int max_sum = maxSubArraySum(a, n); return 0; }",constant,linear "// C++ program to find maximum // possible profit with at most // two transactions #include using namespace std; // Returns maximum profit with // two transactions on a given // list of stock prices, price[0..n-1] int maxProfit(int price[], int n) { // Create profit array and // initialize it as 0 int* profit = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; // we can get profit[i] by taking maximum of: // a) previous maximum, i.e., profit[i+1] // b) profit by buying at price[i] and selling at // max_price profit[i] = max(profit[i + 1], max_price - price[i]); } /* Get the maximum profit with two transactions allowed After this loop, profit[n-1] contains the result */ int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum price in price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., profit[i-1] // b) (Buy, Sell) at (min_price, price[i]) and add // profit of other trans. stored in profit[i] profit[i] = max(profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; delete[] profit; // To avoid memory leak return result; } // Driver code int main() { int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = sizeof(price) / sizeof(price[0]); cout << ""Maximum Profit = "" << maxProfit(price, n); return 0; }",linear,linear "#include #include using namespace std; int maxtwobuysell(int arr[],int size) { int first_buy = INT_MIN; int first_sell = 0; int second_buy = INT_MIN; int second_sell = 0; for(int i=0;i using namespace std; //function to find subarray void findsubarrayleast(int arr[],int k,int n){ int min=INT_MAX,minindex; for (int i = 0; i <= n-k; i++) { int sum=0; for (int j = i; j < i+k; j++) { sum+=arr[j]; } if(sum using namespace std; // Prints beginning and ending indexes of subarray // of size k with minimum average void findMinAvgSubarray(int arr[], int n, int k) { // k must be smaller than or equal to n if (n < k) return; // Initialize beginning index of result int res_index = 0; // Compute sum of first subarray of size k int curr_sum = 0; for (int i = 0; i < k; i++) curr_sum += arr[i]; // Initialize minimum sum as current sum int min_sum = curr_sum; // Traverse from (k+1)'th element to n'th element for (int i = k; i < n; i++) { // Add current item and remove first item of // previous subarray curr_sum += arr[i] - arr[i - k]; // Update result if needed if (curr_sum < min_sum) { min_sum = curr_sum; res_index = (i - k + 1); } } cout << ""Subarray between ["" << res_index << "", "" << res_index + k - 1 << ""] has minimum average""; } // Driver program int main() { int arr[] = { 3, 7, 90, 20, 10, 50, 40 }; int k = 3; // Subarray size int n = sizeof arr / sizeof arr[0]; findMinAvgSubarray(arr, n, k); return 0; }",constant,linear "// C++ program to Find the minimum // distance between two numbers #include using namespace std; int minDist(int arr[], int n, int x, int y) { int i, j; int min_dist = INT_MAX; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > abs(i - j)) { min_dist = abs(i - j); } } } if (min_dist > n) { return -1; } return min_dist; } /* Driver code */ int main() { int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << ""Minimum distance between "" << x << "" and "" << y << "" is "" << minDist(arr, n, x, y) << endl; } // This code is contributed by Shivi_Aggarwal",constant,quadratic "// C++ implementation of above approach #include using namespace std; int minDist(int arr[], int n, int x, int y) { //previous index and min distance int p = -1, min_dist = INT_MAX; for(int i=0 ; i using namespace std; int minDist(int arr[], int n, int x, int y) { //idx1 and idx2 will store indices of //x or y and min_dist will store the minimum difference int idx1=-1,idx2=-1,min_dist = INT_MAX; for(int i=0;i using namespace std; // User function Template int getMinDiff(int arr[], int n, int k) { sort(arr, arr + n); // Maximum possible height difference int ans = arr[n - 1] - arr[0]; int tempmin, tempmax; tempmin = arr[0]; tempmax = arr[n - 1]; for (int i = 1; i < n; i++) { // If on subtracting k we got // negative then continue if (arr[i] - k < 0) continue; // Minimum element when we // add k to whole array tempmin = min(arr[0] + k, arr[i] - k); // Maximum element when we // subtract k from whole array tempmax = max(arr[i - 1] + k, arr[n - 1] - k); ans = min(ans, tempmax - tempmin); } return ans; } // Driver Code Starts int main() { int k = 6, n = 6; int arr[n] = { 7, 4, 8, 8, 8, 9 }; // Function Call int ans = getMinDiff(arr, n, k); cout << ans; }",constant,nlogn "// C++ program to find Minimum // number of jumps to reach end #include using namespace std; // Function to return the minimum number // of jumps to reach arr[h] from arr[l] int minJumps(int arr[], int n) { // Base case: when source and // destination are same if (n == 1) return 0; // Traverse through all the points // reachable from arr[l] // Recursively, get the minimum number // of jumps needed to reach arr[h] from // these reachable points int res = INT_MAX; for (int i = n - 2; i >= 0; i--) { if (i + arr[i] >= n - 1) { int sub_res = minJumps(arr, i + 1); if (sub_res != INT_MAX) res = min(res, sub_res + 1); } } return res; } // Driver Code int main() { int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Minimum number of jumps to""; cout << "" reach the end is "" << minJumps(arr, n); return 0; } // This code is contributed // by Shivi_Aggarwal",linear,np "// C++ program for Minimum number // of jumps to reach end #include using namespace std; int min(int x, int y) { return (x < y) ? x : y; } // Returns minimum number of jumps // to reach arr[n-1] from arr[0] int minJumps(int arr[], int n) { // jumps[n-1] will hold the result int* jumps = new int[n]; int i, j; if (n == 0 || arr[0] == 0) return INT_MAX; jumps[0] = 0; // Find the minimum number of jumps to reach arr[i] // from arr[0], and assign this value to jumps[i] for (i = 1; i < n; i++) { jumps[i] = INT_MAX; for (j = 0; j < i; j++) { if (i <= j + arr[j] && jumps[j] != INT_MAX) { jumps[i] = min(jumps[i], jumps[j] + 1); break; } } } return jumps[n - 1]; } // Driver code int main() { int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 }; int size = sizeof(arr) / sizeof(int); cout << ""Minimum number of jumps to reach end is "" << minJumps(arr, size); return 0; } // This is code is contributed by rathbhupendra",linear,np "// C++ program to find Minimum number of jumps to reach end #include using namespace std; // Returns Minimum number of jumps to reach end int minJumps(int arr[], int n) { // jumps[0] will hold the result int* jumps = new int[n]; int min; // Minimum number of jumps needed to reach last element // from last elements itself is always 0 jumps[n - 1] = 0; // Start from the second element, move from right to // left and construct the jumps[] array where jumps[i] // represents minimum number of jumps needed to reach // arr[m-1] from arr[i] for (int i = n - 2; i >= 0; i--) { // If arr[i] is 0 then arr[n-1] can't be reached // from here if (arr[i] == 0) jumps[i] = INT_MAX; // If we can directly reach to the end point from // here then jumps[i] is 1 else if (arr[i] >= n - i - 1) jumps[i] = 1; // Otherwise, to find out the minimum number of // jumps needed to reach arr[n-1], check all the // points reachable from here and jumps[] value for // those points else { // initialize min value min = INT_MAX; // following loop checks with all reachable // points and takes the minimum for (int j = i + 1; j < n && j <= arr[i] + i; j++) { if (min > jumps[j]) min = jumps[j]; } // Handle overflow if (min != INT_MAX) jumps[i] = min + 1; else jumps[i] = min; // or INT_MAX } } return jumps[0]; } // Driver program to test above function int main() { int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 }; int size = sizeof(arr) / sizeof(int); cout << ""Minimum number of jumps to reach"" << "" end is "" << minJumps(arr, size); return 0; } // This code is contributed by Sania Kumari Gupta",linear,quadratic "/* Dynamic Programming implementation of Maximum Sum Increasing Subsequence (MSIS) problem */ #include using namespace std; /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */ int maxSumIS(int arr[], int n) { int i, j, max = 0; int msis[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max; } // Driver Code int main() { int arr[] = {1, 101, 2, 3, 100, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); cout << ""Sum of maximum sum increasing "" ""subsequence is "" << maxSumIS( arr, n ) << endl; return 0; } // This is code is contributed by rathbhupendra",linear,quadratic "# include using namespace std; // Returns length of smallest subarray with sum greater than x. // If there is no subarray with given sum, then returns n+1 int smallestSubWithSum(int arr[], int n, int x) { // Initialize length of smallest subarray as n+1 int min_len = n + 1; // Pick every element as starting point for (int start=0; start x) return 1; // Try different ending points for current start for (int end=start+1; end x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len; } /* Driver program to test above function */ int main() { int arr1[] = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = sizeof(arr1)/sizeof(arr1[0]); int res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1+1)? cout << ""Not possible\n"" : cout << res1 << endl; int arr2[] = {1, 10, 5, 2, 7}; int n2 = sizeof(arr2)/sizeof(arr2[0]); x = 9; int res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2+1)? cout << ""Not possible\n"" : cout << res2 << endl; int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = sizeof(arr3)/sizeof(arr3[0]); x = 280; int res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3+1)? cout << ""Not possible\n"" : cout << res3 << endl; return 0; }",constant,quadratic "// O(n) solution for finding smallest subarray with sum // greater than x #include using namespace std; // Returns length of smallest subarray with sum greater than // x. If there is no subarray with given sum, then returns // n+1 int smallestSubWithSum(int arr[], int n, int x) { // Initialize current sum and minimum length int curr_sum = 0, min_len = n + 1; // Initialize starting and ending indexes int start = 0, end = 0; while (end < n) { // Keep adding array elements while current sum // is smaller than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes greater than x. while (curr_sum > x && start < n) { // Update minimum length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len; } /* Driver program to test above function */ int main() { int arr1[] = { 1, 4, 45, 6, 10, 19 }; int x = 51; int n1 = sizeof(arr1) / sizeof(arr1[0]); int res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1 + 1) ? cout << ""Not possible\n"" : cout << res1 << endl; int arr2[] = { 1, 10, 5, 2, 7 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); x = 9; int res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2 + 1) ? cout << ""Not possible\n"" : cout << res2 << endl; int arr3[] = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; int n3 = sizeof(arr3) / sizeof(arr3[0]); x = 280; int res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3 + 1) ? cout << ""Not possible\n"" : cout << res3 << endl; return 0; }",constant,linear "// C++ program to find maximum average subarray // of given length. #include using namespace std; // Returns beginning index of maximum average // subarray of length 'k' int findMaxAverage(int arr[], int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Create and fill array to store cumulative // sum. csum[i] stores sum of arr[0] to arr[i] int *csum = new int[n]; csum[0] = arr[0]; for (int i=1; i max_sum) { max_sum = curr_sum; max_end = i; } } delete [] csum; // To avoid memory leak // Return starting index return max_end - k + 1; } // Driver program int main() { int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << ""The maximum average subarray of "" ""length ""<< k << "" begins at index "" << findMaxAverage(arr, n, k); return 0; }",linear,linear "// C++ program to find maximum average subarray // of given length. #include using namespace std; // Returns beginning index of maximum average // subarray of length 'k' int findMaxAverage(int arr[], int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' elements int sum = arr[0]; for (int i=1; i max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1; } // Driver program int main() { int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << ""The maximum average subarray of "" ""length ""<< k << "" begins at index "" << findMaxAverage(arr, n, k); return 0; }",constant,linear "/* C++ program to count minimum number of operations to get the given target array */ #include using namespace std; // Returns count of minimum operations to convert a // zero array to target array with increment and // doubling operations. // This function computes count by doing reverse // steps, i.e., convert target to zero array. int countMinOperations(unsigned int target[], int n) { // Initialize result (Count of minimum moves) int result = 0; // Keep looping while all elements of target // don't become 0. while (1) { // To store count of zeroes in current // target array int zero_count = 0; int i; // To find first odd element for (i=0; i using namespace std; // Returns minimum number of count operations // required to make arr[] palindrome int findMinOps(int arr[], int n) { int ans = 0; // Initialize result // Start from two corners for (int i=0,j=n-1; i<=j;) { // If corner elements are same, // problem reduces arr[i+1..j-1] if (arr[i] == arr[j]) { i++; j--; } // If left element is greater, then // we merge right two elements else if (arr[i] > arr[j]) { // need to merge from tail. j--; arr[j] += arr[j+1] ; ans++; } // Else we merge left two elements else { i++; arr[i] += arr[i-1]; ans++; } } return ans; } // Driver program to test above int main() { int arr[] = {1, 4, 5, 9, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << ""Count of minimum operations is "" << findMinOps(arr, n) << endl; return 0; }",constant,linear "// C++ program to find the smallest positive value that cannot be // represented as sum of subsets of a given sorted array #include #include #include using namespace std; // Returns the smallest number that cannot be represented as sum // of subset of elements from set represented by sorted array arr[0..n-1] long long smallestpositive(vector arr, int n) { long long int res = 1; // Initialize result sort(arr.begin(), arr.end()); // Traverse the array and increment 'res' if arr[i] is // smaller than or equal to 'res'. for (int i = 0; i < n && arr[i] <= res; i++) res = res + arr[i]; return res; } // Driver program to test above function int main() { vector arr1 = {1, 3, 4, 5}; cout << smallestpositive(arr1, arr1.size()) << endl; vector arr2 = {1, 2, 6, 10, 11, 15}; cout << smallestpositive(arr2, arr2.size()) << endl; vector arr3 = {1, 1, 1, 1}; cout << smallestpositive(arr3, arr3.size()) << endl; vector arr4 = {1, 1, 3, 4}; cout << smallestpositive(arr4, arr4.size()) << endl; return 0; }",constant,nlogn "// C++ program to print length of the largest // contiguous array sum #include using namespace std; int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0, start =0, end = 0, s=0; for (int i=0; i< size; i++ ) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1); } /*Driver program to test maxSubArraySum*/ int main() { int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); cout << maxSubArraySum(a, n); return 0; }",constant,linear "// C++ implementation of simple method to find // minimum difference between any pair #include using namespace std; // Returns minimum difference between any pair int findMinDiff(int arr[], int n) { // Initialize difference as infinite int diff = INT_MAX; // Find the min diff by comparing difference // of all possible pairs in given array for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (abs(arr[i] - arr[j]) < diff) diff = abs(arr[i] - arr[j]); // Return min diff return diff; } // Driver code int main() { int arr[] = { 1, 5, 3, 19, 18, 25 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""Minimum difference is "" << findMinDiff(arr, n); return 0; }",constant,quadratic "// C++ program to find minimum difference between // any pair in an unsorted array #include using namespace std; // Returns minimum difference between any pair int findMinDiff(int arr[], int n) { // Sort array in non-decreasing order sort(arr, arr + n); // Initialize difference as infinite int diff = INT_MAX; // Find the min diff by comparing adjacent // pairs in sorted array for (int i = 0; i < n - 1; i++) if (arr[i + 1] - arr[i] < diff) diff = arr[i + 1] - arr[i]; // Return min diff return diff; } // Driver code int main() { int arr[] = { 1, 5, 3, 19, 18, 25 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""Minimum difference is "" << findMinDiff(arr, n); return 0; }",constant,nlogn "// A Simple C++ program to find longest common // subarray of two binary arrays with same sum #include using namespace std; // Returns length of the longest common subarray // with same sum int longestCommonSum(bool arr1[], bool arr2[], int n) { // Initialize result int maxLen = 0; // One by one pick all possible starting points // of subarrays for (int i=0; i maxLen) maxLen = len; } } } return maxLen; } // Driver program to test above function int main() { bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << ""Length of the longest common span with same "" ""sum is ""<< longestCommonSum(arr1, arr2, n); return 0; }",constant,quadratic "// A O(n) and O(n) extra space C++ program to find // longest common subarray of two binary arrays with // same sum #include using namespace std; // Returns length of the longest common sum in arr1[] // and arr2[]. Both are of same size n. int longestCommonSum(bool arr1[], bool arr2[], int n) { // Initialize result int maxLen = 0; // Initialize prefix sums of two arrays int preSum1 = 0, preSum2 = 0; // Create an array to store starting and ending // indexes of all possible diff values. diff[i] // would store starting and ending points for // difference ""i-n"" int diff[2*n+1]; // Initialize all starting and ending values as -1. memset(diff, -1, sizeof(diff)); // Traverse both arrays for (int i=0; i maxLen) maxLen = len; } } return maxLen; } // Driver code int main() { bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << ""Length of the longest common span with same "" ""sum is ""<< longestCommonSum(arr1, arr2, n); return 0; }",linear,linear "// C++ program to find largest subarray // with equal number of 0's and 1's. #include using namespace std; // Returns largest common subarray with equal // number of 0s and 1s in both of t int longestCommonSum(bool arr1[], bool arr2[], int n) { // Find difference between the two int arr[n]; for (int i=0; i hM; int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.find(sum) != hM.end()) max_len = max(max_len, i - hM[sum]); else // Else put this sum in hash table hM[sum] = i; } return max_len; } // Driver program to test above function int main() { bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << longestCommonSum(arr1, arr2, n); return 0; }",linear,linear "// C++ program to print an array in alternate // sorted manner. #include using namespace std; // Function to print alternate sorted values void alternateSort(int arr[], int n) { // Sorting the array sort(arr, arr+n); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. int i = 0, j = n-1; while (i < j) { cout << arr[j--] << "" ""; cout << arr[i++] << "" ""; } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) cout << arr[i]; } // Driver code int main() { int arr[] = {1, 12, 4, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); alternateSort(arr, n); return 0; }",constant,nlogn "// A STL based C++ program to sort a nearly sorted array. #include using namespace std; // Given an array of size n, where every element // is k away from its target position, sorts the // array in O(n logk) time. void sortK(int arr[], int n, int k) { // Insert first k+1 items in a priority queue (or min // heap) //(A O(k) operation). We assume, k < n. //if size of array = k i.e k away from its target position //then int size; size=(n==k)?k:k+1; priority_queue, greater > pq(arr, arr +size); // i is index for remaining elements in arr[] and index // is target index of for current minimum element in // Min Heap 'pq'. int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = pq.top(); pq.pop(); pq.push(arr[i]); } while (pq.empty() == false) { arr[index++] = pq.top(); pq.pop(); } } // A utility function to print array elements void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << "" ""; cout << endl; } // Driver program to test above functions int main() { int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << ""Following is sorted array"" << endl; printArray(arr, n); return 0; }",constant,constant "#include #include using namespace std; int sort(vector& array, int l, int h, int k) { int mid = l + (h - l) / 2; //Choose middle element as pivot int i = max(l, mid - k), j = i, end = min(mid + k, h); // Set appropriate range swap(array[mid], array[end]); //Swap middle and last element to avoid extra complications while (j < end) { if (array[j] < array[end]) { swap(array[i++], array[j]); } j = j + 1; } swap(array[end], array[i]); return i; } void ksorter(vector& array, int l, int h, int k) { if (l < h) { int q = sort(array, l, h, k); ksorter(array, l, q - 1, k); ksorter(array, q + 1, h, k); } } int main() { vector array( { 3, 3, 2, 1, 6, 4, 4, 5, 9, 7, 8, 11, 12 }); int k = 3; cout << ""Array before k sort\n""; for (int& num : array) cout << num << ' '; cout << endl; ksorter(array, 0, array.size() - 1, k); cout << ""Array after k sort\n""; for (int& num : array) cout << num << ' '; return 0; }",logn,nlogn "// C++ program to sort an array according absolute // difference with x. #include using namespace std; // Function to sort an array according absolute // difference with x. void rearrange(int arr[], int n, int x) { multimap m; multimap::iterator it; // Store values in a map with the difference // with X as key for (int i = 0; i < n; i++) m.insert(make_pair(abs(x - arr[i]), arr[i])); // Update the values of array int i = 0; for (it = m.begin(); it != m.end(); it++) arr[i++] = (*it).second; } // Function to print the array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Driver code int main() { int arr[] = { 10, 5, 3, 9, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; // Function call rearrange(arr, n, x); printArray(arr, n); return 0; }",linear,nlogn "// CPP program for the above approach #include using namespace std; void rearrange(int arr[], int n, int x) { /* We can send the value x into lambda expression as follows: [capture]() { //statements //capture value can be used inside } */ stable_sort(arr, arr + n, [x](int a, int b) { if (abs(a - x) < abs(b - x)) return true; else return false; }); } // Driver code int main() { int arr[] = { 10, 5, 3, 9, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; // Function call rearrange(arr, n, x); for (int i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; }",constant,nlogn "// A C++ program to sort an array in wave form using // a sorting function #include #include using namespace std; // A utility method to swap two numbers. void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // This function sorts arr[0..n-1] in wave form, i.e., // arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5].. void sortInWave(int arr[], int n) { // Sort the input array sort(arr, arr+n); // Swap adjacent elements for (int i=0; i using namespace std; // A utility method to swap two numbers. void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // This function sorts arr[0..n-1] in wave form, i.e., arr[0] >= // arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5] .... void sortInWave(int arr[], int n) { // Traverse all even elements for (int i = 0; i < n; i+=2) { // If current even element is smaller than previous if (i>0 && arr[i-1] > arr[i] ) swap(&arr[i], &arr[i-1]); // If current even element is smaller than next if (i using namespace std; /* Assuming -1 is filled for the places where element is not available */ #define NA -1 /* Function to move m elements at the end of array mPlusN[] */ void moveToEnd(int mPlusN[], int size) { int j = size - 1; for (int i = size - 1; i >= 0; i--) if (mPlusN[i] != NA) { mPlusN[j] = mPlusN[i]; j--; } } /* Merges array N[] of size n into array mPlusN[] of size m+n*/ int merge(int mPlusN[], int N[], int m, int n) { int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((j == n)||(i < (m + n) && mPlusN[i] <= N[j])) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line */ void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << "" ""; cout << endl; } /* Driver code */ int main() { /* Initialize arrays */ int mPlusN[] = {2, 8, NA, NA, NA, 13, NA, 15, 20}; int N[] = {5, 7, 9, 25}; int n = sizeof(N) / sizeof(N[0]); int m = sizeof(mPlusN) / sizeof(mPlusN[0]) - n; /*Move the m elements at the end of mPlusN*/ moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ printArray(mPlusN, m+n); return 0; }",constant,linear "// CPP program to test whether array // can be sorted by swapping adjacent // elements using boolean array #include using namespace std; // Return true if array can be // sorted otherwise false bool sortedAfterSwap(int A[], bool B[], int n) { int i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) j++; // Sort array A from i to j sort(A + i, A + 1 + j); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) return false; } return true; } // Driver program to test sortedAfterSwap() int main() { int A[] = { 1, 2, 5, 3, 4, 6 }; bool B[] = { 0, 1, 1, 1, 0 }; int n = sizeof(A) / sizeof(A[0]); if (sortedAfterSwap(A, B, n)) cout << ""A can be sorted\n""; else cout << ""A can not be sorted\n""; return 0; }",constant,quadratic "// CPP program to test whether array // can be sorted by swapping adjacent // elements using boolean array #include using namespace std; // Return true if array can be // sorted otherwise false bool sortedAfterSwap(int A[], bool B[], int n) { for (int i = 0; i < n - 1; i++) { if (B[i]) { if (A[i] != i + 1) swap(A[i], A[i + 1]); } } // Check if array is sorted or not for (int i = 0; i < n; i++) { if (A[i] != i + 1) return false; } return true; } // Driver program to test sortedAfterSwap() int main() { int A[] = { 1, 2, 5, 3, 4, 6 }; bool B[] = { 0, 1, 1, 1, 0 }; int n = sizeof(A) / sizeof(A[0]); if (sortedAfterSwap(A, B, n)) cout << ""A can be sorted\n""; else cout << ""A can not be sorted\n""; return 0; }",constant,linear "// CPP program to sort an array with two types // of values in one traversal. #include using namespace std; /* Method for segregation 0 and 1 given input array */ void segregate0and1(int arr[], int n) { int type0 = 0; int type1 = n - 1; while (type0 < type1) { if (arr[type0] == 1) { swap(arr[type0], arr[type1]); type1--; } else { type0++; } } } // Driver program int main() { int arr[] = { 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1 }; int n = sizeof(arr)/sizeof(arr[0]); segregate0and1(arr, n); for (int a : arr) cout << a << "" ""; }",constant,linear "// C++ program for the above approach #include using namespace std; // Used for sorting struct ele { int count, index, val; }; // Used for sorting by value bool mycomp(struct ele a, struct ele b) { return (a.val < b.val); } // Used for sorting by frequency. And if frequency is same, // then by appearance bool mycomp2(struct ele a, struct ele b) { if (a.count != b.count) return (a.count < b.count); else return a.index > b.index; } void sortByFrequency(int arr[], int n) { struct ele element[n]; for (int i = 0; i < n; i++) { // Fill Indexes element[i].index = i; // Initialize counts as 0 element[i].count = 0; // Fill values in structure // elements element[i].val = arr[i]; } /* Sort the structure elements according to value, we used stable sort so relative order is maintained. */ stable_sort(element, element + n, mycomp); /* initialize count of first element as 1 */ element[0].count = 1; /* Count occurrences of remaining elements */ for (int i = 1; i < n; i++) { if (element[i].val == element[i - 1].val) { element[i].count += element[i - 1].count + 1; /* Set count of previous element as -1, we are doing this because we'll again sort on the basis of counts (if counts are equal than on the basis of index)*/ element[i - 1].count = -1; /* Retain the first index (Remember first index is always present in the first duplicate we used stable sort. */ element[i].index = element[i - 1].index; } /* Else If previous element is not equal to current so set the count to 1 */ else element[i].count = 1; } /* Now we have counts and first index for each element so now sort on the basis of count and in case of tie use index to sort.*/ stable_sort(element, element + n, mycomp2); for (int i = n - 1, index = 0; i >= 0; i--) if (element[i].count != -1) for (int j = 0; j < element[i].count; j++) arr[index++] = element[i].val; } // Driver code int main() { int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call sortByFrequency(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; }",linear,nlogn "// CPP program for above approach #include using namespace std; // Compare function bool fcompare(pair > p, pair > p1) { if (p.second.second != p1.second.second) return (p.second.second > p1.second.second); else return (p.second.first < p1.second.first); } void sortByFrequency(int arr[], int n) { unordered_map > hash; // hash map for (int i = 0; i < n; i++) { if (hash.find(arr[i]) != hash.end()) hash[arr[i]].second++; else hash[arr[i]] = make_pair(i, 1); } // store the count of all the elements in the hashmap // Iterator to Traverse the Hashmap auto it = hash.begin(); // Vector to store the Final Sortted order vector > > b; for (it; it != hash.end(); ++it) b.push_back(make_pair(it->first, it->second)); sort(b.begin(), b.end(), fcompare); // Printing the Sorted sequence for (int i = 0; i < b.size(); i++) { int count = b[i].second.second; while (count--) cout << b[i].first << "" ""; } } // Driver code int main() { int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call sortByFrequency(arr, n); return 0; }",linear,nlogn "// CPP program to find shortest subarray which is // unsorted. #include using namespace std; // bool function for checking an array elements // are in increasing. bool increasing(int a[], int n) { for (int i = 0; i < n - 1; i++) if (a[i] >= a[i + 1]) return false; return true; } // bool function for checking an array // elements are in decreasing. bool decreasing(int a[], int n) { for (int i = 0; i < n - 1; i++) if (a[i] < a[i + 1]) return false; return true; } int shortestUnsorted(int a[], int n) { // increasing and decreasing are two functions. // if function return true value then print // 0 otherwise 3. if (increasing(a, n) == true || decreasing(a, n) == true) return 0; else return 3; } // Driver code int main() { int ar[] = { 7, 9, 10, 8, 11 }; int n = sizeof(ar) / sizeof(ar[0]); cout << shortestUnsorted(ar, n); return 0; }",constant,linear "// C++ program to find // minimum number of swaps // required to sort an array #include using namespace std; // Function returns the // minimum number of swaps // required to sort the array int minSwaps(int arr[], int n) { // Create an array of // pairs where first // element is array element // and second element // is position of first element pair arrPos[n]; for (int i = 0; i < n; i++) { arrPos[i].first = arr[i]; arrPos[i].second = i; } // Sort the array by array // element values to // get right position of // every element as second // element of pair. sort(arrPos, arrPos + n); // To keep track of visited elements. // Initialize // all elements as not visited or false. vector vis(n, false); // Initialize result int ans = 0; // Traverse array elements for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrPos[i].second == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = 1; // move to next node j = arrPos[j].second; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans; } // Driver program to test the above function int main() { int arr[] = {1, 5, 4, 3, 2}; int n = (sizeof(arr) / sizeof(int)); cout << minSwaps(arr, n); return 0; }",linear,nlogn "#include using namespace std; // Function returns the // minimum number of swaps // required to sort the array int minSwaps(int nums[], int n) { int len = n; map map; for (int i = 0; i < len; i++) map[nums[i]] = i; sort(nums, nums + n); // To keep track of visited elements. Initialize // all elements as not visited or false. bool visited[len] = { 0 }; // Initialize result int ans = 0; for (int i = 0; i < len; i++) { // already swapped and corrected or // already present at correct pos if (visited[i] || map[nums[i]] == i) continue; int j = i, cycle_size = 0; while (!visited[j]) { visited[j] = true; // move to next node j = map[nums[j]]; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } return ans; } int main() { // Driver program to test the above function int a[] = { 1, 5, 4, 3, 2 }; int n = 5; cout << minSwaps(a, n); return 0; } // This code is contributed by Harshal Khond",linear,nlogn "// C++ program to find minimum number // of swaps required to sort an array #include using namespace std; void swap(vector &arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int indexOf(vector &arr, int ele) { for(int i = 0; i < arr.size(); i++) { if (arr[i] == ele) { return i; } } return -1; } // Return the minimum number // of swaps required to sort the array int minSwaps(vector arr, int N) { int ans = 0; vector temp(arr.begin(),arr.end()); sort(temp.begin(),temp.end()); for(int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans; } // Driver Code int main() { vector a = {101, 758, 315, 730, 472, 619, 460, 479}; int n = a.size(); // Output will be 5 cout << minSwaps(a, n); } // This code is contributed by mohit kumar 29",linear,quadratic "// C++ program to find // minimum number of swaps // required to sort an array #include using namespace std; void swap(vector &arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Return the minimum number // of swaps required to sort // the array int minSwaps(vectorarr, int N) { int ans = 0; vectortemp = arr; // Hashmap which stores the // indexes of the input array map h; sort(temp.begin(), temp.end()); for (int i = 0; i < N; i++) { h[arr[i]] = i; } for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; int init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h[temp[i]]); // Update the indexes in // the hashmap accordingly h[init] = h[temp[i]]; h[temp[i]] = i; } } return ans; } // Driver class int main() { // Driver program to // test the above function vector a = {101, 758, 315, 730, 472, 619, 460, 479}; int n = a.size(); // Output will be 5 cout << minSwaps(a, n); } // This code is contributed by Stream_Cipher",linear,nlogn "// C++ program to sort an array // with 0, 1 and 2 in a single pass #include using namespace std; // Function to sort the input array, // the array is assumed // to have values in {0, 1, 2} void sort012(int a[], int arr_size) { int lo = 0; int hi = arr_size - 1; int mid = 0; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } } } // Function to print array arr[] void printArray(int arr[], int arr_size) { // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << "" ""; } // Driver Code int main() { int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); printArray(arr, n); return 0; } // This code is contributed by Shivi_Aggarwal",constant,linear "// C++ implementation of the approach #include using namespace std; // Utility function to print the contents of an array void printArr(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Function to sort the array of 0s, 1s and 2s void sortArr(int arr[], int n) { int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n); } // Driver code int main() { int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0; }",constant,linear "// This code is contributed by Anjali Saxena #include using namespace std; // Function to find position to insert current element of // stream using binary search int binarySearch(int arr[], int item, int low, int high) { if (low >= high) { return (item > arr[low]) ? (low + 1) : low; } int mid = (low + high) / 2; if (item == arr[mid]) return mid + 1; if (item > arr[mid]) return binarySearch(arr, item, mid + 1, high); return binarySearch(arr, item, low, mid - 1); } // Function to print median of stream of integers void printMedian(int arr[], int n) { int i, j, pos, num; int count = 1; cout << ""Median after reading 1"" << "" element is "" << arr[0] << ""\n""; for (i = 1; i < n; i++) { float median; j = i - 1; num = arr[i]; // find position to insert current element in sorted // part of array pos = binarySearch(arr, num, 0, j); // move elements to right to create space to insert // the current element while (j >= pos) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = num; // increment count of sorted elements in array count++; // if odd number of integers are read from stream // then middle element in sorted order is median // else average of middle elements is median if (count % 2 != 0) { median = arr[count / 2]; } else { median = (arr[(count / 2) - 1] + arr[count / 2]) / 2; } cout << ""Median after reading "" << i + 1 << "" elements is "" << median << ""\n""; } } // Driver Code int main() { int arr[] = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 }; int n = sizeof(arr) / sizeof(arr[0]); printMedian(arr, n); return 0; }",constant,quadratic "// C++ code to implement the approach #include using namespace std; // Function to find the median of stream of data void streamMed(int A[], int n) { // Declared two max heap priority_queue g, s; for (int i = 0; i < n; i++) { s.push(A[i]); int temp = s.top(); s.pop(); // Negation for treating it as min heap g.push(-1 * temp); if (g.size() > s.size()) { temp = g.top(); g.pop(); s.push(-1 * temp); } if (g.size() != s.size()) cout << (double)s.top() << ""\n""; else cout << (double)((s.top() * 1.0 - g.top() * 1.0) / 2) << ""\n""; } } // Driver code int main() { int A[] = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 }; int N = sizeof(A) / sizeof(A[0]); // Function call streamMed(A, N); return 0; }",linear,nlogn "// C++ code to count the number of possible triangles using // brute force approach #include using namespace std; // Function to count all possible triangles with arr[] // elements int findNumberOfTriangles(int arr[], int n) { // Count of triangles int count = 0; // The three loops select three different values from // array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // The innermost loop checks for the triangle // property for (int k = j + 1; k < n; k++) // Sum of two sides is greater than the // third if (arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count; } // Driver code int main() { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""Total number of triangles possible is "" << findNumberOfTriangles(arr, size); return 0; } // This code is contributed by Sania Kumari Gupta",constant,cubic "// C++ program to count number of triangles that can be // formed from given array #include using namespace std; // Function to count all possible triangles with arr[] // elements int findNumberOfTriangles(int arr[], int n) { // Sort the array elements in non-decreasing order sort(arr, arr + n); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 // as the other two elements are selected from // arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { // Find the rightmost element which is smaller // than the sum of two fixed elements The // important thing to note here is, we use the // previous value of k. If value of arr[i] + // arr[j-1] was greater than arr[k], then arr[i] // + arr[j] must be greater than k, because the // array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and // arr[j]. One is subtracted from k because k is // incremented one extra in above while loop. k // will always be greater than j. If j becomes // equal to k, then above loop will increment k, // because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count; } // Driver code int main() { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""Total number of triangles possible is "" << findNumberOfTriangles(arr, size); return 0; } // This code is contributed by Sania Kumari Gupta",constant,quadratic "// C++ implementation of the above approach #include using namespace std; void CountTriangles(vector A) { int n = A.size(); sort(A.begin(), A.end()); int count = 0; for (int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] l++; } } cout << ""No of possible solutions: "" << count; } // Driver code int main() { vector A = { 10, 21, 22, 100, 101, 200, 300 }; // Function call CountTriangles(A); }",constant,quadratic "// C++ program to finds the number of pairs (x, y) // in an array such that x^y > y^x #include using namespace std; // Function to return count of pairs with x as one element // of the pair. It mainly looks for all values in Y[] where // x ^ Y[i] > Y[i] ^ x int count(int x, int Y[], int n, int NoOfY[]) { // If x is 0, then there cannot be any value in Y such // that x^Y[i] > Y[i]^x if (x == 0) return 0; // If x is 1, then the number of pairs is equal to number // of zeroes in Y[] if (x == 1) return NoOfY[0]; // Find number of elements in Y[] with values greater // than x upper_bound() gets address of first greater // element in Y[0..n-1] int* idx = upper_bound(Y, Y + n, x); int ans = (Y + n) - idx; // If we have reached here, then x must be greater than // 1, increase number of pairs for y=0 and y=1 ans += (NoOfY[0] + NoOfY[1]); // Decrease number of pairs for x=2 and (y=4 or y=3) if (x == 2) ans -= (NoOfY[3] + NoOfY[4]); // Increase number of pairs for x=3 and y=2 if (x == 3) ans += NoOfY[2]; return ans; } // Function to return count of pairs (x, y) such that // x belongs to X[], y belongs to Y[] and x^y > y^x int countPairs(int X[], int Y[], int m, int n) { // To store counts of 0, 1, 2, 3 and 4 in array Y int NoOfY[5] = { 0 }; for (int i = 0; i < n; i++) if (Y[i] < 5) NoOfY[Y[i]]++; // Sort Y[] so that we can do binary search in it sort(Y, Y + n); int total_pairs = 0; // Initialize result // Take every element of X and count pairs with it for (int i = 0; i < m; i++) total_pairs += count(X[i], Y, n, NoOfY); return total_pairs; } // Driver program int main() { int X[] = { 2, 1, 6 }; int Y[] = { 1, 5 }; int m = sizeof(X) / sizeof(X[0]); int n = sizeof(Y) / sizeof(Y[0]); cout << ""Total pairs = "" << countPairs(X, Y, m, n); return 0; }",constant,nlogn "/* A simple program to count pairs with difference k*/ #include using namespace std; int countPairsWithDiffK(int arr[], int n, int k) { int count = 0; // Pick all elements one by one for (int i = 0; i < n; i++) { // See if there is a pair of this picked element for (int j = i + 1; j < n; j++) if (arr[i] - arr[j] == k || arr[j] - arr[i] == k) count++; } return count; } // Driver program to test above function int main() { int arr[] = { 1, 5, 3, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << ""Count of pairs with given diff is "" << countPairsWithDiffK(arr, n, k); return 0; } // This code is contributed by Sania Kumari Gupta",constant,quadratic "/* A sorting based program to count pairs with difference k*/ #include #include using namespace std; /* Returns count of pairs with difference k in arr[] of size n. */ int countPairsWithDiffK(int arr[], int n, int k) { int count = 0; sort(arr, arr+n); // Sort array elements int l = 0; int r = 0; while(r < n) { if(arr[r] - arr[l] == k) { count++; l++; r++; } else if(arr[r] - arr[l] > k) l++; else // arr[r] - arr[l] < sum r++; } return count; } // Driver program to test above function int main() { int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << ""Count of pairs with given diff is "" << countPairsWithDiffK(arr, n, k); return 0; }",constant,nlogn "#include using namespace std; int BS(int arr[], int X, int low, int N) { int high = N - 1; int ans = N; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] >= X) { ans = mid; high = mid - 1; } else low = mid + 1; } return ans; } int countPairsWithDiffK(int arr[], int N, int k) { int count = 0; sort(arr, arr + N); for (int i = 0; i < N; ++i) { int X = BS(arr, arr[i] + k, i + 1, N); if (X != N) { int Y = BS(arr, arr[i] + k + 1, i + 1, N); count += Y - X; } } return count; } int main() { int arr[] = { 1, 3, 5, 8, 6, 4, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << ""Count of pairs with given diff is "" << countPairsWithDiffK(arr, n, k); return 0; } // This code is contributed by umadevi9616",constant,nlogn "// C++ program to print all distinct elements in a given array #include using namespace std; void printDistinct(int arr[], int n) { // Pick all elements one by one for (int i=0; i using namespace std; void printDistinct(int arr[], int n) { // First sort the array so that all occurrences become consecutive sort(arr, arr + n); // Traverse the sorted array for (int i=0; i using namespace std; // This function prints all distinct elements void printDistinct(int arr[],int n) { // Creates an empty hashset unordered_set s; // Traverse the input array for (int i=0; i using namespace std; int main() { int ar[] = { 10, 5, 3, 4, 3, 5, 6 }; map hm; for (int i = 0; i < sizeof(ar)/sizeof(ar[0]); i++) { // total = O(n*logn) hm.insert({ar[i], i}); // time complexity for insert() in map O(logn) } cout <<""[""; for (auto const &pair: hm) { cout << pair.first << "", ""; } cout <<""]""; } // This code is contributed by Shubham Singh",linear,nlogn "// C++ program to merge two sorted arrays with O(1) extra // space. #include using namespace std; // Merge ar1[] and ar2[] with O(1) extra space void merge(int ar1[], int ar2[], int m, int n) { // Iterate through all elements // of ar2[] starting from the last element for (int i = n - 1; i >= 0; i--) { // Find the smallest element greater than ar2[i]. // Move all elements one position ahead till the // smallest greater element is not found */ int j, last = ar1[m - 1]; for (j = m - 2; j >= 0 && ar1[j] > ar2[i]; j--) ar1[j + 1] = ar1[j]; // If there was a greater element if (last > ar2[i]) { ar1[j + 1] = ar2[i]; ar2[i] = last; } } } // Driver program int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << ""After Merging \nFirst Array: ""; for (int i = 0; i < m; i++) cout << ar1[i] << "" ""; cout << ""\nSecond Array: ""; for (int i = 0; i < n; i++) cout << ar2[i] << "" ""; return 0; }",constant,quadratic "#include #include using namespace std; void merge(int arr1[], int arr2[], int n, int m) { int i=0; // while loop till last element of array 1(sorted) is greater than // first element of array 2(sorted) while(arr1[n-1]>arr2[0]) { if(arr1[i]>arr2[0]) { // swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) swap(arr1[i],arr2[0]); sort(arr2,arr2+m); } i++; } } int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << ""After Merging \nFirst Array: ""; for (int i = 0; i < m; i++) cout << ar1[i] << "" ""; cout << ""\nSecond Array: ""; for (int i = 0; i < n; i++) cout << ar2[i] << "" ""; return 0; }",constant,linear "#include using namespace std; void swap(int& a, int& b) { int temp = a; a = b; b = temp; } void rotate(int a[], int n, int idx) { int i; for (i = 0; i < idx / 2; i++) swap(a[i], a[idx - 1 - i]); for (i = idx; i < (n + idx) / 2; i++) swap(a[i], a[n - 1 - (i - idx)]); for (i = 0; i < n / 2; i++) swap(a[i], a[n - 1 - i]); } void sol(int a1[], int a2[], int n, int m) { int l = 0, h = n - 1, idx = 0; //--------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray int c1 = (l + h) / 2; // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array int c2 = n - c1 - 1; int l1 = a1[c1]; int l2 = a2[c2 - 1]; int r1 = c1 == n - 1 ? INT_MAX : a1[c1 + 1]; int r2 = c2 == m ? INT_MAX : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (int i = idx; i < n; i++) swap(a1[i], a2[i - idx]); sort(a1, a1 + n); sort(a2, a2 + m); } void merge(int arr1[], int arr2[], int n, int m) { // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (int i = 0; i < m; i++) swap(arr2[i], arr1[i]); } else { sol(arr1, arr2, n, m); } } int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << ""After Merging \nFirst Array: ""; for (int i = 0; i < m; i++) cout << ar1[i] << "" ""; cout << ""\nSecond Array: ""; for (int i = 0; i < n; i++) cout << ar2[i] << "" ""; return 0; }",constant,nlogn "#include using namespace std; void merge(int arr1[], int arr2[], int n, int m) { // two pointer to iterate int i = 0; int j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1[] become sorted then we check that // arr2[j] is smaller than all other element in // right side of arr2[j] if arr2[] is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left swap(arr1[i], arr2[j]); i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { int temp = arr2[j]; int tempj = j + 1; while (arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } } } int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << ""After Merging \nFirst Array: ""; for (int i = 0; i < m; i++) cout << ar1[i] << "" ""; cout << ""\nSecond Array: ""; for (int i = 0; i < n; i++) cout << ar2[i] << "" ""; return 0; }",constant,quadratic "// C++ program to merge two sorted arrays without using extra space #include using namespace std; void merge(int arr1[], int arr2[], int n, int m) { // three pointers to iterate int i = 0, j = 0, k = 0; // for euclid's division lemma int x = 10e7 + 1; // in this loop we are rearranging the elements of arr1 while (i < n && (j < n && k < m)) { // if both arr1 and arr2 elements are modified if (arr1[j] >= x && arr2[k] >= x) { if (arr1[j] % x <= arr2[k] % x) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if only arr1 elements are modified else if (arr1[j] >= x) { if (arr1[j] % x <= arr2[k]) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if only arr2 elements are modified else if (arr2[k] >= x) { if (arr1[j] <= arr2[k] % x) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if none elements are modified else { if (arr1[j] <= arr2[k]) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } i++; } // we can copy the elements directly as the other array // is exchausted while (j < n && i < n) { arr1[i++] += (arr1[j++] % x) * x; } while (k < m && i < n) { arr1[i++] += (arr2[k++] % x) * x; } // we need to reset i i = 0; // in this loop we are rearranging the elements of arr2 while (i < m && (j < n && k < m)) { // if both arr1 and arr2 elements are modified if (arr1[j] >= x && arr2[k] >= x) { if (arr1[j] % x <= arr2[k] % x) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } // if only arr1 elements are modified else if (arr1[j] >= x) { if (arr1[j] % x <= arr2[k]) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } // if only arr2 elements are modified else if (arr2[k] >= x) { if (arr1[j] <= arr2[k] % x) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } else { // if none elements are modified if (arr1[j] <= arr2[k]) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } i++; } // we can copy the elements directly as the other array // is exhausted while (j < n && i < m) { arr2[i++] += (arr1[j++] % x) * x; } while (k < m && i < m) { arr2[i++] += (arr2[k++] % x) * x; } // we need to reset i i = 0; // we need to divide the whole arr1 by x while (i < n) { arr1[i++] /= x; } // we need to reset i i = 0; // we need to divide the whole arr2 by x while (i < m) { arr2[i++] /= x; } } int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << ""After Merging \nFirst Array: ""; for (int i = 0; i < m; i++) cout << ar1[i] << "" ""; cout << ""\nSecond Array: ""; for (int i = 0; i < n; i++) cout << ar2[i] << "" ""; return 0; } // This code is contributed by @ancientmoon8 (Mayank Kashyap)",constant,linear "// C++ program to calculate the // product of max element of // first array and min element // of second array #include using namespace std; // Function to calculate // the product int minMaxProduct(int arr1[], int arr2[], int n1, int n2) { // Sort the arrays to find // the maximum and minimum // elements in given arrays sort(arr1, arr1 + n1); sort(arr2, arr2 + n2); // Return product of // maximum and minimum. return arr1[n1 - 1] * arr2[0]; } // Driven code int main() { int arr1[] = { 10, 2, 3, 6, 4, 1 }; int arr2[] = { 5, 1, 4, 2, 6, 9 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr1) / sizeof(arr1[0]); cout << minMaxProduct(arr1, arr2, n1, n2); return 0; }",constant,nlogn "// C++ program to find the to // calculate the product of // max element of first array // and min element of second array #include using namespace std; // Function to calculate the product int minMaxProduct(int arr1[], int arr2[], int n1, int n2) { // Initialize max of first array int max = arr1[0]; // initialize min of second array int min = arr2[0]; int i; for (i = 1; i < n1 && i < n2; ++i) { // To find the maximum // element in first array if (arr1[i] > max) max = arr1[i]; // To find the minimum // element in second array if (arr2[i] < min) min = arr2[i]; } // Process remaining elements while (i < n1) { if (arr1[i] > max) max = arr1[i]; i++; } while (i < n2) { if (arr2[i] < min) min = arr2[i]; i++; } return max * min; } // Driven code int main() { int arr1[] = { 10, 2, 3, 6, 4, 1 }; int arr2[] = { 5, 1, 4, 2, 6, 9 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr1) / sizeof(arr1[0]); cout << minMaxProduct(arr1, arr2, n1, n2) << endl; return 0; }",constant,linear "// C++ program to implement linear // search in unsorted array #include using namespace std; // Function to implement search operation int findElement(int arr[], int n, int key) { int i; for (i = 0; i < n; i++) if (arr[i] == key) return i; // If the key is not found return -1; } // Driver's Code int main() { int arr[] = { 12, 34, 10, 6, 40 }; int n = sizeof(arr) / sizeof(arr[0]); // Using a last element as search element int key = 40; // Function call int position = findElement(arr, n, key); if (position == -1) cout << ""Element not found""; else cout << ""Element Found at Position: "" << position + 1; return 0; } // This code is contributed // by Akanksha Rai",constant,linear "// C++ program to implement insert // operation in an unsorted array. #include using namespace std; // Inserts a key in arr[] of given capacity. // n is current size of arr[]. This // function returns n + 1 if insertion // is successful, else n. int insertSorted(int arr[], int n, int key, int capacity) { // Cannot insert more elements if n is // already more than or equal to capacity if (n >= capacity) return n; arr[n] = key; return (n + 1); } // Driver Code int main() { int arr[20] = { 12, 16, 20, 40, 50, 70 }; int capacity = sizeof(arr) / sizeof(arr[0]); int n = 6; int i, key = 26; cout << ""\n Before Insertion: ""; for (i = 0; i < n; i++) cout << arr[i] << "" ""; // Inserting key n = insertSorted(arr, n, key, capacity); cout << ""\n After Insertion: ""; for (i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; } // This code is contributed by SHUBHAMSINGH10",constant,constant "// C Program to Insert an element // at a specific position in an Array #include using namespace std; // Function to insert element // at a specific position void insertElement(int arr[], int n, int x, int pos) { // shift elements to the right // which are on the right side of pos for (int i = n - 1; i >= pos; i--) arr[i + 1] = arr[i]; arr[pos] = x; } // Driver's code int main() { int arr[15] = { 2, 4, 1, 8, 5 }; int n = 5; cout<<""Before insertion : ""; for (int i = 0; i < n; i++) cout< using namespace std; // To search a key to be deleted int findElement(int arr[], int n, int key); // Function to delete an element int deleteElement(int arr[], int n, int key) { // Find position of element to be deleted int pos = findElement(arr, n, key); if (pos == -1) { cout << ""Element not found""; return n; } // Deleting element int i; for (i = pos; i < n - 1; i++) arr[i] = arr[i + 1]; return n - 1; } // Function to implement search operation int findElement(int arr[], int n, int key) { int i; for (i = 0; i < n; i++) if (arr[i] == key) return i; return -1; } // Driver's code int main() { int i; int arr[] = { 10, 50, 30, 40, 20 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 30; cout << ""Array before deletion\n""; for (i = 0; i < n; i++) cout << arr[i] << "" ""; // Function call n = deleteElement(arr, n, key); cout << ""\n\nArray after deletion\n""; for (i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; } // This code is contributed by shubhamsingh10",constant,linear "// C++ program to implement binary search in sorted array #include using namespace std; int binarySearch(int arr[], int low, int high, int key) { if (high < low) return -1; int mid = (low + high) / 2; /*low + (high - low)/2;*/ if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); } /* Driver code */ int main() { // Let us search 3 in below array int arr[] = { 5, 6, 7, 8, 9, 10 }; int n, key; n = sizeof(arr) / sizeof(arr[0]); key = 10; // Function call cout << ""Index: "" << binarySearch(arr, 0, n - 1, key) << endl; return 0; } // This code is contributed by NamrataSrivastava1",logn,logn "// C++ program to implement insert operation in // an sorted array. #include using namespace std; // Inserts a key in arr[] of given capacity. n is current // size of arr[]. This function returns n+1 if insertion // is successful, else n. int insertSorted(int arr[], int n, int key, int capacity) { // Cannot insert more elements if n is already // more than or equal to capacity if (n >= capacity) return n; int i; for (i = n - 1; (i >= 0 && arr[i] > key); i--) arr[i + 1] = arr[i]; arr[i + 1] = key; return (n + 1); } /* Driver code */ int main() { int arr[20] = { 12, 16, 20, 40, 50, 70 }; int capacity = sizeof(arr) / sizeof(arr[0]); int n = 6; int i, key = 26; cout << ""\nBefore Insertion: ""; for (i = 0; i < n; i++) cout << arr[i] << "" ""; // Function call n = insertSorted(arr, n, key, capacity); cout << ""\nAfter Insertion: ""; for (i = 0; i < n; i++) cout << arr[i] << "" ""; return 0; } // This code is contributed by SHUBHAMSINGH10",constant,linear "// C++ program to implement delete operation in a // sorted array #include using namespace std; // To search a key to be deleted int binarySearch(int arr[], int low, int high, int key); /* Function to delete an element */ int deleteElement(int arr[], int n, int key) { // Find position of element to be deleted int pos = binarySearch(arr, 0, n - 1, key); if (pos == -1) { cout << ""Element not found""; return n; } // Deleting element int i; for (i = pos; i < n - 1; i++) arr[i] = arr[i + 1]; return n - 1; } int binarySearch(int arr[], int low, int high, int key) { if (high < low) return -1; int mid = (low + high) / 2; if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); } // Driver code int main() { int i; int arr[] = { 10, 20, 30, 40, 50 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 30; cout << ""Array before deletion\n""; for (i = 0; i < n; i++) cout << arr[i] << "" ""; // Function call n = deleteElement(arr, n, key); cout << ""\n\nArray after deletion\n""; for (i = 0; i < n; i++) cout << arr[i] << "" ""; } // This code is contributed by shubhamsingh10",logn,linear "// C++ program for the above approach #include using namespace std; // Function to find and print pair bool chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { return 1; } } } return 0; } // Driver code int main() { int A[] = { 0, -1, 2, -3, 1 }; int x = -2; int size = sizeof(A) / sizeof(A[0]); if (chkPair(A, size, x)) { cout << ""Yes"" << endl; } else { cout << ""No"" << x << endl; } return 0; } // This code is contributed by Samim Hossain Mondal.",constant,quadratic "// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include using namespace std; // Function to check if array has 2 elements // whose sum is equal to the given value bool hasArrayTwoCandidates(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, A + arr_size); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[l] + A[r] > sum r--; } return 0; } /* Driver program to test above function */ int main() { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (hasArrayTwoCandidates(A, arr_size, n)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,nlogn "// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include using namespace std; bool binarySearch(int A[], int low, int high, int searchKey) { while (low <= high) { int m = low + (high - low) / 2; // Check if searchKey is present at mid if (A[m] == searchKey) return true; // If searchKey greater, ignore left half if (A[m] < searchKey) low = m + 1; // If searchKey is smaller, ignore right half else high = m - 1; } // if we reach here, then element was // not present return false; } bool checkTwoSum(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, A + arr_size); // Traversing all element in an array search for // searchKey for (int i = 0; i < arr_size - 1; i++) { int searchKey = sum - A[i]; // calling binarySearch function if (binarySearch(A, i + 1, arr_size - 1, searchKey) == true) { return true; } } return false; } /* Driver program to test above function */ int main() { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 14; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (checkTwoSum(A, arr_size, n)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,nlogn "// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include using namespace std; void printPairs(int arr[], int arr_size, int sum) { unordered_set s; for (int i = 0; i < arr_size; i++) { int temp = sum - arr[i]; if (s.find(temp) != s.end()) { cout << ""Yes"" << endl; return; } s.insert(arr[i]); } cout << ""No"" << endl; } /* Driver Code */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0; }",linear,linear "// Code in cpp to tell if there exists a pair in array whose // sum results in x. #include using namespace std; // Function to print pairs void printPairs(int a[], int n, int x) { int i; int rem[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if the element // is x, as numbers greater than x can't be used to get // a sum x. Updating the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i will // result to a sum of x. Once we get two // elements which add up to x , we print x and // break. cout << ""Yes\n""; break; } } // Once we reach middle of remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 elements // with remainder x/2, then we will have two // distinct elements which add up to x. if we // dont have more than 1 element, print ""No"". if (rem[x / 2] > 1) cout << ""Yes\n""; else cout << ""No\n""; } else { // When x is odd we continue the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) cout << ""Yes\n""; else cout << ""No\n""; } } } /* Driver Code */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// C++ program to search an element in an array // where difference between adjacent elements is atmost k #include using namespace std; // x is the element to be searched in arr[0..n-1] // such that all elements differ by at-most k. int search(int arr[], int n, int x, int k) { // Traverse the given array starting from // leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x divided by k // We use max here to make sure that i // moves at-least one step ahead. i = i + max(1, abs(arr[i]-x)/k); } cout << ""number is not present!""; return -1; } // Driver program to test above function int main() { int arr[] = {2, 4, 5, 7, 7, 6}; int x = 6; int k = 2; int n = sizeof(arr)/sizeof(arr[0]); cout << ""Element "" << x << "" is present at index "" << search(arr, n, x, k); return 0; }",constant,linear "// C++ program to print common elements in three arrays #include using namespace std; // This function prints common elements in ar1 void findCommon(int ar1[], int ar2[], int ar3[], int n1, int n2, int n3) { // Initialize starting indexes for ar1[], ar2[] and // ar3[] int i = 0, j = 0, k = 0; // Iterate through three arrays while all arrays have // elements while (i < n1 && j < n2 && k < n3) { // If x = y and y = z, print any of them and move // ahead in all arrays if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) { cout << ar1[i] << "" ""; i++; j++; k++; } // x < y else if (ar1[i] < ar2[j]) i++; // y < z else if (ar2[j] < ar3[k]) j++; // We reach here when x > y and z < y, i.e., z is // smallest else k++; } } // Driver code int main() { int ar1[] = { 1, 5, 10, 20, 40, 80 }; int ar2[] = { 6, 7, 20, 80, 100 }; int ar3[] = { 3, 4, 15, 20, 30, 70, 80, 120 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); int n3 = sizeof(ar3) / sizeof(ar3[0]); cout << ""Common Elements are ""; findCommon(ar1, ar2, ar3, n1, n2, n3); return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)",constant,linear "// C++ program to print common elements in three arrays #include using namespace std; // This function prints common elements in ar1 void findCommon(int ar1[], int ar2[], int ar3[], int n1, int n2, int n3) { // Initialize starting indexes for ar1[], ar2[] and ar3[] int i = 0, j = 0, k = 0; // Declare three variables prev1, prev2, prev3 to track // previous element int prev1, prev2, prev3; // Initialize prev1, prev2, prev3 with INT_MIN prev1 = prev2 = prev3 = INT_MIN; // Iterate through three arrays while all arrays have // elements while (i < n1 && j < n2 && k < n3) { // If ar1[i] = prev1 and i < n1, keep incrementing i while (ar1[i] == prev1 && i < n1) i++; // If ar2[j] = prev2 and j < n2, keep incrementing j while (ar2[j] == prev2 && j < n2) j++; // If ar3[k] = prev3 and k < n3, keep incrementing k while (ar3[k] == prev3 && k < n3) k++; // If x = y and y = z, print any of them, update // prev1 prev2, prev3 and move ahead in each array if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) { cout << ar1[i] << "" ""; prev1 = ar1[i++]; prev2 = ar2[j++]; prev3 = ar3[k++]; } // If x < y, update prev1 and increment i else if (ar1[i] < ar2[j]) prev1 = ar1[i++]; // If y < z, update prev2 and increment j else if (ar2[j] < ar3[k]) prev2 = ar2[j++]; // We reach here when x > y and z < y, i.e., z is // smallest update prev3 and increment k else prev3 = ar3[k++]; } } // Driver code int main() { int ar1[] = { 1, 5, 10, 20, 40, 80, 80 }; int ar2[] = { 6, 7, 20, 80, 80, 100 }; int ar3[] = { 3, 4, 15, 20, 30, 70, 80, 80, 120 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); int n3 = sizeof(ar3) / sizeof(ar3[0]); cout << ""Common Elements are ""; findCommon(ar1, ar2, ar3, n1, n2, n3); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,linear "#include using namespace std; void findCommon(int a[], int b[], int c[], int n1, int n2, int n3) { // three sets to maintain frequency of elements unordered_set uset, uset2, uset3; for (int i = 0; i < n1; i++) { uset.insert(a[i]); } for (int i = 0; i < n2; i++) { uset2.insert(b[i]); } // checking if elements of 3rd array are present in // first 2 sets for (int i = 0; i < n3; i++) { if (uset.find(c[i]) != uset.end() && uset2.find(c[i]) != uset.end()) { // using a 3rd set to prevent duplicates if (uset3.find(c[i]) == uset3.end()) cout << c[i] << "" ""; uset3.insert(c[i]); } } } // Driver code int main() { int ar1[] = { 1, 5, 10, 20, 40, 80 }; int ar2[] = { 6, 7, 20, 80, 100 }; int ar3[] = { 3, 4, 15, 20, 30, 70, 80, 120 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); int n3 = sizeof(ar3) / sizeof(ar3[0]); cout << ""Common Elements are "" << endl; findCommon(ar1, ar2, ar3, n1, n2, n3); return 0; }",linear,linear "// C++ program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (arr[i] == arr[j]) return arr[i]; } } } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; } // This code is added by Arpit Jain",constant,quadratic "// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { sort(arr, arr + N); // sort array for (int i = 0; i < N; i++) { // compare array element with its index if (arr[i] != i + 1) { return arr[i]; } } return -1; } // driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; } // this code is contributed by devendra solunke",constant,nlogn "// C++ program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { unordered_set s; for (int i = 0; i < N; i++) { if (s.find(arr[i]) != s.end()) return arr[i]; s.insert(arr[i]); } // If input is correct, we should // never reach here return -1; } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }",linear,linear "// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { // Find array sum and subtract sum // first N-1 natural numbers from it // to find the result. return accumulate(arr, arr + N, 0) - ((N - 1) * N / 2); } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }",constant,linear "// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (N-1) ^ arr[0] ^ // arr[1] ^ .... arr[N-1] int res = 0; for (int i = 0; i < N - 1; i++) res = res ^ (i + 1) ^ arr[i]; res = res ^ arr[N - 1]; return res; } // Driver code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }",constant,linear "// CPP program to find the only // repeating element in an array // where elements are from 1 to N-1. #include using namespace std; // Function to find repeated element int findRepeating(int arr[], int N) { int missingElement = 0; // indexing based for (int i = 0; i < N; i++) { int element = arr[abs(arr[i])]; if (element < 0) { missingElement = arr[i]; break; } arr[abs(arr[i])] = -arr[abs(arr[i])]; } return abs(missingElement); } // Driver code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }",constant,linear "#include using namespace std; int findDuplicate(vector& nums) { int slow = nums[0]; int fast = nums[0]; do { slow = nums[slow]; fast = nums[nums[fast]]; } while (slow != fast); fast = nums[0]; while (slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } // Driver code int main() { vector v{ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; // Function call int ans = findDuplicate(v); cout << ans << endl; return 0; }",constant,linear "// C++ program to find the array element // that appears only once #include using namespace std; // Function to find the int findSingle(int A[], int ar_size) { // Iterate over every element for (int i = 0; i < ar_size; i++) { // Initialize count to 0 int count = 0; for (int j = 0; j < ar_size; j++) { // Count the frequency // of the element if (A[i] == A[j]) { count++; } } // if the frequency of the // element is one if (count == 1) { return A[i]; } } // if no element exist at most once return -1; } // Driver code int main() { int ar[] = { 2, 3, 5, 4, 5, 3, 4 }; int n = sizeof(ar) / sizeof(ar[0]); // Function call cout << ""Element occurring once is "" << findSingle(ar, n); return 0; } // This code is contributed by Arpit Jain",constant,quadratic "// C++ program to find the array element // that appears only once #include using namespace std; int findSingle(int ar[], int ar_size) { // Do XOR of all elements and return int res = ar[0]; for (int i = 1; i < ar_size; i++) res = res ^ ar[i]; return res; } // Driver code int main() { int ar[] = { 2, 3, 5, 4, 5, 3, 4 }; int n = sizeof(ar) / sizeof(ar[0]); cout << ""Element occurring once is "" << findSingle(ar, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,linear "// C++ program to find // element that appears once #include using namespace std; // function which find number int singleNumber(int nums[],int n) { map m; long sum1 = 0,sum2 = 0; for(int i = 0; i < n; i++) { if(m[nums[i]] == 0) { sum1 += nums[i]; m[nums[i]]++; } sum2 += nums[i]; } // applying the formula. return 2 * (sum1) - sum2; } // Driver code int main() { int a[] = {2, 3, 5, 4, 5, 3, 4}; int n = 7; cout << singleNumber(a,n) << ""\n""; int b[] = {15, 18, 16, 18, 16, 15, 89}; cout << singleNumber(b,n); return 0; } // This code is contributed by mohit kumar 29",linear,nlogn "#include using namespace std; int singleelement(int arr[], int n) { int low = 0, high = n - 2; int mid; while (low <= high) { mid = (low + high) / 2; if (arr[mid] == arr[mid ^ 1]) low = mid + 1; else high = mid - 1; } return arr[low]; } int main() { int arr[] = { 2, 3, 5, 4, 5, 3, 4 }; int size = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + size); cout << singleelement(arr, size); return 0; } // This code is contributed by Sania Kumari Gupta",constant,nlogn "// C++ Program to find max subarray // sum excluding some elements #include using namespace std; // Function to check the element // present in array B bool isPresent(int B[], int m, int x) { for (int i = 0; i < m; i++) if (B[i] == x) return true; return false; } // Utility function for findMaxSubarraySum() // with the following parameters // A => Array A, // B => Array B, // n => Number of elements in Array A, // m => Number of elements in Array B int findMaxSubarraySumUtil(int A[], int B[], int n, int m) { // set max_so_far to INT_MIN int max_so_far = INT_MIN, curr_max = 0; for (int i = 0; i < n; i++) { // if the element is present in B, // set current max to 0 and move to // the next element */ if (isPresent(B, m, A[i])) { curr_max = 0; continue; } // Proceed as in Kadane's Algorithm curr_max = max(A[i], curr_max + A[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far; } // Wrapper for findMaxSubarraySumUtil() void findMaxSubarraySum(int A[], int B[], int n, int m) { int maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m); // This case will occur when all elements // of A are present in B, thus // no subarray can be formed if (maxSubarraySum == INT_MIN) { cout << ""Maximum Subarray Sum cant be found"" << endl; } else { cout << ""The Maximum Subarray Sum = "" << maxSubarraySum << endl; } } // Driver Code int main() { int A[] = { 3, 4, 5, -4, 6 }; int B[] = { 1, 8, 5 }; int n = sizeof(A) / sizeof(A[0]); int m = sizeof(B) / sizeof(B[0]); // Function call findMaxSubarraySum(A, B, n, m); return 0; }",constant,quadratic "// C++ Program to find max subarray // sum excluding some elements #include using namespace std; // Utility function for findMaxSubarraySum() // with the following parameters // A => Array A, // B => Array B, // n => Number of elements in Array A, // m => Number of elements in Array B int findMaxSubarraySumUtil(int A[], int B[], int n, int m) { // set max_so_far to INT_MIN int max_so_far = INT_MIN, curr_max = 0; for (int i = 0; i < n; i++) { // if the element is present in B, // set current max to 0 and move to // the next element if (binary_search(B, B + m, A[i])) { curr_max = 0; continue; } // Proceed as in Kadane's Algorithm curr_max = max(A[i], curr_max + A[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far; } // Wrapper for findMaxSubarraySumUtil() void findMaxSubarraySum(int A[], int B[], int n, int m) { // sort array B to apply Binary Search sort(B, B + m); int maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m); // This case will occur when all elements // of A are present in B, thus no subarray // can be formed if (maxSubarraySum == INT_MIN) { cout << ""Maximum subarray sum cant be found"" << endl; } else { cout << ""The Maximum subarray sum = "" << maxSubarraySum << endl; } } // Driver Code int main() { int A[] = { 3, 4, 5, -4, 6 }; int B[] = { 1, 8, 5 }; int n = sizeof(A) / sizeof(A[0]); int m = sizeof(B) / sizeof(B[0]); // Function call findMaxSubarraySum(A, B, n, m); return 0; }",constant,nlogn "// C++ Program implementation of the // above idea #include using namespace std; // Function to calculate the max sum of contiguous // subarray of B whose elements are not present in A int findMaxSubarraySum(vector A,vector B) { unordered_map m; // mark all the elements present in B for(int i=0;i a = { 3, 4, 5, -4, 6 }; vector b = { 1, 8, 5 }; // Function call cout << findMaxSubarraySum(a,b); return 0; } //This code is contributed by G.Vivek",linear,linear "// CPP program to find // maximum equilibrium sum. #include using namespace std; // Function to find // maximum equilibrium sum. int findMaxSum(int arr[], int n) { int res = INT_MIN; for (int i = 0; i < n; i++) { int prefix_sum = arr[i]; for (int j = 0; j < i; j++) prefix_sum += arr[j]; int suffix_sum = arr[i]; for (int j = n - 1; j > i; j--) suffix_sum += arr[j]; if (prefix_sum == suffix_sum) res = max(res, prefix_sum); } return res; } // Driver Code int main() { int arr[] = {-2, 5, 3, 1, 2, 6, -4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxSum(arr, n); return 0; }",linear,quadratic "// CPP program to find // maximum equilibrium sum. #include using namespace std; // Function to find maximum // equilibrium sum. int findMaxSum(int arr[], int n) { // Array to store prefix sum. int preSum[n]; // Array to store suffix sum. int suffSum[n]; // Variable to store maximum sum. int ans = INT_MIN; // Calculate prefix sum. preSum[0] = arr[0]; for (int i = 1; i < n; i++) preSum[i] = preSum[i - 1] + arr[i]; // Calculate suffix sum and compare // it with prefix sum. Update ans // accordingly. suffSum[n - 1] = arr[n - 1]; if (preSum[n - 1] == suffSum[n - 1]) ans = max(ans, preSum[n - 1]); for (int i = n - 2; i >= 0; i--) { suffSum[i] = suffSum[i + 1] + arr[i]; if (suffSum[i] == preSum[i]) ans = max(ans, preSum[i]); } return ans; } // Driver Code int main() { int arr[] = { -2, 5, 3, 1, 2, 6, -4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxSum(arr, n); return 0; }",linear,linear "// CPP program to find // maximum equilibrium sum. #include using namespace std; // Function to find // maximum equilibrium sum. int findMaxSum(int arr[], int n) { int sum = accumulate(arr, arr + n, 0); int prefix_sum = 0, res = INT_MIN; for (int i = 0; i < n; i++) { prefix_sum += arr[i]; if (prefix_sum == sum) res = max(res, prefix_sum); sum -= arr[i]; } return res; } // Driver Code int main() { int arr[] = { -2, 5, 3, 1, 2, 6, -4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxSum(arr, n); return 0; }",constant,linear "// C++ program to find equilibrium // index of an array #include using namespace std; int equilibrium(int arr[], int n) { int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { /* get left sum */ leftsum = 0; for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ rightsum = 0; for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1; } // Driver code int main() { int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); // Function call cout << equilibrium(arr, arr_size); return 0; } // This code is contributed // by Akanksha Rai(Abby_akku)",constant,quadratic "// C++ program to find equilibrium // index of an array #include using namespace std; int equilibrium(int arr[], int n) { int sum = 0; // initialize sum of whole array int leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1; } // Driver code int main() { int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""First equilibrium index is "" << equilibrium(arr, arr_size); return 0; } // This is code is contributed by rathbhupendra",constant,linear "// C++ program to find equilibrium index of an array #include using namespace std; int equilibrium(int a[], int n) { if (n == 1) return (0); int forward[n] = { 0 }; int rev[n] = { 0 }; // Taking the prefixsum from front end array for (int i = 0; i < n; i++) { if (i) { forward[i] = forward[i - 1] + a[i]; } else { forward[i] = a[i]; } } // Taking the prefixsum from back end of array for (int i = n - 1; i > 0; i--) { if (i <= n - 2) { rev[i] = rev[i + 1] + a[i]; } else { rev[i] = a[i]; } } // Checking if forward prefix sum // is equal to rev prefix // sum for (int i = 0; i < n; i++) { if (forward[i] == rev[i]) { return i; } } return -1; // If You want all the points // of equilibrium create // vector and push all equilibrium // points in it and // return the vector } // Driver code int main() { int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""First Point of equilibrium is at index "" << equilibrium(arr, n) << ""\n""; return 0; }",linear,linear "#include using namespace std; /*C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) { for (int i = 0; i < size; i++) { int j; for (j = i+1; j < size; j++) { if (arr[i] <=arr[j]) break; } if (j == size) // the loop didn't break cout << arr[i] << "" ""; } } /* Driver program to test above function */ int main() { int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0; }",constant,quadratic "#include using namespace std; /* C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) { int max_from_right = arr[size-1]; /* Rightmost element is always leader */ cout << max_from_right << "" ""; for (int i = size-2; i >= 0; i--) { if (max_from_right < arr[i]) { max_from_right = arr[i]; cout << max_from_right << "" ""; } } } /* Driver program to test above function*/ int main() { int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0; } ",constant,linear "#include using namespace std; /* C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) { /* create stack to store leaders*/ stack sk; sk.push(arr[size-1]); for (int i = size-2; i >= 0; i--) { if(arr[i] >= sk.top()) { sk.push(arr[i]); } } /* print stack elements*/ /* run loop till stack is not empty*/ while(!sk.empty()){ cout< using namespace std; /* Function to get index of ceiling of x in arr[low..high] */ int ceilSearch(int arr[], int low, int high, int x) { int i; /* If x is smaller than or equal to first element, then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1; } /* Driver code*/ int main() { int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; int index = ceilSearch(arr, 0, n-1, x); if(index == -1) cout << ""Ceiling of "" << x << "" doesn't exist in array ""; else cout << ""ceiling of "" << x << "" is "" << arr[index]; return 0; } // This is code is contributed by rathbhupendra",constant,linear "#include using namespace std; /* Function to get index of ceiling of x in arr[low..high]*/ int ceilSearch(int arr[], int low, int high, int x) { int mid; /* If x is smaller than or equal to the first element, then return the first element */ if (x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if (x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high) / 2; /* low + (high - low)/2 */ /* If x is same as middle element, then return mid */ if (arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if (arr[mid] < x) { if (mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low...mid-1] */ else { if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); } } // Driver Code int main() { int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 20; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) cout << ""Ceiling of "" << x << "" doesn't exist in array ""; else cout << ""ceiling of "" << x << "" is "" << arr[index]; return 0; } // This code is contributed by rathbhupendra",constant,logn "#include using namespace std; /* Function to get index of ceiling of x in arr[low..high]*/ int ceilSearch(int arr[], int low, int high, int x) { // base condition if length of arr == 0 then return -1 if (x == 0) { return -1; } int mid; // this while loop function will run until condition not // break once condition break loop will return start and // ans is low which will be next smallest greater than // target which is ceiling while (low <= high) { mid = low + (high - low) / 2; if (arr[mid] == x) return mid; else if (x < arr[mid]) high = mid - 1; else low = mid + 1; } return low; } /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */ int main() { int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) printf(""Ceiling of %d does not exist in an array"", x); else printf(""Ceiling of %d is %d"", x, arr[index]); return 0; }",constant,logn "// Hashing based C++ program to find if there // is a majority element in input array. #include using namespace std; // Returns true if there is a majority element // in a[] bool isMajority(int a[], int n) { // Insert all elements in a hash table unordered_map mp; for (int i = 0; i < n; i++) mp[a[i]]++; // Check if frequency of any element is // n/2 or more. for (auto x : mp) if (x.second >= n/2) return true; return false; } // Driver code int main() { int a[] = { 2, 3, 9, 2, 2 }; int n = sizeof(a) / sizeof(a[0]); if (isMajority(a, n)) cout << ""Yes""; else cout << ""No""; return 0; }",linear,linear "// A C++ program to find a peak element // using divide and conquer #include using namespace std; // A binary search based function // that returns index of a peak element int findPeakUtil(int arr[], int low, int high, int n) { // Find index of middle element // low + (high - low) / 2 int mid = low + (high - low) / 2; // Compare middle element with its // neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak and its // left neighbour is greater than it, // then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak and its // right neighbour is greater than it, // then right half must have a peak element else return findPeakUtil( arr, (mid + 1), high, n); } // A wrapper over recursive function findPeakUtil() int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code int main() { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Index of a peak point is "" << findPeak(arr, n); return 0; } // This code is contributed by rajdeep999",logn,logn "// A C++ program to find a peak element // using divide and conquer #include using namespace std; // A binary search based function // that returns index of a peak element int findPeak(int arr[], int n) { int l = 0; int r = n-1; int mid; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid]) and (mid == n - 1 || arr[mid + 1] <= arr[mid])) break; // move the right pointer if (mid > 0 and arr[mid - 1] > arr[mid]) r = mid - 1; // move the left pointer else l = mid + 1; } return mid; } // Driver Code int main() { int arr[] = { 1, 3, 20, 4, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); cout << ""Index of a peak point is "" << findPeak(arr, N); return 0; } // This code is contributed by Rajdeep Mallick (rajdeep999)",constant,logn "// C++ program to Find the two repeating // elements in a given array #include using namespace std; void printTwoRepeatNumber(int arr[], int size) { int i, j; cout << ""Repeating elements are ""; for (i = 0; i < size; i++) { for (j = i + 1; j < size; j++) { if (arr[i] == arr[j]) { cout << arr[i] << "" ""; break; } } } } int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printTwoRepeatNumber(arr, arr_size); return 0; }",constant,quadratic "// C++ implementation of above approach #include using namespace std; void printRepeating(int arr[], int size) { int* count = new int[sizeof(int) * (size - 2)]; int i; cout << "" Repeating elements are ""; for (i = 0; i < size; i++) { if (count[arr[i]] == 1) cout << arr[i] << "" ""; else count[arr[i]]++; } } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This is code is contributed by rathbhupendra",linear,linear "#include using namespace std; /* function to get factorial of n */ int fact(int n); void printRepeating(int arr[], int size) { int S = 0; /* S is for sum of elements in arr[] */ int P = 1; /* P is for product of elements in arr[] */ int x, y; /* x and y are two repeating elements */ int D; /* D is for difference of x and y, i.e., x-y*/ int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for (i = 0; i < size; i++) { S = S + arr[i]; P = P * arr[i]; } S = S - n * (n + 1) / 2; /* S is x + y now */ P = P / fact(n); /* P is x*y now */ D = sqrt(S * S - 4 * P); /* D is x - y now */ x = (D + S) / 2; y = (S - D) / 2; cout << ""Repeating elements are "" << x << "" "" << y; } int fact(int n) { return (n == 0) ? 1 : n * fact(n - 1); } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This code is contributed by rathbhupendra",constant,linear "#include using namespace std; void printRepeating(int arr[], int size) { int Xor = arr[0]; /* Will hold Xor of all elements */ int set_bit_no; /* Will have only single set bit of Xor */ int i; int n = size - 2; int x = 0, y = 0; /* Get the Xor of all elements in arr[] and {1, 2 .. n} */ for (i = 1; i < size; i++) Xor ^= arr[i]; for (i = 1; i <= n; i++) Xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = Xor & ~(Xor - 1); /* Now divide elements in two sets by comparing rightmost set bit of Xor with bit at same position in each element. */ for (i = 0; i < size; i++) { if (arr[i] & set_bit_no) x = x ^ arr[i]; /*Xor of first set in arr[] */ else y = y ^ arr[i]; /*Xor of second set in arr[] */ } for (i = 1; i <= n; i++) { if (i & set_bit_no) x = x ^ i; /*Xor of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*Xor of second set in arr[] and {1, 2, ...n } */ } cout << ""Repeating elements are "" << y << "" "" << x; } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This code is contributed by rathbhupendra",constant,linear "#include using namespace std; void printRepeating(int arr[], int size) { int i; cout << ""Repeating elements are ""; for (i = 0; i < size; i++) { if (arr[abs(arr[i])] > 0) arr[abs(arr[i])] = -arr[abs(arr[i])]; else cout << abs(arr[i]) << "" ""; } } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This code is contributed by rathbhupendra",constant,linear "#include using namespace std; void twoRepeated(int arr[], int N) { int m = N - 1; for (int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) cout << arr[i] % m << "" ""; } } // Driver Code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Repeating elements are ""; twoRepeated(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,linear "// C++ program to Find the two repeating // elements in a given array #include using namespace std; void printRepeating(int arr[], int size) { unordered_set s; cout << ""Repeating elements are ""; for (int i = 0; i < size; i++) { if (s.empty() == false && s.find(arr[i]) != s.end()) cout << arr[i] << "" ""; s.insert(arr[i]); } } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This code is contributed by nakul amate",linear,linear "/* A simple program to print subarray with sum as given sum */ #include using namespace std; /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ void subArraySum(int arr[], int n, int sum) { // Pick a starting point for (int i = 0; i < n; i++) { int currentSum = arr[i]; if (currentSum == sum) { cout << ""Sum found at indexes "" << i << endl; return; } else { // Try all subarrays starting with 'i' for (int j = i + 1; j < n; j++) { currentSum += arr[j]; if (currentSum == sum) { cout << ""Sum found between indexes "" << i << "" and "" << j << endl; return; } } } } cout << ""No subarray found""; return; } // Driver Code int main() { int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0; } // This code is contributed // by rathbhupendra",constant,quadratic "/* An efficient program to print subarray with sum as given sum */ #include using namespace std; /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { /* Initialize currentSum as value of first element and starting point as 0 */ int currentSum = arr[0], start = 0, i; /* Add elements one by one to currentSum and if the currentSum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If currentSum exceeds the sum, // then remove the starting elements while (currentSum > sum && start < i - 1) { currentSum = currentSum - arr[start]; start++; } // If currentSum becomes equal to sum, // then return true if (currentSum == sum) { cout << ""Sum found between indexes "" << start << "" and "" << i - 1; return 1; } // Add this element to currentSum if (i < n) currentSum = currentSum + arr[i]; } // If we reach here, then no subarray cout << ""No subarray found""; return 0; } // Driver Code int main() { int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0; } // This code is contributed by SHUBHAMSINGH10",constant,linear "// C++ implementation of smallest difference triplet #include using namespace std; // function to find maximum number int maximum(int a, int b, int c) { return max(max(a, b), c); } // function to find minimum number int minimum(int a, int b, int c) { return min(min(a, b), c); } // Finds and prints the smallest Difference Triplet void smallestDifferenceTriplet(int arr1[], int arr2[], int arr3[], int n) { // sorting all the three arrays sort(arr1, arr1+n); sort(arr2, arr2+n); sort(arr3, arr3+n); // To store resultant three numbers int res_min, res_max, res_mid; // pointers to arr1, arr2, arr3 // respectively int i = 0, j = 0, k = 0; // Loop until one array reaches to its end // Find the smallest difference. int diff = INT_MAX; while (i < n && j < n && k < n) { int sum = arr1[i] + arr2[j] + arr3[k]; // maximum number int max = maximum(arr1[i], arr2[j], arr3[k]); // Find minimum and increment its index. int min = minimum(arr1[i], arr2[j], arr3[k]); if (min == arr1[i]) i++; else if (min == arr2[j]) j++; else k++; // comparing new difference with the // previous one and updating accordingly if (diff > (max-min)) { diff = max - min; res_max = max; res_mid = sum - (max + min); res_min = min; } } // Print result cout << res_max << "", "" << res_mid << "", "" << res_min; } // Driver program to test above int main() { int arr1[] = {5, 2, 8}; int arr2[] = {10, 7, 12}; int arr3[] = {9, 14, 6}; int n = sizeof(arr1) / sizeof(arr1[0]); smallestDifferenceTriplet(arr1, arr2, arr3, n); return 0; }",constant,nlogn "// A simple C++ program to find three elements // whose sum is equal to zero #include using namespace std; // Prints all triplets in arr[] with 0 sum void findTriplets(int arr[], int n) { bool found = false; for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == 0) { cout << arr[i] << "" "" << arr[j] << "" "" << arr[k] << endl; found = true; } } } } // If no triplet with 0 sum found in array if (found == false) cout << "" not exist "" << endl; } // Driver code int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,cubic "// C++ program to find triplets in a given // array whose sum is zero #include using namespace std; // function to print triplets with 0 sum void findTriplets(int arr[], int n) { bool found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // ""-arr[i]"" unordered_set s; for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.find(x) != s.end()) { printf(""%d %d %d\n"", x, arr[i], arr[j]); found = true; } else s.insert(arr[j]); } } if (found == false) cout << "" No Triplet Found"" << endl; } // Driver code int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; }",linear,quadratic "// C++ program to find triplets in a given // array whose sum is zero #include using namespace std; // function to print triplets with 0 sum void findTriplets(int arr[], int n) { bool found = false; // sort array elements sort(arr, arr + n); for (int i = 0; i < n - 1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero printf(""%d %d %d\n"", x, arr[l], arr[r]); l++; r--; found = true; // break; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) cout << "" No Triplet Found"" << endl; } // Driven source int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; }",constant,quadratic "// C++ program to rotate a matrix #include #define R 4 #define C 4 using namespace std; // A function to rotate a matrix mat[][] of size R x C. // Initially, m = R and n = C void rotatematrix(int m, int n, int mat[R][C]) { int row = 0, col = 0; int prev, curr; /* row - Starting row index m - ending row index col - starting column index n - ending column index i - iterator */ while (row < m && col < n) { if (row + 1 == m || col + 1 == n) break; // Store the first element of next row, this // element will replace first element of current // row prev = mat[row + 1][col]; /* Move elements of first row from the remaining rows */ for (int i = col; i < n; i++) { curr = mat[row][i]; mat[row][i] = prev; prev = curr; } row++; /* Move elements of last column from the remaining columns */ for (int i = row; i < m; i++) { curr = mat[i][n-1]; mat[i][n-1] = prev; prev = curr; } n--; /* Move elements of last row from the remaining rows */ if (row < m) { for (int i = n-1; i >= col; i--) { curr = mat[m-1][i]; mat[m-1][i] = prev; prev = curr; } } m--; /* Move elements of first column from the remaining rows */ if (col < n) { for (int i = m-1; i >= row; i--) { curr = mat[i][col]; mat[i][col] = prev; prev = curr; } } col++; } // Print rotated matrix for (int i=0; i #define N 4 using namespace std; // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction void rotateMatrix(int mat[][N]) { // Consider all squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (int y = x; y < N - x - 1; y++) { // Store current cell in // temp variable int temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } } } // Function to print the matrix void displayMatrix(int mat[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << mat[i][j] << "" ""; } cout << endl; } cout << endl; } /* Driver code */ int main() { // Test Case 1 int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0; }",constant,quadratic "// C++ program to rotate a matrix // by 90 degrees #include using namespace std; #define N 4 // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction void rotateMatrix(int mat[][N]) { // REVERSE every row for (int i = 0; i < N; i++) reverse(mat[i], mat[i] + N); // Performing Transpose for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) swap(mat[i][j], mat[j][i]); } } // Function to print the matrix void displayMatrix(int mat[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << mat[i][j] << "" ""; } cout << endl; } cout << endl; } /* Driver code */ int main() { int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0; }",constant,quadratic "#include using namespace std; //Function to rotate matrix anticlockwise by 90 degrees. void rotateby90(vector >& matrix) { int n=matrix.size(); int mid; if(n%2==0) mid=n/2-1; else mid=n/2; for(int i=0,j=n-1;i<=mid;i++,j--) { for(int k=0;k>& arr) { int n=arr.size(); for(int i=0;i> arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); return 0; }",constant,quadratic "// C++ program to rotate a matrix by 180 degrees #include #define N 3 using namespace std; // Function to Rotate the matrix by 180 degree void rotateMatrix(int mat[][N]) { // Simply print from last cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) printf(""%d "", mat[i][j]); printf(""\n""); } } // Driven code int main() { int mat[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); return 0; }",constant,quadratic "// C++ program for left rotation of matrix by 180 #include using namespace std; #define R 4 #define C 4 // Function to rotate the matrix by 180 degree void reverseColumns(int arr[R][C]) { for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) swap(arr[j][i], arr[k][i]); } // Function for transpose of matrix void transpose(int arr[R][C]) { for (int i = 0; i < R; i++) for (int j = i; j < C; j++) swap(arr[i][j], arr[j][i]); } // Function for display the matrix void printMatrix(int arr[R][C]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << "" ""; cout << '\n'; } } // Function to anticlockwise rotate matrix // by 180 degree void rotate180(int arr[R][C]) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driven code int main() { int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); return 0; }",constant,quadratic "#include using namespace std; /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ void reverseRow(vector>& data, int index) { int cols = data[index].size(); for(int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ void printMatrix(vector>& data) { for(int i = 0; i < data.size(); i++) { for(int j = 0; j < data[i].size(); j++) { cout << data[i][j] << "" ""; } cout << endl; } } /** * Rotate Matrix by 180 degrees * @param data matrix */ void rotateMatrix180(vector>& data) { int rows = data.size(); int cols = data[0].size(); if (rows % 2 != 0) { // If N is odd reverse the middle // row in the matrix reverseRow(data, data.size() / 2); } // Swap the value of matrix [i][j] with // [rows - i - 1][cols - j - 1] for half // the rows size. for(int i = 0; i <= (rows/2) - 1; i++) { for(int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } } } // Driver code int main() { vector> data{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; // Rotate Matrix rotateMatrix180(data); // Print Matrix printMatrix(data); return 0; } // This code is contributed by divyeshrabadiya07",constant,quadratic "// C++ program to rotate individual rings by k in // spiral order traversal. #include #define MAX 100 using namespace std; // Fills temp array into mat[][] using spiral order // traversal. void fillSpiral(int mat[][MAX], int m, int n, int temp[]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int tIdx = 0; // Index in temp array while (k < m && l < n) { /* first row from the remaining rows */ for (int i = l; i < n; ++i) mat[k][i] = temp[tIdx++]; k++; /* last column from the remaining columns */ for (int i = k; i < m; ++i) mat[i][n-1] = temp[tIdx++]; n--; /* last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) mat[m-1][i] = temp[tIdx++]; m--; } /* first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) mat[i][l] = temp[tIdx++]; l++; } } } // Function to spirally traverse matrix and // rotate each ring of matrix by K elements // mat[][] --> matrix of elements // M --> number of rows // N --> number of columns void spiralRotate(int mat[][MAX], int M, int N, int k) { // Create a temporary array to store the result int temp[M*N]; /* s - starting row index m - ending row index l - starting column index n - ending column index; */ int m = M, n = N, s = 0, l = 0; int *start = temp; // Start position of current ring int tIdx = 0; // Index in temp while (s < m && l < n) { // Initialize end position of current ring int *end = start; // copy the first row from the remaining rows for (int i = l; i < n; ++i) { temp[tIdx++] = mat[s][i]; end++; } s++; // copy the last column from the remaining columns for (int i = s; i < m; ++i) { temp[tIdx++] = mat[i][n-1]; end++; } n--; // copy the last row from the remaining rows if (s < m) { for (int i = n-1; i >= l; --i) { temp[tIdx++] = mat[m-1][i]; end++; } m--; } /* copy the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= s; --i) { temp[tIdx++] = mat[i][l]; end++; } l++; } // if elements in current ring greater than // k then rotate elements of current ring if (end-start > k) { // Rotate current ring using reversal // algorithm for rotation reverse(start, start+k); reverse(start+k, end); reverse(start, end); // Reset start for next ring start = end; } } // Fill temp array in original matrix. fillSpiral(mat, M, N, temp); } // Driver program to run the case int main() { // Your C++ Code int M = 4, N = 4, k = 3; int mat[][MAX]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; spiralRotate(mat, M, N, k); // print modified matrix for (int i=0; i using namespace std; const int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1] // are rotations of each other. bool isPermutedMatrix( int mat[MAX][MAX], int n) { // Creating a string that contains elements of first // row. string str_cat = """"; for (int i = 0 ; i < n ; i++) str_cat = str_cat + ""-"" + to_string(mat[0][i]); // Concatenating the string with itself so that // substring search operations can be performed on // this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i=1; i using namespace std; #define SIZE 10 // function to sort the given matrix void sortMat(int mat[SIZE][SIZE], int n) { // temporary matrix of size n^2 int temp[n * n]; int k = 0; // copy the elements of matrix one by one // into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] sort(temp, temp + k); // copy the elements of temp[] one by one // in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++]; } // function to print the given matrix void printMat(int mat[SIZE][SIZE], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << "" ""; cout << endl; } } // Driver program to test above int main() { int mat[SIZE][SIZE] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; cout << ""Original Matrix:\n""; printMat(mat, n); sortMat(mat, n); cout << ""\nMatrix After Sorting:\n""; printMat(mat, n); return 0; }",quadratic,quadratic "// C++ program to find median of a matrix // sorted row wise #include using namespace std; const int MAX = 100; // function to find median in the matrix int binaryMedian(int m[][MAX], int r ,int c) { int min = INT_MAX, max = INT_MIN; for (int i=0; i max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while (min < max) { int mid = min + (max - min) / 2; int place = 0; // Find count of elements smaller than or equal to mid for (int i = 0; i < r; ++i) place += upper_bound(m[i], m[i]+c, mid) - m[i]; if (place < desired) min = mid + 1; else max = mid; } return min; } // driver program to check above functions int main() { int r = 3, c = 3; int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; cout << ""Median is "" << binaryMedian(m, r, c) << endl; return 0; }",constant,nlogn "// C++ program to print Lower // triangular and Upper triangular // matrix of an array #include using namespace std; // Function to form // lower triangular matrix void lower(int matrix[3][3], int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i < j) { cout << ""0"" << "" ""; } else cout << matrix[i][j] << "" ""; } cout << endl; } } // Function to form upper triangular matrix void upper(int matrix[3][3], int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i > j) { cout << ""0"" << "" ""; } else cout << matrix[i][j] << "" ""; } cout << endl; } } // Driver Code int main() { int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int row = 3, col = 3; cout << ""Lower triangular matrix: \n""; lower(matrix, row, col); cout << ""Upper triangular matrix: \n""; upper(matrix, row, col); return 0; }",constant,quadratic "// C++ program for the above approach #include using namespace std; vector spiralOrder(vector >& matrix) { int m = matrix.size(), n = matrix[0].size(); vector ans; if (m == 0) return ans; vector > seen(m, vector(n, false)); int dr[] = { 0, 1, 0, -1 }; int dc[] = { 1, 0, -1, 0 }; int x = 0, y = 0, di = 0; // Iterate from 0 to m * n - 1 for (int i = 0; i < m * n; i++) { ans.push_back(matrix[x][y]); // on normal geeksforgeeks ui page it is showing // 'ans.push_back(matrix[x])' which gets copied as // this only and gives error on compilation, seen[x][y] = true; int newX = x + dr[di]; int newY = y + dc[di]; if (0 <= newX && newX < m && 0 <= newY && newY < n && !seen[newX][newY]) { x = newX; y = newY; } else { di = (di + 1) % 4; x += dr[di]; y += dc[di]; } } return ans; } // Driver code int main() { vector > a{ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call for (int x : spiralOrder(a)) { cout << x << "" ""; } return 0; } // This code is contributed by Yashvendra Singh",linear,linear "// C++ Program to print a matrix spirally #include using namespace std; #define R 4 #define C 4 void spiralPrint(int m, int n, int a[R][C]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { cout << a[k][i] << "" ""; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { cout << a[i][n - 1] << "" ""; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { cout << a[m - 1][i] << "" ""; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m - 1; i >= k; --i) { cout << a[i][l] << "" ""; } l++; } } } /* Driver Code */ int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call spiralPrint(R, C, a); return 0; } // This is code is contributed by rathbhupendra",constant,quadratic "// C++. program for the above approach #include using namespace std; #define R 4 #define C 4 // Function for printing matrix in spiral // form i, j: Start index of matrix, row // and column respectively m, n: End index // of matrix row and column respectively void print(int arr[R][C], int i, int j, int m, int n) { // If i or j lies outside the matrix if (i >= m or j >= n) return; // Print First Row for (int p = j; p < n; p++) cout << arr[i][p] << "" ""; // Print Last Column for (int p = i + 1; p < m; p++) cout << arr[p][n - 1] << "" ""; // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) for (int p = n - 2; p >= j; p--) cout << arr[m - 1][p] << "" ""; // Print First Column, if Last and // First Column are not same if ((n - 1) != j) for (int p = m - 2; p > i; p--) cout << arr[p][j] << "" ""; print(arr, i + 1, j + 1, m - 1, n - 1); } // Driver Code int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); return 0; } // This Code is contributed by Ankur Goel",constant,quadratic "// C++ program for the above approach #include using namespace std; #define R 4 #define C 4 bool isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } // check if the position is blocked bool isBlocked(int matrix[R][C], int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false; } // DFS code to traverse spirally void spirallyDFSTravserse(int matrix[R][C], int i, int j, int dir, vector& res) { if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push_back(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } // To traverse spirally vector spirallyTraverse(int matrix[R][C]) { vector res; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } // Driver Code int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call vector res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) cout << res[i] << "" ""; cout << endl; return 0; } // code contributed by Ephi F",constant,quadratic "// C++ program to find unique element in matrix #include using namespace std; #define R 4 #define C 4 // function that calculate unique element int unique(int mat[R][C], int n, int m) { // declare map for hashing unordered_map mp; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) // increase freq of mat[i][j] in map mp[mat[i][j]]++; int flag = false; // print unique element for (auto p : mp) { if (p.second == 1) { cout << p.first << "" ""; flag = 1; } } if (!flag) { cout << ""No unique element in the matrix""; } } // Driver program int main() { int mat[R][C] = { { 1, 2, 3, 20 }, { 5, 6, 20, 25 }, { 1, 3, 5, 6 }, { 6, 7, 8, 15 } }; // function that calculate unique element unique(mat, R, C); return 0; }",quadratic,quadratic "// CPP Program to swap diagonal of a matrix #include using namespace std; // size of square matrix #define N 3 // Function to swap diagonal of matrix void swapDiagonal(int matrix[][N]) { for (int i = 0; i < N; i++) swap(matrix[i][i], matrix[i][N - i - 1]); } // Driver Code int main() { int matrix[N][N] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; swapDiagonal(matrix); // Displaying modified matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << matrix[i][j] << "" ""; cout << endl; } return 0; }",constant,quadratic "// CPP program for finding max path in matrix #include #define N 4 #define M 6 using namespace std; // To calculate max path in matrix int findMaxPath(int mat[][M]) { for (int i = 1; i < N; i++) { for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum } } int res = 0; for (int j = 0; j < M; j++) res = max(mat[N-1][j], res); return res; } // Driver program to check findMaxPath int main() { int mat1[N][M] = { { 10, 10, 2, 0, 20, 4 }, { 1, 0, 0, 30, 2, 5 }, { 0, 10, 4, 0, 2, 0 }, { 1, 0, 2, 20, 0, 4 } }; cout << findMaxPath(mat1) << endl; return 0; }",constant,quadratic "// C++ code to move matrix elements // in given direction with add // element with same value #include using namespace std; #define MAX 50 // Function to shift the matrix // in the given direction void moveMatrix(char d[], int n, int a[MAX][MAX]) { // For right shift move. if (d[0] == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { vector v, w; int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (auto it = w.begin(); it != w.end(); it++) a[i][j--] = *it; } } // for left shift move else if (d[0] == 'l') { // for each row for (int i = 0; i < n; i++) { vector v, w; int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (auto it = w.begin(); it != w.end(); it++) a[i][j++] = *it; } } // for down shift move. else if (d[0] == 'd') { // for each column for (int i = 0; i < n; i++) { vector v, w; int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j--][i] = *it; } } // for up shift move else if (d[0] == 'u') { // for each column for (int i = 0; i < n; i++) { vector v, w; int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j++][i] = *it; } } } // Driven Program int main() { char d[2] = ""l""; int n = 5; int a[MAX][MAX] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << a[i][j] << "" ""; cout << endl; } return 0; }",linear,quadratic "// C++ program to find number of subarrays // having product exactly equal to k. #include using namespace std; // Function to find number of subarrays // having product equal to 1. int countOne(int arr[], int n){ int i = 0; // To store number of ones in // current segment of all 1s. int len = 0; // To store number of subarrays // having product equal to 1. int ans = 0; while(i < n){ // If current element is 1, then // find length of segment of 1s // starting from current element. if(arr[i] == 1){ len = 0; while(i < n && arr[i] == 1){ i++; len++; } // add number of possible // subarrays of 1 to result. ans += (len*(len+1)) / 2; } i++; } return ans; } /// Function to find number of subarrays having /// product exactly equal to k. int findSubarrayCount(int arr[], int n, int k) { int start = 0, endval = 0, p = 1, countOnes = 0, res = 0; while (endval < n) { p *= (arr[endval]); // If product is greater than k then we need to decrease // it. This could be done by shifting starting point of // sliding window one place to right at a time and update // product accordingly. if(p > k) { while(start <= endval && p > k) { p /= arr[start]; start++; } } if(p == k) { // Count number of succeeding ones. countOnes = 0; while(endval + 1 < n && arr[endval + 1] == 1) { countOnes++; endval++; } // Update result by adding both new subarray // and effect of succeeding ones. res += (countOnes + 1); // Update sliding window and result according // to change in sliding window. Here preceding // 1s have same effect on subarray as succeeding // 1s, so simply add. while(start <= endval && arr[start] == 1 && k!=1) { res += (countOnes + 1); start++; } // Move start to correct position to find new // subarray and update product accordingly. p /= arr[start]; start++; } endval++; } return res; } // Driver code int main() { int arr1[] = { 2, 1, 1, 1, 3, 1, 1, 4}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int k = 1; if(k != 1) cout << findSubarrayCount(arr1, n1, k) << ""\n""; else cout << countOne(arr1, n1) << ""\n""; int arr2[] = { 2, 1, 1, 1, 4, 5}; int n2 = sizeof(arr2) / sizeof(arr2[0]); k = 4; if(k != 1) cout << findSubarrayCount(arr2, n2, k) << ""\n""; else cout << countOne(arr2, n2) << ""\n""; return 0; }",constant,linear "// CPP program to find all those // elements of arr1[] that are not // present in arr2[] #include using namespace std; void relativeComplement(int arr1[], int arr2[], int n, int m) { int i = 0, j = 0; while (i < n && j < m) { // If current element in arr2[] is // greater, then arr1[i] can't be // present in arr2[j..m-1] if (arr1[i] < arr2[j]) { cout << arr1[i] << "" ""; i++; // Skipping smaller elements of // arr2[] } else if (arr1[i] > arr2[j]) { j++; // Equal elements found (skipping // in both arrays) } else if (arr1[i] == arr2[j]) { i++; j++; } } // Printing remaining elements of // arr1[] while (i < n) cout << arr1[i] << "" ""; } // Driver code int main() { int arr1[] = {3, 6, 10, 12, 15}; int arr2[] = {1, 3, 5, 10, 16}; int n = sizeof(arr1) / sizeof(arr1[0]); int m = sizeof(arr2) / sizeof(arr2[0]); relativeComplement(arr1, arr2, n, m); return 0; }",constant,linear "// Program to make all array equal #include using namespace std; // function for calculating min operations int minOps(int arr[], int n, int k) { // max elements of array int max = *max_element(arr, arr + n); int res = 0; // iterate for all elements for (int i = 0; i < n; i++) { // check if element can make equal to // max or not if not then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required operations else res += (max - arr[i]) / k; } // return result return res; } // driver program int main() { int arr[] = { 21, 33, 9, 45, 63 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 6; cout << minOps(arr, n, k); return 0; }",constant,linear "// C++ code for above approach #include using namespace std; int solve(int A[], int B[], int C[], int i, int j, int k) { int min_diff, current_diff, max_term; // calculating min difference from last // index of lists min_diff = abs(max(A[i], max(B[j], C[k])) - min(A[i], min(B[j], C[k])));; while (i != -1 && j != -1 && k != -1) { current_diff = abs(max(A[i], max(B[j], C[k])) - min(A[i], min(B[j], C[k]))); // checking condition if (current_diff < min_diff) min_diff = current_diff; // calculating max term from list max_term = max(A[i], max(B[j], C[k])); // Moving to smaller value in the // array with maximum out of three. if (A[i] == max_term) i -= 1; else if (B[j] == max_term) j -= 1; else k -= 1; } return min_diff; } // Driver code int main() { int D[] = { 5, 8, 10, 15 }; int E[] = { 6, 9, 15, 78, 89 }; int F[] = { 2, 3, 6, 6, 8, 8, 10 }; int nD = sizeof(D) / sizeof(D[0]); int nE = sizeof(E) / sizeof(E[0]); int nF = sizeof(F) / sizeof(F[0]); cout << solve(D, E, F, nD-1, nE-1, nF-1); return 0; } // This code is contributed by Ravi Maurya.",constant,linear "/* A program to convert Binary Tree to Binary Search Tree */ #include using namespace std; /* A binary tree node structure */ struct node { int data; struct node* left; struct node* right; }; /* A helper function that stores inorder traversal of a tree rooted with node */ void storeInorder(struct node* node, int inorder[], int* index_ptr) { // Base Case if (node == NULL) return; /* first store the left subtree */ storeInorder(node->left, inorder, index_ptr); /* Copy the root's data */ inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* finally store the right subtree */ storeInorder(node->right, inorder, index_ptr); } /* A helper function to count nodes in a Binary Tree */ int countNodes(struct node* root) { if (root == NULL) return 0; return countNodes(root->left) + countNodes(root->right) + 1; } // Following function is needed for library function qsort() int compare(const void* a, const void* b) { return (*(int*)a - *(int*)b); } /* A helper function that copies contents of arr[] to Binary Tree. This function basically does Inorder traversal of Binary Tree and one by one copy arr[] elements to Binary Tree nodes */ void arrayToBST(int* arr, struct node* root, int* index_ptr) { // Base Case if (root == NULL) return; /* first update the left subtree */ arrayToBST(arr, root->left, index_ptr); /* Now update root's data and increment index */ root->data = arr[*index_ptr]; (*index_ptr)++; /* finally update the right subtree */ arrayToBST(arr, root->right, index_ptr); } // This function converts a given Binary Tree to BST void binaryTreeToBST(struct node* root) { // base case: tree is empty if (root == NULL) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder // traversal of tree in arr[] int* arr = new int[n]; int i = 0; storeInorder(root, arr, &i); // Sort the array using library function for quick sort qsort(arr, n, sizeof(arr[0]), compare); // Copy array elements back to Binary Tree i = 0; arrayToBST(arr, root, &i); // delete dynamically allocated memory to // avoid memory leak delete[] arr; } /* Utility function to create a new Binary Tree node */ struct node* newNode(int data) { struct node* temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } /* Utility function to print inorder traversal of Binary Tree */ void printInorder(struct node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout <<"" ""<< node->data; /* now recur on right child */ printInorder(node->right); } /* Driver function to test above functions */ int main() { struct node* root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ root = newNode(10); root->left = newNode(30); root->right = newNode(15); root->left->left = newNode(20); root->right->right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); cout <<""Following is Inorder Traversal of the converted BST:"" << endl ; printInorder(root); return 0; } // This code is contributed by shivanisinghss2110",linear,nlogn "// C++ program to print BST in given range #include using namespace std; /* A Binary Tree node */ class TNode { public: int data; TNode* left; TNode* right; }; TNode* newNode(int data); /* A function that constructs Balanced Binary Search Tree from a sorted array */ TNode* sortedArrayToBST(int arr[], int start, int end) { /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; TNode *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid + 1, end); return root; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ TNode* newNode(int data) { TNode* node = new TNode(); node->data = data; node->left = NULL; node->right = NULL; return node; } /* A utility function to print preorder traversal of BST */ void preOrder(TNode* node) { if (node == NULL) return; cout << node->data << "" ""; preOrder(node->left); preOrder(node->right); } // Driver Code int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); /* Convert List to BST */ TNode *root = sortedArrayToBST(arr, 0, n-1); cout << ""PreOrder Traversal of constructed BST \n""; preOrder(root); return 0; } // This code is contributed by rathbhupendra",logn,linear "// C++ program to transform a BST to sum tree #include using namespace std; // A BST node struct Node { int data; struct Node *left, *right; }; // A utility function to create a new Binary Tree Node struct Node *newNode(int item) { struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } // Recursive function to transform a BST to sum tree. // This function traverses the tree in reverse inorder so // that we have visited all greater key nodes of the currently // visited node void transformTreeUtil(struct Node *root, int *sum) { // Base case if (root == NULL) return; // Recur for right subtree transformTreeUtil(root->right, sum); // Update sum *sum = *sum + root->data; // Store old sum in current node root->data = *sum - root->data; // Recur for left subtree transformTreeUtil(root->left, sum); } // A wrapper over transformTreeUtil() void transformTree(struct Node *root) { int sum = 0; // Initialize sum transformTreeUtil(root, ∑); } // A utility function to print indorder traversal of a // binary tree void printInorder(struct Node *root) { if (root == NULL) return; printInorder(root->left); cout << root->data << "" ""; printInorder(root->right); } // Driver Program to test above functions int main() { struct Node *root = newNode(11); root->left = newNode(2); root->right = newNode(29); root->left->left = newNode(1); root->left->right = newNode(7); root->right->left = newNode(15); root->right->right = newNode(40); root->right->right->left = newNode(35); cout << ""Inorder Traversal of given tree\n""; printInorder(root); transformTree(root); cout << ""\n\nInorder Traversal of transformed tree\n""; printInorder(root); return 0; }",linear,linear "//C++ Program to convert a BST into a Min-Heap // in O(n) time and in-place #include using namespace std; // Node for BST/Min-Heap struct Node { int data; Node *left, *right; }; // Utility function for allocating node for BST Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // Utility function to print Min-heap level by level void printLevelOrder(Node *root) { // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue q; q.push(root); while (!q.empty()) { int nodeCount = q.size(); while (nodeCount > 0) { Node *node = q.front(); cout << node->data << "" ""; q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); nodeCount--; } cout << endl; } } // A simple recursive function to convert a given // Binary Search tree to Sorted Linked List // root --> Root of Binary Search Tree // head_ref --> Pointer to head node of created // linked list void BSTToSortedLL(Node* root, Node** head_ref) { // Base cases if(root == NULL) return; // Recursively convert right subtree BSTToSortedLL(root->right, head_ref); // insert root into linked list root->right = *head_ref; // Change left pointer of previous head // to point to NULL if (*head_ref != NULL) (*head_ref)->left = NULL; // Change head of linked list *head_ref = root; // Recursively convert left subtree BSTToSortedLL(root->left, head_ref); } // Function to convert a sorted Linked // List to Min-Heap. // root --> Root of Min-Heap // head --> Pointer to head node of sorted // linked list void SortedLLToMinHeap(Node* &root, Node* head) { // Base Case if (head == NULL) return; // queue to store the parent nodes queue q; // The first node is always the root node root = head; // advance the pointer to the next node head = head->right; // set right child to NULL root->right = NULL; // add first node to the queue q.push(root); // run until the end of linked list is reached while (head) { // Take the parent node from the q and remove it from q Node* parent = q.front(); q.pop(); // Take next two nodes from the linked list and // Add them as children of the current parent node // Also in push them into the queue so that // they will be parents to the future nodes Node *leftChild = head; head = head->right; // advance linked list to next node leftChild->right = NULL; // set its right child to NULL q.push(leftChild); // Assign the left child of parent parent->left = leftChild; if (head) { Node *rightChild = head; head = head->right; // advance linked list to next node rightChild->right = NULL; // set its right child to NULL q.push(rightChild); // Assign the right child of parent parent->right = rightChild; } } } // Function to convert BST into a Min-Heap // without using any extra space Node* BSTToMinHeap(Node* &root) { // head of Linked List Node *head = NULL; // Convert a given BST to Sorted Linked List BSTToSortedLL(root, &head); // set root as NULL root = NULL; // Convert Sorted Linked List to Min-Heap SortedLLToMinHeap(root, head); } // Driver code int main() { /* Constructing below tree 8 / \ 4 12 / \ / \ 2 6 10 14 */ Node* root = newNode(8); root->left = newNode(4); root->right = newNode(12); root->right->left = newNode(10); root->right->right = newNode(14); root->left->left = newNode(2); root->left->right = newNode(6); BSTToMinHeap(root); /* Output - Min Heap 2 / \ 4 6 / \ / \ 8 10 12 14 */ printLevelOrder(root); return 0; }",linear,linear "// C++ implementation to convert the given // BST to Min Heap #include using namespace std; // Structure of a node of BST struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* getNode(int data) { struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // function prototype for preorder traversal // of the given tree void preorderTraversal(Node*); // function for the inorder traversal of the tree // so as to store the node values in 'arr' in // sorted order void inorderTraversal(Node* root, vector& arr) { if (root == NULL) return; // first recur on left subtree inorderTraversal(root->left, arr); // then copy the data of the node arr.push_back(root->data); // now recur for right subtree inorderTraversal(root->right, arr); } // function to convert the given BST to MIN HEAP // performs preorder traversal of the tree void BSTToMinHeap(Node* root, vector arr, int* i) { if (root == NULL) return; // first copy data at index 'i' of 'arr' to // the node root->data = arr[++*i]; // then recur on left subtree BSTToMinHeap(root->left, arr, i); // now recur on right subtree BSTToMinHeap(root->right, arr, i); } // utility function to convert the given BST to // MIN HEAP void convertToMinHeapUtil(Node* root) { // vector to store the data of all the // nodes of the BST vector arr; int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MIN HEAP conversion BSTToMinHeap(root, arr, &i); } // function for the preorder traversal of the tree void preorderTraversal(Node* root) { if (!root) return; // first print the root's data cout << root->data << "" ""; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right); } // Driver program to test above int main() { // BST formation struct Node* root = getNode(4); root->left = getNode(2); root->right = getNode(6); root->left->left = getNode(1); root->left->right = getNode(3); root->right->left = getNode(5); root->right->right = getNode(7); // Function call convertToMinHeapUtil(root); cout << ""Preorder Traversal:"" << endl; preorderTraversal(root); return 0; }",linear,linear "// C++ implementation to construct a BST // from its level order traversal #include using namespace std; // node of a BST struct Node { int data; Node *left, *right; }; // function to get a new node Node* getNode(int data) { // Allocate memory Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // function to construct a BST from // its level order traversal Node* LevelOrder(Node* root, int data) { if (root == NULL) { root = getNode(data); return root; } if (data <= root->data) root->left = LevelOrder(root->left, data); else root->right = LevelOrder(root->right, data); return root; } Node* constructBst(int arr[], int n) { if (n == 0) return NULL; Node* root = NULL; for (int i = 0; i < n; i++) root = LevelOrder(root, arr[i]); return root; } // function to print the inorder traversal void inorderTraversal(Node* root) { if (!root) return; inorderTraversal(root->left); cout << root->data << "" ""; inorderTraversal(root->right); } // Driver program to test above int main() { int arr[] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 }; int n = sizeof(arr) / sizeof(arr[0]); Node* root = constructBst(arr, n); cout << ""Inorder Traversal: ""; inorderTraversal(root); return 0; }",linear,nlogn "// C++ implementation to construct a BST // from its level order traversal #include using namespace std; // node of a BST struct Node { int data; Node *left, *right; Node(int x) { data = x; right = NULL; left = NULL; } }; // Function to construct a BST from // its level order traversal Node* constructBst(int arr[], int n) { // Create queue to store the tree nodes queue > > q; // If array is empty we return NULL if (n == 0) return NULL; // Create root node and store a copy of it in head Node *root = new Node(arr[0]), *head = root; // Push the root node and the initial range q.push({ root, { INT_MIN, INT_MAX } }); // Loop over the contents of arr to process all the // elements for (int i = 1; i < n; i++) { // Get the node and the range at the front of the // queue Node* temp = q.front().first; pair range = q.front().second; // Check if arr[i] can be a child of the temp node if (arr[i] > range.first && arr[i] < range.second) { // Check if arr[i] can be left child if (arr[i] < temp->data) { // Set the left child and range temp->left = new Node(arr[i]); q.push({ temp->left, { range.first, temp->data } }); } // Check if arr[i] can be left child else { // Pop the temp node from queue, set the // right child and new range q.pop(); temp->right = new Node(arr[i]); q.push({ temp->right, { temp->data, range.second } }); } } else { q.pop(); i--; } } return head; } // Function to print the inorder traversal void inorderTraversal(Node* root) { if (!root) return; inorderTraversal(root->left); cout << root->data << "" ""; inorderTraversal(root->right); } // Driver program to test above int main() { int arr[] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 }; int n = sizeof(arr) / sizeof(arr[0]); Node* root = constructBst(arr, n); cout << ""Inorder Traversal: ""; inorderTraversal(root); return 0; } // This code is contributed by Rohit Iyer (rohit_iyer)",linear,linear "/* CPP program to convert a Binary tree to BST using sets as containers. */ #include using namespace std; struct Node { int data; struct Node *left, *right; }; // function to store the nodes in set while // doing inorder traversal. void storeinorderInSet(Node* root, set& s) { if (!root) return; // visit the left subtree first storeinorderInSet(root->left, s); // insertion takes order of O(logn) for sets s.insert(root->data); // visit the right subtree storeinorderInSet(root->right, s); } // Time complexity = O(nlogn) // function to copy items of set one by one // to the tree while doing inorder traversal void setToBST(set& s, Node* root) { // base condition if (!root) return; // first move to the left subtree and // update items setToBST(s, root->left); // iterator initially pointing to the // beginning of set auto it = s.begin(); // copying the item at beginning of // set(sorted) to the tree. root->data = *it; // now erasing the beginning item from set. s.erase(it); // now move to right subtree and update items setToBST(s, root->right); } // T(n) = O(nlogn) time // Converts Binary tree to BST. void binaryTreeToBST(Node* root) { set s; // populating the set with the tree's // inorder traversal data storeinorderInSet(root, s); // now sets are by default sorted as // they are implemented using self- // balancing BST // copying items from set to the tree // while inorder traversal which makes a BST setToBST(s, root); } // Time complexity = O(nlogn), // Auxiliary Space = O(n) for set. // helper function to create a node Node* newNode(int data) { // dynamically allocating memory Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // function to do inorder traversal void inorder(Node* root) { if (!root) return; inorder(root->left); cout << root->data << "" ""; inorder(root->right); } int main() { Node* root = newNode(5); root->left = newNode(7); root->right = newNode(9); root->right->left = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(11); /* Constructing tree given in the above figure 5 / \ 7 9 /\ / \ 1 6 10 11 */ // converting the above Binary tree to BST binaryTreeToBST(root); cout << ""Inorder traversal of BST is: "" << endl; inorder(root); return 0; }",linear,nlogn "// C++ Code for the above approach #include using namespace std; /* A binary tree node has data, a pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; }; // Function to return a new Node Node* newNode(int data) { Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Function to convert bst to // a doubly linked list void bstTodll(Node* root, Node*& head) { // if root is NULL if (!root) return; // Convert right subtree recursively bstTodll(root->right, head); // Update root root->right = head; // if head is not NULL if (head) { // Update left of the head head->left = root; } // Update head head = root; // Convert left subtree recursively bstTodll(root->left, head); } // Function to merge two sorted linked list Node* mergeLinkedList(Node* head1, Node* head2) { /*Create head and tail for result list*/ Node* head = NULL; Node* tail = NULL; while (head1 && head2) { if (head1->data < head2->data) { if (!head) head = head1; else { tail->right = head1; head1->left = tail; } tail = head1; head1 = head1->right; } else { if (!head) head = head2; else { tail->right = head2; head2->left = tail; } tail = head2; head2 = head2->right; } } while (head1) { tail->right = head1; head1->left = tail; tail = head1; head1 = head1->right; } while (head2) { tail->right = head2; head2->left = tail; tail = head2; head2 = head2->right; } // Return the created DLL return head; } // function to convert list to bst Node* sortedListToBST(Node*& head, int n) { // if no element is left or head is null if (n <= 0 || !head) return NULL; // Create left part from the list recursively Node* left = sortedListToBST(head, n / 2); Node* root = head; root->left = left; head = head->right; // Create left part from the list recursively root->right = sortedListToBST(head, n - (n / 2) - 1); // Return the root of BST return root; } // This function merges two balanced BSTs Node* mergeTrees(Node* root1, Node* root2, int m, int n) { // Convert BSTs into sorted Doubly Linked Lists Node* head1 = NULL; bstTodll(root1, head1); head1->left = NULL; Node* head2 = NULL; bstTodll(root2, head2); head2->left = NULL; // Merge the two sorted lists into one Node* head = mergeLinkedList(head1, head2); // Construct a tree from the merged lists return sortedListToBST(head, m + n); } void printInorder(Node* node) { // if current node is NULL if (!node) { return; } printInorder(node->left); // Print node of current data cout << node->data << "" ""; printInorder(node->right); } /* Driver code*/ int main() { /* Create following tree as first balanced BST 100 / \ 50 300 / \ 20 70 */ Node* root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \ 40 120 */ Node* root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); // Function Call Node* mergedTree = mergeTrees(root1, root2, 5, 3); cout << ""Following is Inorder traversal of the merged "" ""tree \n""; printInorder(mergedTree); return 0; } // This code is contributed by Tapesh(tapeshdua420)",constant,linear "#include using namespace std; // Structure of a BST Node class node { public: int data; node *left; node *right; }; //.................... START OF STACK RELATED STUFF.................... // A stack node class snode { public: node *t; snode *next; }; // Function to add an element k to stack void push(snode **s, node *k) { snode *tmp = new snode(); //perform memory check here tmp->t = k; tmp->next = *s; (*s) = tmp; } // Function to pop an element t from stack node *pop(snode **s) { node *t; snode *st; st=*s; (*s) = (*s)->next; t = st->t; free(st); return t; } // Function to check whether the stack is empty or not int isEmpty(snode *s) { if (s == NULL ) return 1; return 0; } //.................... END OF STACK RELATED STUFF.................... /* Utility function to create a new Binary Tree node */ node* newNode (int data) { node *temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } /* A utility function to print Inorder traversal of a Binary Tree */ void inorder(node *root) { if (root != NULL) { inorder(root->left); cout<data<<"" ""; inorder(root->right); } } // The function to print data of two BSTs in sorted order void merge(node *root1, node *root2) { // s1 is stack to hold nodes of first BST snode *s1 = NULL; // Current node of first BST node *current1 = root1; // s2 is stack to hold nodes of second BST snode *s2 = NULL; // Current node of second BST node *current2 = root2; // If first BST is empty, then output is inorder // traversal of second BST if (root1 == NULL) { inorder(root2); return; } // If second BST is empty, then output is inorder // traversal of first BST if (root2 == NULL) { inorder(root1); return ; } // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (current1 != NULL || !isEmpty(s1) || current2 != NULL || !isEmpty(s2)) { // Following steps follow iterative Inorder Traversal if (current1 != NULL || current2 != NULL ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != NULL) { push(&s1, current1); current1 = current1->left; } if (current2 != NULL) { push(&s2, current2); current2 = current2->left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, print the other tree if (isEmpty(s1)) { while (!isEmpty(s2)) { current2 = pop (&s2); current2->left = NULL; inorder(current2); } return ; } if (isEmpty(s2)) { while (!isEmpty(s1)) { current1 = pop (&s1); current1->left = NULL; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = pop(&s1); current2 = pop(&s2); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1->data < current2->data) { cout<data<<"" ""; current1 = current1->right; push(&s2, current2); current2 = NULL; } else { cout<data<<"" ""; current2 = current2->right; push(&s1, current1); current1 = NULL; } } } } /* Driver program to test above functions */ int main() { node *root1 = NULL, *root2 = NULL; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted nodes of both trees merge(root1, root2); return 0; } //This code is contributed by rathbhupendra",logn,linear "#include using namespace std; // Structure of a BST Node class Node { public: int val; Node* left; Node* right; }; /* Utility function to create a new Binary Tree Node */ Node* newNode(int data) { Node* temp = new Node; temp->val = data; temp->left = nullptr; temp->right = nullptr; return temp; } vector mergeTwoBST(Node* root1, Node* root2) { vector res; stack s1, s2; while (root1 || root2 || !s1.empty() || !s2.empty()) { while (root1) { s1.push(root1); root1 = root1->left; } while (root2) { s2.push(root2); root2 = root2->left; } // Step 3 Case 1:- if (s2.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val)) { root1 = s1.top(); s1.pop(); res.push_back(root1->val); root1 = root1->right; } // Step 3 case 2 :- else { root2 = s2.top(); s2.pop(); res.push_back(root2->val); root2 = root2->right; } } return res; } /* Driver program to test above functions */ int main() { Node *root1 = nullptr, *root2 = nullptr; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted Nodes of both trees vector ans = mergeTwoBST(root1, root2); for (auto it : ans) cout << it << "" ""; return 0; } // This code is contributed by Aditya kumar (adityakumar129)",logn,linear "// C++ program to find minimum value node in binary search // Tree. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct node { int data; struct node* left; struct node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } /* Give a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ struct node* insert(struct node* node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; } } /* Given a non-empty binary search tree, return the minimum data value found in that tree. Note that the entire tree does not need to be searched. */ int minValue(struct node* node) { struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) { current = current->left; } return (current->data); } /* Driver Code*/ int main() { struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); // Function call cout << ""\n Minimum value in BST is "" << minValue(root); getchar(); return 0; } // This code is contributed by Mukul Singh.",linear,linear "// C++ program for an efficient solution to check if // a given array can represent Preorder traversal of // a Binary Search Tree #include using namespace std; bool canRepresentBST(int pre[], int n) { // Create an empty stack stack s; // Initialize current root as minimum possible // value int root = INT_MIN; // Traverse given array for (int i=0; i using namespace std; // We are actually not building the tree void buildBST_helper(int& preIndex, int n, int pre[], int min, int max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(preIndex, n, pre, min, rootData); // build right subtree buildBST_helper(preIndex, n, pre, rootData, max); } // else // return NULL; } bool canRepresentBST(int arr[], int N) { // code here int min = INT_MIN, max = INT_MAX; int preIndex = 0; buildBST_helper(preIndex, N, arr, min, max); return preIndex == N; } // Driver Code int main() { int preorder1[] = { 2, 4, 3 }; /* 2 \ 4 / 3 */ int n1 = sizeof(preorder1) / sizeof(preorder1[0]); if (canRepresentBST(preorder1, n1)) cout << ""\npreorder1 can represent BST""; else cout << ""\npreorder1 can not represent BST :(""; int preorder2[] = { 5, 3, 4, 1, 6, 10 }; int n2 = sizeof(preorder2) / sizeof(preorder2[0]); /* 5 / \ 3 1 \ / \ 4 6 10 */ if (canRepresentBST(preorder2, n2)) cout << ""\npreorder2 can represent BST""; else cout << ""\npreorder2 can not represent BST :(""; int preorder3[] = { 5, 3, 4, 8, 6, 10 }; int n3 = sizeof(preorder3) / sizeof(preorder3[0]); /* 5 / \ 3 8 \ / \ 4 6 10 */ if (canRepresentBST(preorder3, n3)) cout << ""\npreorder3 can represent BST""; else cout << ""\npreorder3 can not represent BST :(""; return 0; } // This code is contributed by Sourashis Mondal",logn,linear "// A recursive CPP program to find // LCA of two nodes n1 and n2. #include using namespace std; class node { public: int data; node *left, *right; }; /* Function to find LCA of n1 and n2. The function assumes that both n1 and n2 are present in BST */ node* lca(node* root, int n1, int n2) { if (root == NULL) return NULL; // If both n1 and n2 are smaller // than root, then LCA lies in left if (root->data > n1 && root->data > n2) return lca(root->left, n1, n2); // If both n1 and n2 are greater than // root, then LCA lies in right if (root->data < n1 && root->data < n2) return lca(root->right, n1, n2); return root; } /* Helper function that allocates a new node with the given data.*/ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = Node->right = NULL; return (Node); } /* Driver code*/ int main() { // Let us construct the BST // shown in the above figure node* root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); // Function calls int n1 = 10, n2 = 14; node* t = lca(root, n1, n2); cout << ""LCA of "" << n1 << "" and "" << n2 << "" is "" << t->data << endl; n1 = 14, n2 = 8; t = lca(root, n1, n2); cout << ""LCA of "" << n1 << "" and "" << n2 << "" is "" << t->data << endl; n1 = 10, n2 = 22; t = lca(root, n1, n2); cout << ""LCA of "" << n1 << "" and "" << n2 << "" is "" << t->data << endl; return 0; } // This code is contributed by rathbhupendra",logn,constant "// A recursive CPP program to find // LCA of two nodes n1 and n2. #include using namespace std; class node { public: int data; node *left, *right; }; /* Function to find LCA of n1 and n2. The function assumes that both n1 and n2 are present in BST */ node* lca(node* root, int n1, int n2) { while (root != NULL) { // If both n1 and n2 are smaller than root, // then LCA lies in left if (root->data > n1 && root->data > n2) root = root->left; // If both n1 and n2 are greater than root, // then LCA lies in right else if (root->data < n1 && root->data < n2) root = root->right; else break; } return root; } /* Helper function that allocates a new node with the given data.*/ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = Node->right = NULL; return (Node); } /* Driver code*/ int main() { // Let us construct the BST // shown in the above figure node* root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); // Function calls int n1 = 10, n2 = 14; node* t = lca(root, n1, n2); cout << ""LCA of "" << n1 << "" and "" << n2 << "" is "" << t->data << endl; n1 = 14, n2 = 8; t = lca(root, n1, n2); cout << ""LCA of "" << n1 << "" and "" << n2 << "" is "" << t->data << endl; n1 = 10, n2 = 22; t = lca(root, n1, n2); cout << ""LCA of "" << n1 << "" and "" << n2 << "" is "" << t->data << endl; return 0; } // This code is contributed by rathbhupendra",constant,constant "#include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node* left; node* right; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; } }; int isBSTUtil(node* node, int min, int max); /* Returns true if the given tree is a binary search tree (efficient version). */ int isBST(node* node) { return (isBSTUtil(node, INT_MIN, INT_MAX)); } /* Returns true if the given tree is a BST and its values are >= min and <= max. */ int isBSTUtil(node* node, int min, int max) { /* an empty tree is BST */ if (node == NULL) return 1; /* false if this node violates the min/max constraint */ if (node->data < min || node->data > max) return 0; /* otherwise check the subtrees recursively, tightening the min or max constraint */ return isBSTUtil(node->left, min, node->data - 1) && // Allow only distinct values isBSTUtil(node->right, node->data + 1, max); // Allow only distinct values } /* Driver code*/ int main() { node* root = new node(4); root->left = new node(2); root->right = new node(5); root->left->left = new node(1); root->left->right = new node(3); // Function call if (isBST(root)) cout << ""Is BST""; else cout << ""Not a BST""; return 0; } // This code is contributed by rathbhupendra",constant,linear "// C++ program to check if a given tree is BST. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; Node(int data) { this->data = data; left = right = NULL; } }; bool isBSTUtil(struct Node* root, Node*& prev) { // traverse the tree in inorder fashion and // keep track of prev node if (root) { if (!isBSTUtil(root->left, prev)) return false; // Allows only distinct valued nodes if (prev != NULL && root->data <= prev->data) return false; prev = root; return isBSTUtil(root->right, prev); } return true; } bool isBST(Node* root) { Node* prev = NULL; return isBSTUtil(root, prev); } /* Driver code*/ int main() { struct Node* root = new Node(3); root->left = new Node(2); root->right = new Node(5); root->left->left = new Node(1); root->left->right = new Node(4); // Function call if (isBST(root)) cout << ""Is BST""; else cout << ""Not a BST""; return 0; }",logn,linear "// A C++ program to check for Identical // BSTs without building the trees #include using namespace std; /* The main function that checks if two arrays a[] and b[] of size n construct same BST. The two values 'min' and 'max' decide whether the call is made for left subtree or right subtree of a parent element. The indexes i1 and i2 are the indexes in (a[] and b[]) after which we search the left or right child. Initially, the call is made for INT_MIN and INT_MAX as 'min' and 'max' respectively, because root has no parent. i1 and i2 are just after the indexes of the parent element in a[] and b[]. */ bool isSameBSTUtil(int a[], int b[], int n, int i1, int i2, int min, int max) { int j, k; /* Search for a value satisfying the constraints of min and max in a[] and b[]. If the parent element is a leaf node then there must be some elements in a[] and b[] satisfying constraint. */ for (j = i1; j < n; j++) if (a[j] > min && a[j] < max) break; for (k = i2; k < n; k++) if (b[k] > min && b[k] < max) break; /* If the parent element is leaf in both arrays */ if (j == n && k == n) return true; /* Return false if any of the following is true a) If the parent element is leaf in one array, but non-leaf in other. b) The elements satisfying constraints are not same. We either search for left child or right child of the parent element (decided by min and max values). The child found must be same in both arrays */ if (((j == n) ^ (k == n)) || a[j] != b[k]) return false; /* Make the current child as parent and recursively check for left and right subtrees of it. Note that we can also pass a[k] in place of a[j] as they are both are same */ return isSameBSTUtil(a, b, n, j + 1, k + 1, a[j], max) && // Right Subtree isSameBSTUtil(a, b, n, j + 1, k + 1, min, a[j]); // Left Subtree } // A wrapper over isSameBSTUtil() bool isSameBST(int a[], int b[], int n) { return isSameBSTUtil(a, b, n, 0, 0, INT_MIN, INT_MAX); } // Driver code int main() { int a[] = { 8, 3, 6, 1, 4, 7, 10, 14, 13 }; int b[] = { 8, 10, 14, 3, 6, 4, 1, 7, 13 }; int n = sizeof(a) / sizeof(a[0]); if (isSameBST(a, b, n)) { cout << ""BSTs are same""; } else { cout << ""BSTs not same""; } return 0; } // This code is contributed by rathbhupendra",linear,quadratic "// CPP code for finding K-th largest Node using O(1) // extra memory and reverse Morris traversal. #include using namespace std; struct Node { int data; struct Node *left, *right; }; // helper function to create a new Node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->right = temp->left = NULL; return temp; } Node* KthLargestUsingMorrisTraversal(Node* root, int k) { Node* curr = root; Node* Klargest = NULL; // count variable to keep count of visited Nodes int count = 0; while (curr != NULL) { // if right child is NULL if (curr->right == NULL) { // first increment count and check if count = k if (++count == k) Klargest = curr; // otherwise move to the left child curr = curr->left; } else { // find inorder successor of current Node Node* succ = curr->right; while (succ->left != NULL && succ->left != curr) succ = succ->left; if (succ->left == NULL) { // set left child of successor to the // current Node succ->left = curr; // move current to its right curr = curr->right; } // restoring the tree back to original binary // search tree removing threaded links else { succ->left = NULL; if (++count == k) Klargest = curr; // move current to its left child curr = curr->left; } } } return Klargest; } int main() { // Your C++ Code /* Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10 */ Node* root = newNode(4); root->left = newNode(2); root->right = newNode(7); root->left->left = newNode(1); root->left->right = newNode(3); root->right->left = newNode(6); root->right->right = newNode(10); cout << ""Finding K-th largest Node in BST : "" << KthLargestUsingMorrisTraversal(root, 2)->data; return 0; }",constant,linear "// C++ program to find k'th largest element in BST #include using namespace std; // A BST node struct Node { int key; Node *left, *right; }; // A function to find int KSmallestUsingMorris(Node *root, int k) { // Count to iterate over elements till we // get the kth smallest number int count = 0; int ksmall = INT_MIN; // store the Kth smallest Node *curr = root; // to store the current node while (curr != NULL) { // Like Morris traversal if current does // not have left child rather than printing // as we did in inorder, we will just // increment the count as the number will // be in an increasing order if (curr->left == NULL) { count++; // if count is equal to K then we found the // kth smallest, so store it in ksmall if (count==k) ksmall = curr->key; // go to current's right child curr = curr->right; } else { // we create links to Inorder Successor and // count using these links Node *pre = curr->left; while (pre->right != NULL && pre->right != curr) pre = pre->right; // building links if (pre->right==NULL) { //link made to Inorder Successor pre->right = curr; curr = curr->left; } // While breaking the links in so made temporary // threaded tree we will check for the K smallest // condition else { // Revert the changes made in if part (break link // from the Inorder Successor) pre->right = NULL; count++; // If count is equal to K then we found // the kth smallest and so store it in ksmall if (count==k) ksmall = curr->key; curr = curr->right; } } } return ksmall; //return the found value } // A utility function to create a new BST node Node *newNode(int item) { Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } /* A utility function to insert a new node with given key in BST */ Node* insert(Node* node, int key) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node; } // Driver Program to test above functions int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); for (int k=1; k<=7; k++) cout << KSmallestUsingMorris(root, k) << "" ""; return 0; }",constant,linear "// C++ program to check if a given array is sorted // or not. #include using namespace std; // Function that returns true if array is Inorder // traversal of any Binary Search Tree or not. bool isInorder(int arr[], int n) { // Array has one or no element if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) // Unsorted pair found if (arr[i-1] > arr[i]) return false; // No unsorted pair found return true; } // Driver code int main() { int arr[] = { 19, 23, 25, 30, 45 }; int n = sizeof(arr)/sizeof(arr[0]); if (isInorder(arr, n)) cout << ""Yesn""; else cout << ""Non""; return 0; }",constant,linear "// CPP program to check if two BSTs contains // same set of elements #include using namespace std; // BST Node struct Node { int data; struct Node* left; struct Node* right; }; // Utility function to create new Node Node* newNode(int val) { Node* temp = new Node; temp->data = val; temp->left = temp->right = NULL; return temp; } // function to insert elements of the // tree to map m void insertToHash(Node* root, unordered_set &s) { if (!root) return; insertToHash(root->left, s); s.insert(root->data); insertToHash(root->right, s); } // function to check if the two BSTs contain // same set of elements bool checkBSTs(Node* root1, Node* root2) { // Base cases if (!root1 && !root2) return true; if ((root1 && !root2) || (!root1 && root2)) return false; // Create two hash sets and store // elements both BSTs in them. unordered_set s1, s2; insertToHash(root1, s1); insertToHash(root2, s2); // Return true if both hash sets // contain same elements. return (s1 == s2); } // Driver program to check above functions int main() { // First BST Node* root1 = newNode(15); root1->left = newNode(10); root1->right = newNode(20); root1->left->left = newNode(5); root1->left->right = newNode(12); root1->right->right = newNode(25); // Second BST Node* root2 = newNode(15); root2->left = newNode(12); root2->right = newNode(20); root2->left->left = newNode(5); root2->left->left->right = newNode(10); root2->right->right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) cout << ""YES""; else cout << ""NO""; return 0; }",linear,linear "// CPP program to check if two BSTs contains // same set of elements #include using namespace std; // BST Node struct Node { int data; struct Node* left; struct Node* right; }; // Utility function to create new Node Node* newNode(int val) { Node* temp = new Node; temp->data = val; temp->left = temp->right = NULL; return temp; } // function to insert elements of the // tree to map m void storeInorder(Node* root, vector &v) { if (!root) return; storeInorder(root->left, v); v.push_back(root->data); storeInorder(root->right, v); } // function to check if the two BSTs contain // same set of elements bool checkBSTs(Node* root1, Node* root2) { // Base cases if (!root1 && !root2) return true; if ((root1 && !root2) || (!root1 && root2)) return false; // Create two vectors and store // inorder traversals of both BSTs // in them. vector v1, v2; storeInorder(root1, v1); storeInorder(root2, v2); // Return true if both vectors are // identical return (v1 == v2); } // Driver program to check above functions int main() { // First BST Node* root1 = newNode(15); root1->left = newNode(10); root1->right = newNode(20); root1->left->left = newNode(5); root1->left->right = newNode(12); root1->right->right = newNode(25); // Second BST Node* root2 = newNode(15); root2->left = newNode(12); root2->right = newNode(20); root2->left->left = newNode(5); root2->left->left->right = newNode(10); root2->right->right = newNode(25); // check if two BSTs have same set of elements if (checkBSTs(root1, root2)) cout << ""YES""; else cout << ""NO""; return 0; }",linear,linear "// C++ implementation to count pairs from two // BSTs whose sum is equal to a given value x #include using namespace std; // structure of a node of BST struct Node { int data; Node* left, *right; }; // function to create and return a node of BST Node* getNode(int data) { // allocate space for the node Node* new_node = (Node*)malloc(sizeof(Node)); // put in the data new_node->data = data; new_node->left = new_node->right = NULL; } // function to count pairs from two BSTs // whose sum is equal to a given value x int countPairs(Node* root1, Node* root2, int x) { // if either of the tree is empty if (root1 == NULL || root2 == NULL) return 0; // stack 'st1' used for the inorder // traversal of BST 1 // stack 'st2' used for the reverse // inorder traversal of BST 2 stack st1, st2; Node* top1, *top2; int count = 0; // the loop will break when either of two // traversals gets completed while (1) { // to find next node in inorder // traversal of BST 1 while (root1 != NULL) { st1.push(root1); root1 = root1->left; } // to find next node in reverse // inorder traversal of BST 2 while (root2 != NULL) { st2.push(root2); root2 = root2->right; } // if either gets empty then corresponding // tree traversal is completed if (st1.empty() || st2.empty()) break; top1 = st1.top(); top2 = st2.top(); // if the sum of the node's is equal to 'x' if ((top1->data + top2->data) == x) { // increment count count++; // pop nodes from the respective stacks st1.pop(); st2.pop(); // insert next possible node in the // respective stacks root1 = top1->right; root2 = top2->left; } // move to next possible node in the // inorder traversal of BST 1 else if ((top1->data + top2->data) < x) { st1.pop(); root1 = top1->right; } // move to next possible node in the // reverse inorder traversal of BST 2 else { st2.pop(); root2 = top2->left; } } // required count of pairs return count; } // Driver program to test above int main() { // formation of BST 1 Node* root1 = getNode(5); /* 5 */ root1->left = getNode(3); /* / \ */ root1->right = getNode(7); /* 3 7 */ root1->left->left = getNode(2); /* / \ / \ */ root1->left->right = getNode(4); /* 2 4 6 8 */ root1->right->left = getNode(6); root1->right->right = getNode(8); // formation of BST 2 Node* root2 = getNode(10); /* 10 */ root2->left = getNode(6); /* / \ */ root2->right = getNode(15); /* 6 15 */ root2->left->left = getNode(3); /* / \ / \ */ root2->left->right = getNode(8); /* 3 8 11 18 */ root2->right->left = getNode(11); root2->right->right = getNode(18); int x = 16; cout << ""Pairs = "" << countPairs(root1, root2, x); return 0; }",logn,linear "/* C++ program to find the median of BST in O(n) time and O(1) space*/ #include using namespace std; /* A binary search tree Node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left, *right; }; // A utility function to create a new BST node struct Node *newNode(int item) { struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } /* A utility function to insert a new node with given key in BST */ struct Node* insert(struct Node* node, int key) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->data) node->left = insert(node->left, key); else if (key > node->data) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node; } /* Function to count nodes in a binary search tree using Morris Inorder traversal*/ int counNodes(struct Node *root) { struct Node *current, *pre; // Initialise count of nodes as 0 int count = 0; if (root == NULL) return count; current = root; while (current != NULL) { if (current->left == NULL) { // Count node if its left is NULL count++; // Move to its right current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if(pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; // Increment count if the current // node is to be visited count++; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return count; } /* Function to find median in O(n) time and O(1) space using Morris Inorder traversal*/ int findMedian(struct Node *root) { if (root == NULL) return 0; int count = counNodes(root); int currCount = 0; struct Node *current = root, *pre, *prev; while (current != NULL) { if (current->left == NULL) { // count current node currCount++; // check if current node is the median // Odd case if (count % 2 != 0 && currCount == (count+1)/2) return current->data; // Even case else if (count % 2 == 0 && currCount == (count/2)+1) return (prev->data + current->data)/2; // Update prev for even no. of nodes prev = current; //Move to the right current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecessor */ else { pre->right = NULL; prev = pre; // Count current node currCount++; // Check if the current node is the median if (count % 2 != 0 && currCount == (count+1)/2 ) return current->data; else if (count%2==0 && currCount == (count/2)+1) return (prev->data+current->data)/2; // update prev node for the case of even // no. of nodes prev = current; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ } /* Driver program to test above functions*/ int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ struct Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout << ""\nMedian of BST is "" << findMedian(root); return 0; }",constant,linear "// C++ program to find largest BST in a // Binary Tree. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Information to be returned by every // node in bottom up traversal. struct Info { // Size of subtree int sz; // Min value in subtree int max; // Max value in subtree int min; // Size of largest BST which // is subtree of current node int ans; // If subtree is BST bool isBST; }; // Returns Information about subtree. The // Information also includes size of largest // subtree which is a BST. Info largestBSTBT(Node* root) { // Base cases : When tree is empty or it has // one child. if (root == NULL) return { 0, INT_MIN, INT_MAX, 0, true }; if (root->left == NULL && root->right == NULL) return { 1, root->data, root->data, 1, true }; // Recur for left subtree and right subtrees Info l = largestBSTBT(root->left); Info r = largestBSTBT(root->right); // Create a return variable and initialize its // size. Info ret; ret.sz = (1 + l.sz + r.sz); // If whole tree rooted under current root is // BST. if (l.isBST && r.isBST && l.max < root->data && r.min > root->data) { ret.min = min(l.min, root->data); ret.max = max(r.max, root->data); // Update answer for tree rooted under // current 'root' ret.ans = l.ans + r.ans + 1; ret.isBST = true; return ret; } // If whole tree is not BST, return maximum // of left and right subtrees ret.ans = max(l.ans, r.ans); ret.isBST = false; return ret; } /* Driver program to test above functions*/ int main() { /* Let us construct the following Tree 60 / \ 65 70 / 50 */ struct Node* root = newNode(60); root->left = newNode(65); root->right = newNode(70); root->left->left = newNode(50); printf("" Size of the largest BST is %d\n"", largestBSTBT(root).ans); return 0; } // This code is contributed by Vivek Garg in a // comment on below set 1. // www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/ // This code is updated by Naman Sharma",linear,linear "// A C++ program to remove BST keys // outside the given range #include using namespace std; // A BST node has key, and left and right pointers struct node { int key; struct node *left; struct node *right; }; // Removes all nodes having value outside the // given range and returns the root of modified tree node* removeOutsideRange(node *root, int min, int max) { // Base Case if (root == NULL) return NULL; // First fix the left and right subtrees of root root->left = removeOutsideRange(root->left, min, max); root->right = removeOutsideRange(root->right, min, max); // Now fix the root. There are 2 possible cases // for root 1.a) Root's key is smaller than min // value (root is not in range) if (root->key < min) { node *rChild = root->right; delete root; return rChild; } // 1.b) Root's key is greater than max value // (root is not in range) if (root->key > max) { node *lChild = root->left; delete root; return lChild; } // 2. Root is in range return root; } // A utility function to create a new BST // node with key as given num node* newNode(int num) { node* temp = new node; temp->key = num; temp->left = temp->right = NULL; return temp; } // A utility function to insert a given key to BST node* insert(node* root, int key) { if (root == NULL) return newNode(key); if (root->key > key) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root; } // Utility function to traverse the binary // tree after conversion void inorderTraversal(node* root) { if (root) { inorderTraversal( root->left ); cout << root->key << "" ""; inorderTraversal( root->right ); } } // Driver program to test above functions int main() { node* root = NULL; root = insert(root, 6); root = insert(root, -13); root = insert(root, 14); root = insert(root, -8); root = insert(root, 15); root = insert(root, 13); root = insert(root, 7); cout << ""Inorder traversal of the given tree is: ""; inorderTraversal(root); root = removeOutsideRange(root, -10, 13); cout << ""\nInorder traversal of the modified tree is: ""; inorderTraversal(root); return 0; }",constant,linear "// C++ program to print BST in given range #include using namespace std; /* A tree node structure */ class node { public: int data; node *left; node *right; }; /* The functions prints all the keys which in the given range [k1..k2]. The function assumes than k1 < k2 */ void Print(node *root, int k1, int k2) { /* base case */ if ( NULL == root ) return; /* Since the desired o/p is sorted, recurse for left subtree first If root->data is greater than k1, then only we can get o/p keys in left subtree */ if ( k1 < root->data ) Print(root->left, k1, k2); /* if root's data lies in range, then prints root's data */ if ( k1 <= root->data && k2 >= root->data ) cout<data<<"" ""; /* recursively call the right subtree */ Print(root->right, k1, k2); } /* Utility function to create a new Binary Tree node */ node* newNode(int data) { node *temp = new node(); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } /* Driver code */ int main() { node *root = new node(); int k1 = 10, k2 = 25; /* Constructing tree given in the above figure */ root = newNode(20); root->left = newNode(8); root->right = newNode(22); root->left->left = newNode(4); root->left->right = newNode(12); Print(root, k1, k2); return 0; } // This code is contributed by rathbhupendra",logn,linear "// CPP code to print BST keys in given Range in // constant space using Morris traversal. #include using namespace std; struct node { int data; struct node *left, *right; }; // Function to print the keys in range void RangeTraversal(node* root, int n1, int n2) { if (!root) return; node* curr = root; while (curr) { if (curr->left == NULL) { // check if current node // lies between n1 and n2 if (curr->data <= n2 && curr->data >= n1) { cout << curr->data << "" ""; } curr = curr->right; } else { node* pre = curr->left; // finding the inorder predecessor- // inorder predecessor is the right // most in left subtree or the left // child, i.e in BST it is the // maximum(right most) in left subtree. while (pre->right != NULL && pre->right != curr) pre = pre->right; if (pre->right == NULL) { pre->right = curr; curr = curr->left; } else { pre->right = NULL; // check if current node lies // between n1 and n2 if (curr->data <= n2 && curr->data >= n1) { cout << curr->data << "" ""; } curr = curr->right; } } } } // Helper function to create a new node node* newNode(int data) { node* temp = new node; temp->data = data; temp->right = temp->left = NULL; return temp; } // Driver Code int main() { /* Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10 */ node* root = newNode(4); root->left = newNode(2); root->right = newNode(7); root->left->left = newNode(1); root->left->right = newNode(3); root->right->left = newNode(6); root->right->right = newNode(10); RangeTraversal(root, 4, 12); return 0; }",constant,linear "// C++ program to count BST nodes within a given range #include using namespace std; // A BST node struct node { int data; struct node* left, *right; }; // Utility function to create new node node *newNode(int data) { node *temp = new node; temp->data = data; temp->left = temp->right = NULL; return (temp); } // Returns count of nodes in BST in range [low, high] int getCount(node *root, int low, int high) { // Base case if (!root) return 0; // Special Optional case for improving efficiency if (root->data == high && root->data == low) return 1; // If current node is in range, then include it in count and // recur for left and right children of it if (root->data <= high && root->data >= low) return 1 + getCount(root->left, low, high) + getCount(root->right, low, high); // If current node is smaller than low, then recur for right // child else if (root->data < low) return getCount(root->right, low, high); // Else recur for left child else return getCount(root->left, low, high); } // Driver program int main() { // Let us construct the BST shown in the above figure node *root = newNode(10); root->left = newNode(5); root->right = newNode(50); root->left->left = newNode(1); root->right->left = newNode(40); root->right->right = newNode(100); /* Let us constructed BST shown in above example 10 / \ 5 50 / / \ 1 40 100 */ int l = 5; int h = 45; cout << ""Count of nodes between ["" << l << "", "" << h << ""] is "" << getCount(root, l, h); return 0; }",linear,constant "// c++ program to find Sum Of All Elements smaller // than or equal to Kth Smallest Element In BST #include using namespace std; /* Binary tree Node */ struct Node { int data; Node* left, * right; }; // utility function new Node of BST struct Node *createNode(int data) { Node * new_Node = new Node; new_Node->left = NULL; new_Node->right = NULL; new_Node->data = data; return new_Node; } // A utility function to insert a new Node // with given key in BST and also maintain lcount ,Sum struct Node * insert(Node *root, int key) { // If the tree is empty, return a new Node if (root == NULL) return createNode(key); // Otherwise, recur down the tree if (root->data > key) root->left = insert(root->left, key); else if (root->data < key) root->right = insert(root->right, key); // return the (unchanged) Node pointer return root; } // function return sum of all element smaller than // and equal to Kth smallest element int ksmallestElementSumRec(Node *root, int k, int &count) { // Base cases if (root == NULL) return 0; if (count > k) return 0; // Compute sum of elements in left subtree int res = ksmallestElementSumRec(root->left, k, count); if (count >= k) return res; // Add root's data res += root->data; // Add current Node count++; if (count >= k) return res; // If count is less than k, return right subtree Nodes return res + ksmallestElementSumRec(root->right, k, count); } // Wrapper over ksmallestElementSumRec() int ksmallestElementSum(struct Node *root, int k) { int count = 0; return ksmallestElementSumRec(root, k, count); } /* Driver program to test above functions */ int main() { /* 20 / \ 8 22 / \ 4 12 / \ 10 14 */ Node *root = NULL; root = insert(root, 20); root = insert(root, 8); root = insert(root, 4); root = insert(root, 12); root = insert(root, 10); root = insert(root, 14); root = insert(root, 22); int k = 3; cout << ksmallestElementSum(root, k) < using namespace std; // BST Node struct Node { int key; struct Node *left, *right; }; // This function finds predecessor and successor of key in BST. // It sets pre and suc as predecessor and successor respectively void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) { // Base case if (root == NULL) return ; // If key is present at root if (root->key == key) { // the maximum value in left subtree is predecessor if (root->left != NULL) { Node* tmp = root->left; while (tmp->right) tmp = tmp->right; pre = tmp ; } // the minimum value in right subtree is successor if (root->right != NULL) { Node* tmp = root->right ; while (tmp->left) tmp = tmp->left ; suc = tmp ; } return ; } // If key is smaller than root's key, go to left subtree if (root->key > key) { suc = root ; findPreSuc(root->left, pre, suc, key) ; } else // go to right subtree { pre = root ; findPreSuc(root->right, pre, suc, key) ; } } // A utility function to create a new BST node Node *newNode(int item) { Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } /* A utility function to insert a new node with given key in BST */ Node* insert(Node* node, int key) { if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } // Driver program to test above function int main() { int key = 65; //Key to be searched in BST /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); Node* pre = NULL, *suc = NULL; findPreSuc(root, pre, suc, key); if (pre != NULL) cout << ""Predecessor is "" << pre->key << endl; else cout << ""No Predecessor""; if (suc != NULL) cout << ""Successor is "" << suc->key; else cout << ""No Successor""; return 0; }",constant,logn "// CPP code for inorder successor // and predecessor of tree #include #include using namespace std; struct Node { int data; Node* left,*right; }; // Function to return data Node* getnode(int info) { Node* p = (Node*)malloc(sizeof(Node)); p->data = info; p->right = NULL; p->left = NULL; return p; } /* since inorder traversal results in ascending order visit to node , we can store the values of the largest no which is smaller than a (predecessor) and smallest no which is large than a (successor) using inorder traversal */ void find_p_s(Node* root,int a, Node** p, Node** q) { // If root is null return if(!root) return ; // traverse the left subtree find_p_s(root->left, a, p, q); // root data is greater than a if(root&&root->data > a) { // q stores the node whose data is greater // than a and is smaller than the previously // stored data in *q which is successor if((!*q) || (*q) && (*q)->data > root->data) *q = root; } // if the root data is smaller than // store it in p which is predecessor else if(root && root->data < a) { *p = root; } // traverse the right subtree find_p_s(root->right, a, p, q); } // Driver code int main() { Node* root1 = getnode(50); root1->left = getnode(20); root1->right = getnode(60); root1->left->left = getnode(10); root1->left->right = getnode(30); root1->right->left = getnode(55); root1->right->right = getnode(70); Node* p = NULL, *q = NULL; find_p_s(root1, 55, &p, &q); if(p) cout << p->data; if(q) cout << "" "" << q->data; return 0; }",linear,linear "// C++ program to find predecessor // and successor in a BST #include using namespace std; // BST Node struct Node { int key; struct Node *left, *right; }; // Function that finds predecessor and successor of key in BST. void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) { if (root == NULL) return; // Search for given key in BST. while (root != NULL) { // If root is given key. if (root->key == key) { // the minimum value in right subtree // is successor. if (root->right) { suc = root->right; while (suc->left) suc = suc->left; } // the maximum value in left subtree // is predecessor. if (root->left) { pre = root->left; while (pre->right) pre = pre->right; } return; } // If key is greater than root, then // key lies in right subtree. Root // could be predecessor if left // subtree of key is null. else if (root->key < key) { pre = root; root = root->right; } // If key is smaller than root, then // key lies in left subtree. Root // could be successor if right // subtree of key is null. else { suc = root; root = root->left; } } } // A utility function to create a new BST node Node* newNode(int item) { Node* temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp; } // A utility function to insert // a new node with given key in BST Node* insert(Node* node, int key) { if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); return node; } // Driver program to test above function int main() { int key = 65; // Key to be searched in BST /* Let us create following BST 50 / \ / \ 30 70 / \ / \ / \ / \ 20 40 60 80 */ Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); Node *pre = NULL, *suc = NULL; findPreSuc(root, pre, suc, key); if (pre != NULL) cout << ""Predecessor is "" << pre->key << endl; else cout << ""-1""; if (suc != NULL) cout << ""Successor is "" << suc->key; else cout << ""-1""; return 0; }",constant,linear "// CPP program to find a pair with // given sum using hashing #include using namespace std; struct Node { int data; struct Node *left, *right; }; Node* NewNode(int data) { Node* temp = (Node*)malloc(sizeof(Node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } Node* insert(Node* root, int key) { if (root == NULL) return NewNode(key); if (key < root->data) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root; } bool findpairUtil(Node* root, int sum, unordered_set& set) { if (root == NULL) return false; if (findpairUtil(root->left, sum, set)) return true; if (set.find(sum - root->data) != set.end()) { cout << ""Pair is found ("" << sum - root->data << "", "" << root->data << "")"" << endl; return true; } else set.insert(root->data); return findpairUtil(root->right, sum, set); } void findPair(Node* root, int sum) { unordered_set set; if (!findpairUtil(root, sum, set)) cout << ""Pairs do not exit"" << endl; } // Driver code int main() { Node* root = NULL; root = insert(root, 15); root = insert(root, 10); root = insert(root, 20); root = insert(root, 8); root = insert(root, 12); root = insert(root, 16); root = insert(root, 25); root = insert(root, 10); int sum = 28; findPair(root, sum); return 0; }",linear,linear "// C++ program to find pairs with given sum such // that one element of pair exists in one BST and // other in other BST. #include using namespace std; // A binary Tree node struct Node { int data; struct Node *left, *right; }; // A utility function to create a new BST node // with key as given num struct Node* newNode(int num) { struct Node* temp = new Node; temp->data = num; temp->left = temp->right = NULL; return temp; } // A utility function to insert a given key to BST Node* insert(Node* root, int key) { if (root == NULL) return newNode(key); if (root->data > key) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root; } // store storeInorder traversal in auxiliary array void storeInorder(Node *ptr, vector &vect) { if (ptr==NULL) return; storeInorder(ptr->left, vect); vect.push_back(ptr->data); storeInorder(ptr->right, vect); } // Function to find pair for given sum in different bst // vect1[] --> stores storeInorder traversal of first bst // vect2[] --> stores storeInorder traversal of second bst void pairSumUtil(vector &vect1, vector &vect2, int sum) { // Initialize two indexes to two different corners // of two vectors. int left = 0; int right = vect2.size() - 1; // find pair by moving two corners. while (left < vect1.size() && right >= 0) { // If we found a pair if (vect1[left] + vect2[right] == sum) { cout << ""("" << vect1[left] << "", "" << vect2[right] << ""), ""; left++; right--; } // If sum is more, move to higher value in // first vector. else if (vect1[left] + vect2[right] < sum) left++; // If sum is less, move to lower value in // second vector. else right--; } } // Prints all pairs with given ""sum"" such that one // element of pair is in tree with root1 and other // node is in tree with root2. void pairSum(Node *root1, Node *root2, int sum) { // Store inorder traversals of two BSTs in two // vectors. vector vect1, vect2; storeInorder(root1, vect1); storeInorder(root2, vect2); // Now the problem reduces to finding a pair // with given sum such that one element is in // vect1 and other is in vect2. pairSumUtil(vect1, vect2, sum); } // Driver program to run the case int main() { // first BST struct Node* root1 = NULL; root1 = insert(root1, 8); root1 = insert(root1, 10); root1 = insert(root1, 3); root1 = insert(root1, 6); root1 = insert(root1, 1); root1 = insert(root1, 5); root1 = insert(root1, 7); root1 = insert(root1, 14); root1 = insert(root1, 13); // second BST struct Node* root2 = NULL; root2 = insert(root2, 5); root2 = insert(root2, 18); root2 = insert(root2, 2); root2 = insert(root2, 1); root2 = insert(root2, 3); root2 = insert(root2, 4); int sum = 10; pairSum(root1, root2, sum); return 0; }",linear,linear "// Recursive C++ program to find key closest to k // in given Binary Search Tree. #include using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */ struct Node { int key; struct Node* left, *right; }; /* Utility that allocates a new node with the given key and NULL left and right pointers. */ struct Node* newnode(int key) { struct Node* node = new (struct Node); node->key = key; node->left = node->right = NULL; return (node); } // Function to find node with minimum absolute // difference with given K // min_diff --> minimum difference till now // min_diff_key --> node having minimum absolute // difference with K void maxDiffUtil(struct Node *ptr, int k, int &min_diff, int &min_diff_key) { if (ptr == NULL) return ; // If k itself is present if (ptr->key == k) { min_diff_key = k; return; } // update min_diff and min_diff_key by checking // current node value if (min_diff > abs(ptr->key - k)) { min_diff = abs(ptr->key - k); min_diff_key = ptr->key; } // if k is less than ptr->key then move in // left subtree else in right subtree if (k < ptr->key) maxDiffUtil(ptr->left, k, min_diff, min_diff_key); else maxDiffUtil(ptr->right, k, min_diff, min_diff_key); } // Wrapper over maxDiffUtil() int maxDiff(Node *root, int k) { // Initialize minimum difference int min_diff = INT_MAX, min_diff_key = -1; // Find value of min_diff_key (Closest key // in tree with k) maxDiffUtil(root, k, min_diff, min_diff_key); return min_diff_key; } // Driver program to run the case int main() { struct Node *root = newnode(9); root->left = newnode(4); root->right = newnode(17); root->left->left = newnode(3); root->left->right = newnode(6); root->left->right->left = newnode(5); root->left->right->right = newnode(7); root->right->right = newnode(22); root->right->right->left = newnode(20); int k = 18; cout << maxDiff(root, k); return 0; }",constant,constant "// C++ program to find largest BST in a Binary Tree. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; Node(int val) { this->data = val; left = NULL; right = NULL; } }; vector largestBSTBT(Node* root) { // Base cases : When tree is empty or it has one child. if (root == NULL) return {INT_MAX, INT_MIN, 0}; if (root->left == NULL && root->right == NULL) return {root->data, root->data, 1}; // Recur for left subtree and right subtrees vector left = largestBSTBT(root->left); vector right = largestBSTBT(root->right); // Create a return variable and initialize its size. vector ans(3, 0); // If whole tree rooted under current root is BST. if ((left[1] < root->data) && (right[0] > root->data)) { ans[0] = min(left[0], min(right[0], root->data)); ans[1] = max(right[1], max(left[1], root->data)); // Update answer for tree rooted under current 'root' ans[2] = 1 + left[2] + right[2]; return ans; } // If whole tree is not BST, return maximum of left and right subtrees ans[0] = INT_MIN; ans[1] = INT_MAX; ans[2] = max(left[2], right[2]); return ans; } int largestBSTBTutil(Node *root) { return largestBSTBT(root)[2]; } // Driver Function int main() { /* Let us construct the following Tree 50 / \ 75 45 / 45 */ struct Node *root = new Node(50); root->left = new Node(75); root->right = new Node(45); root->left->left = new Node(40); printf("" Size of the largest BST is %d\n"", largestBSTBTutil(root)); return 0; } // This Code is cuntributed by Ajay Makvana",linear,linear "// C++ program to add all greater // values in every node of BST #include using namespace std; class Node { public: int data; Node *left, *right; }; // A utility function to create // a new BST node Node* newNode(int item) { Node* temp = new Node(); temp->data = item; temp->left = temp->right = NULL; return temp; } // Recursive function to add all // greater values in every node void modifyBSTUtil(Node* root, int* sum) { // Base Case if (root == NULL) return; // Recur for right subtree modifyBSTUtil(root->right, sum); // Now *sum has sum of nodes // in right subtree, add // root->data to sum and // update root->data *sum = *sum + root->data; root->data = *sum; // Recur for left subtree modifyBSTUtil(root->left, sum); } // A wrapper over modifyBSTUtil() void modifyBST(Node* root) { int sum = 0; modifyBSTUtil(root, ∑); } // A utility function to do // inorder traversal of BST void inorder(Node* root) { if (root != NULL) { inorder(root->left); cout << root->data << "" ""; inorder(root->right); } } /* A utility function to insert a new node with given data in BST */ Node* insert(Node* node, int data) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(data); /* Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; } // Driver code int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); modifyBST(root); // print inorder traversal of the modified BST inorder(root); return 0; } // This code is contributed by rathbhupendra",constant,linear "/* C++ program to convert a Binary Tree to Threaded Tree */ #include using namespace std; /* Structure of a node in threaded binary tree */ struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer is a // normal right pointer or a pointer to inorder // successor. bool isThreaded; }; // Helper function to put the Nodes in inorder into queue void populateQueue(Node* root, std::queue* q) { if (root == NULL) return; if (root->left) populateQueue(root->left, q); q->push(root); if (root->right) populateQueue(root->right, q); } // Function to traverse queue, and make tree threaded void createThreadedUtil(Node* root, std::queue* q) { if (root == NULL) return; if (root->left) createThreadedUtil(root->left, q); q->pop(); if (root->right) createThreadedUtil(root->right, q); // If right pointer is NULL, link it to the // inorder successor and set 'isThreaded' bit. else { root->right = q->front(); root->isThreaded = true; } } // This function uses populateQueue() and // createThreadedUtil() to convert a given binary tree // to threaded tree. void createThreaded(Node* root) { // Create a queue to store inorder traversal std::queue q; // Store inorder traversal in queue populateQueue(root, &q); // Link NULL right pointers to inorder successor createThreadedUtil(root, &q); } // A utility function to find leftmost node in a binary // tree rooted with 'root'. This function is used in // inOrder() Node* leftMost(Node* root) { while (root != NULL && root->left != NULL) root = root->left; return root; } // Function to do inorder traversal of a threaded binary // tree void inOrder(Node* root) { if (root == NULL) return; // Find the leftmost node in Binary Tree Node* cur = leftMost(root); while (cur != NULL) { cout << cur->key << "" ""; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right // subtree cur = leftMost(cur->right); } } // A utility function to create a new node Node* newNode(int key) { Node* temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp; } // Driver program to test above functions int main() { /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << ""Inorder traversal of created threaded tree "" ""is\n""; inOrder(root); return 0; }",linear,linear "/* C++ program to convert a Binary Tree to Threaded Tree */ #include using namespace std; /* Structure of a node in threaded binary tree */ struct Node { int key; Node *left, *right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. bool isThreaded; }; // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. Node *createThreaded(Node *root) { // Base cases : Tree is empty or has single // node if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) return root; // Find predecessor if it exists if (root->left != NULL) { // Find predecessor of root (Rightmost // child in left subtree) Node* l = createThreaded(root->left); // Link a thread from predecessor to // root. l->right = root; l->isThreaded = true; } // If current node is rightmost child if (root->right == NULL) return root; // Recur for right subtree. return createThreaded(root->right); } // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() Node *leftMost(Node *root) { while (root != NULL && root->left != NULL) root = root->left; return root; } // Function to do inorder traversal of a threadded // binary tree void inOrder(Node *root) { if (root == NULL) return; // Find the leftmost node in Binary Tree Node *cur = leftMost(root); while (cur != NULL) { cout << cur->key << "" ""; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right subtree cur = leftMost(cur->right); } } // A utility function to create a new node Node *newNode(int key) { Node *temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp; } // Driver program to test above functions int main() { /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << ""Inorder traversal of created "" ""threaded tree is\n""; inOrder(root); return 0; }",constant,linear "// C++ program to print BST in given range #include using namespace std; /* A Binary Tree node */ class TNode { public: int data; TNode* left; TNode* right; }; TNode* newNode(int data); /* A function that constructs Balanced Binary Search Tree from a sorted array */ TNode* sortedArrayToBST(int arr[], int start, int end) { /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; TNode *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid + 1, end); return root; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ TNode* newNode(int data) { TNode* node = new TNode(); node->data = data; node->left = NULL; node->right = NULL; return node; } /* A utility function to print preorder traversal of BST */ void preOrder(TNode* node) { if (node == NULL) return; cout << node->data << "" ""; preOrder(node->left); preOrder(node->right); } // Driver Code int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); /* Convert List to BST */ TNode *root = sortedArrayToBST(arr, 0, n-1); cout << ""PreOrder Traversal of constructed BST \n""; preOrder(root); return 0; } // This code is contributed by rathbhupendra",logn,linear "/* CPP program to check if a tree is height-balanced or not */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; Node(int d) { int data = d; left = right = NULL; } }; // Function to calculate the height of a tree int height(Node* node) { // base case tree is empty if (node == NULL) return 0; // If tree is not empty then // height = 1 + max of left height // and right heights return 1 + max(height(node->left), height(node->right)); } // Returns true if binary tree // with root as root is height-balanced bool isBalanced(Node* root) { // for height of left subtree int lh; // for height of right subtree int rh; // If tree is empty then return true if (root == NULL) return 1; // Get the height of left and right sub trees lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; // If we reach here then tree is not height-balanced return 0; } // Driver code int main() { Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->left->left->left = new Node(8); if (isBalanced(root)) cout << ""Tree is balanced""; else cout << ""Tree is not balanced""; return 0; } // This code is contributed by rathbhupendra",linear,quadratic "// C++ Code for the above approach #include using namespace std; /* A binary tree node has data, a pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; }; // Function to return a new Node Node* newNode(int data) { Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Function to convert bst to // a doubly linked list void bstTodll(Node* root, Node*& head) { // if root is NULL if (!root) return; // Convert right subtree recursively bstTodll(root->right, head); // Update root root->right = head; // if head is not NULL if (head) { // Update left of the head head->left = root; } // Update head head = root; // Convert left subtree recursively bstTodll(root->left, head); } // Function to merge two sorted linked list Node* mergeLinkedList(Node* head1, Node* head2) { /*Create head and tail for result list*/ Node* head = NULL; Node* tail = NULL; while (head1 && head2) { if (head1->data < head2->data) { if (!head) head = head1; else { tail->right = head1; head1->left = tail; } tail = head1; head1 = head1->right; } else { if (!head) head = head2; else { tail->right = head2; head2->left = tail; } tail = head2; head2 = head2->right; } } while (head1) { tail->right = head1; head1->left = tail; tail = head1; head1 = head1->right; } while (head2) { tail->right = head2; head2->left = tail; tail = head2; head2 = head2->right; } // Return the created DLL return head; } // function to convert list to bst Node* sortedListToBST(Node*& head, int n) { // if no element is left or head is null if (n <= 0 || !head) return NULL; // Create left part from the list recursively Node* left = sortedListToBST(head, n / 2); Node* root = head; root->left = left; head = head->right; // Create left part from the list recursively root->right = sortedListToBST(head, n - (n / 2) - 1); // Return the root of BST return root; } // This function merges two balanced BSTs Node* mergeTrees(Node* root1, Node* root2, int m, int n) { // Convert BSTs into sorted Doubly Linked Lists Node* head1 = NULL; bstTodll(root1, head1); head1->left = NULL; Node* head2 = NULL; bstTodll(root2, head2); head2->left = NULL; // Merge the two sorted lists into one Node* head = mergeLinkedList(head1, head2); // Construct a tree from the merged lists return sortedListToBST(head, m + n); } void printInorder(Node* node) { // if current node is NULL if (!node) { return; } printInorder(node->left); // Print node of current data cout << node->data << "" ""; printInorder(node->right); } /* Driver code*/ int main() { /* Create following tree as first balanced BST 100 / \ 50 300 / \ 20 70 */ Node* root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \ 40 120 */ Node* root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); // Function Call Node* mergedTree = mergeTrees(root1, root2, 5, 3); cout << ""Following is Inorder traversal of the merged "" ""tree \n""; printInorder(mergedTree); return 0; } // This code is contributed by Tapesh(tapeshdua420)",constant,linear "// Two nodes in the BST's swapped, correct the BST. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct node { int data; struct node *left, *right; }; // A utility function to swap two integers void swap( int* a, int* b ) { int t = *a; *a = *b; *b = t; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node *)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } // This function does inorder traversal to find out the two swapped nodes. // It sets three pointers, first, middle and last. If the swapped nodes are // adjacent to each other, then first and middle contain the resultant nodes // Else, first and last contain the resultant nodes void correctBSTUtil( struct node* root, struct node** first, struct node** middle, struct node** last, struct node** prev ) { if( root ) { // Recur for the left subtree correctBSTUtil( root->left, first, middle, last, prev ); // If this node is smaller than the previous node, it's violating // the BST rule. if (*prev && root->data < (*prev)->data) { // If this is first violation, mark these two nodes as // 'first' and 'middle' if ( !*first ) { *first = *prev; *middle = root; } // If this is second violation, mark this node as last else *last = root; } // Mark this node as previous *prev = root; // Recur for the right subtree correctBSTUtil( root->right, first, middle, last, prev ); } } // A function to fix a given BST where two nodes are swapped. This // function uses correctBSTUtil() to find out two nodes and swaps the // nodes to fix the BST void correctBST( struct node* root ) { // Initialize pointers needed for correctBSTUtil() struct node *first, *middle, *last, *prev; first = middle = last = prev = NULL; // Set the pointers to find out two nodes correctBSTUtil( root, &first, &middle, &last, &prev ); // Fix (or correct) the tree if( first && last ) swap( &(first->data), &(last->data) ); else if( first && middle ) // Adjacent nodes swapped swap( &(first->data), &(middle->data) ); // else nodes have not been swapped, passed tree is really BST. } /* A utility function to print Inorder traversal */ void printInorder(struct node* node) { if (node == NULL) return; printInorder(node->left); cout <<"" ""<< node->data; printInorder(node->right); } /* Driver program to test above functions*/ int main() { /* 6 / \ 10 2 / \ / \ 1 3 7 12 10 and 2 are swapped */ struct node *root = newNode(6); root->left = newNode(10); root->right = newNode(2); root->left->left = newNode(1); root->left->right = newNode(3); root->right->right = newNode(12); root->right->left = newNode(7); cout <<""Inorder Traversal of the original tree \n""; printInorder(root); correctBST(root); cout <<""\nInorder Traversal of the fixed tree \n""; printInorder(root); return 0; } // This code is contributed by shivanisinghss2110",linear,linear "// C++ Program to find ceil of a given value in BST #include using namespace std; /* A binary tree node has key, left child and right child */ class node { public: int key; node* left; node* right; }; /* Helper function that allocates a new node with the given key and NULL left and right pointers.*/ node* newNode(int key) { node* Node = new node(); Node->key = key; Node->left = NULL; Node->right = NULL; return (Node); } // Function to find ceil of a given input in BST. If input // is more than the max key in BST, return -1 int Ceil(node* root, int input) { // Base case if (root == NULL) return -1; // We found equal key if (root->key == input) return root->key; // If root's key is smaller, ceil must be in right // subtree if (root->key < input) return Ceil(root->right, input); // Else, either left subtree or root has the ceil value int ceil = Ceil(root->left, input); return (ceil >= input) ? ceil : root->key; } // Driver code int main() { node* root = newNode(8); root->left = newNode(4); root->right = newNode(12); root->left->left = newNode(2); root->left->right = newNode(6); root->right->left = newNode(10); root->right->right = newNode(14); for (int i = 0; i < 16; i++) cout << i << "" "" << Ceil(root, i) << endl; return 0; } // This code is contributed by rathbhupendra",logn,logn "// C++ Program to find floor of a given value in BST #include using namespace std; /* A binary tree node has key, left child and right child */ class node { public: int key; node* left; node* right; }; /* Helper function that allocates a new node with the given key and NULL left and right pointers.*/ node* newNode(int key) { node* Node = new node(); Node->key = key; Node->left = NULL; Node->right = NULL; return (Node); } // Function to find floor of a given input in BST. If input // is more than the min key in BST, return -1 int Floor(node* root, int input) { // Base case if (root == NULL) return -1; // We found equal key if (root->key == input) return root->key; // If root's key is larger, floor must be in left // subtree if (root->key > input) return Floor(root->left, input); // Else, either right subtree or root has the floor // value else { int floor = Floor(root->right, input); // exception for -1 because it is being returned in // base case return (floor <= input && floor != -1) ? floor : root->key; } } // Driver code int main() { node* root = newNode(8); root->left = newNode(4); root->right = newNode(12); root->left->left = newNode(2); root->left->right = newNode(6); root->right->left = newNode(10); root->right->right = newNode(14); for (int i = 0; i < 16; i++) cout << i << "" "" << Floor(root, i) << endl; return 0; } // This code is contributed by rathbhupendra",logn,logn "// C++ program to find floor and ceil of a given key in BST #include using namespace std; /* A binary tree node has key, left child and right child */ struct Node { int data; Node *left, *right; Node(int value) { data = value; left = right = NULL; } }; // Helper function to find floor and ceil of a given key in // BST void floorCeilBSTHelper(Node* root, int key, int& floor, int& ceil) { while (root) { if (root->data == key) { ceil = root->data; floor = root->data; return; } if (key > root->data) { floor = root->data; root = root->right; } else { ceil = root->data; root = root->left; } } return; } // Display the floor and ceil of a given key in BST. // If key is less than the min key in BST, floor will be -1; // If key is more than the max key in BST, ceil will be -1; void floorCeilBST(Node* root, int key) { // Variables 'floor' and 'ceil' are passed by reference int floor = -1, ceil = -1; floorCeilBSTHelper(root, key, floor, ceil); cout << key << ' ' << floor << ' ' << ceil << '\n'; } // Driver code int main() { Node* root = new Node(8); root->left = new Node(4); root->right = new Node(12); root->left->left = new Node(2); root->left->right = new Node(6); root->right->left = new Node(10); root->right->right = new Node(14); for (int i = 0; i < 16; i++) floorCeilBST(root, i); return 0; }",constant,logn "// C++ program of iterative traversal based method to // find common elements in two BSTs. #include #include using namespace std; // A BST node struct Node { int key; struct Node *left, *right; }; // A utility function to create a new node Node* newNode(int ele) { Node* temp = new Node; temp->key = ele; temp->left = temp->right = NULL; return temp; } // Function two print common elements in given two trees void printCommon(Node* root1, Node* root2) { // Create two stacks for two inorder traversals stack stack1, s1, s2; while (1) { // Push the Nodes of first tree in stack s1 if (root1) { s1.push(root1); root1 = root1->left; } // Push the Nodes of second tree in stack s2 else if (root2) { s2.push(root2); root2 = root2->left; } // Both root1 and root2 are NULL here else if (!s1.empty() && !s2.empty()) { root1 = s1.top(); root2 = s2.top(); // If current keys in two trees are same if (root1->key == root2->key) { cout << root1->key << "" ""; s1.pop(); s2.pop(); // Move to the inorder successor root1 = root1->right; root2 = root2->right; } else if (root1->key < root2->key) { // If Node of first tree is smaller, than // that of second tree, then its obvious // that the inorder successors of current // node can have same value as that of the // second tree Node. Thus, we pop from s2 s1.pop(); root1 = root1->right; // root2 is set to NULL, because we need // new Nodes of tree 1 root2 = NULL; } else if (root1->key > root2->key) { s2.pop(); root2 = root2->right; root1 = NULL; } } // Both roots and both stacks are empty else break; } } // A utility function to do inorder traversal void inorder(struct Node* root) { if (root) { inorder(root->left); cout << root->key << "" ""; inorder(root->right); } } // A utility function to insert a new Node // with given key in BST struct Node* insert(struct Node* node, int key) { // If the tree is empty, return a new Node if (node == NULL) return newNode(key); // Otherwise, recur down the tree if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); // Return the (unchanged) Node pointer return node; } // Driver program int main() { // Create first tree as shown in example Node* root1 = NULL; root1 = insert(root1, 5); root1 = insert(root1, 1); root1 = insert(root1, 10); root1 = insert(root1, 0); root1 = insert(root1, 4); root1 = insert(root1, 7); root1 = insert(root1, 9); // Create second tree as shown in example Node* root2 = NULL; root2 = insert(root2, 10); root2 = insert(root2, 7); root2 = insert(root2, 20); root2 = insert(root2, 4); root2 = insert(root2, 9); cout << ""Tree 1 : "" << endl; inorder(root1); cout << endl; cout << ""Tree 2 : "" << endl; inorder(root2); cout << ""\nCommon Nodes: "" << endl; printCommon(root1, root2); return 0; }",logn,linear "// An AVL Tree based C++ program to count // inversion in an array #include using namespace std; // An AVL tree node struct Node { int key, height; struct Node *left, *right; // size of the tree rooted with this Node int size; }; // A utility function to get the height of // the tree rooted with N int height(struct Node *N) { if (N == NULL) return 0; return N->height; } // A utility function to size of the // tree of rooted with N int size(struct Node *N) { if (N == NULL) return 0; return N->size; } /* Helper function that allocates a new Node with the given key and NULL left and right pointers. */ struct Node* newNode(int key) { struct Node* node = new Node; node->key = key; node->left = node->right = NULL; node->height = node->size = 1; return(node); } // A utility function to right rotate // subtree rooted with y struct Node *rightRotate(struct Node *y) { struct Node *x = y->left; struct Node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right))+1; x->height = max(height(x->left), height(x->right))+1; // Update sizes y->size = size(y->left) + size(y->right) + 1; x->size = size(x->left) + size(x->right) + 1; // Return new root return x; } // A utility function to left rotate // subtree rooted with x struct Node *leftRotate(struct Node *x) { struct Node *y = x->right; struct Node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right))+1; y->height = max(height(y->left), height(y->right))+1; // Update sizes x->size = size(x->left) + size(x->right) + 1; y->size = size(y->left) + size(y->right) + 1; // Return new root return y; } // Get Balance factor of Node N int getBalance(struct Node *N) { if (N == NULL) return 0; return height(N->left) - height(N->right); } // Inserts a new key to the tree rotted with Node. Also, updates // *result (inversion count) struct Node* insert(struct Node* node, int key, int *result) { /* 1. Perform the normal BST rotation */ if (node == NULL) return(newNode(key)); if (key < node->key) { node->left = insert(node->left, key, result); // UPDATE COUNT OF GREATE ELEMENTS FOR KEY *result = *result + size(node->right) + 1; } else node->right = insert(node->right, key, result); /* 2. Update height and size of this ancestor node */ node->height = max(height(node->left), height(node->right)) + 1; node->size = size(node->left) + size(node->right) + 1; /* 3. Get the balance factor of this ancestor node to check whether this node became unbalanced */ int balance = getBalance(node); // If this node becomes unbalanced, then there are // 4 cases // Left Left Case if (balance > 1 && key < node->left->key) return rightRotate(node); // Right Right Case if (balance < -1 && key > node->right->key) return leftRotate(node); // Left Right Case if (balance > 1 && key > node->left->key) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && key < node->right->key) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } // The following function returns inversion count in arr[] int getInvCount(int arr[], int n) { struct Node *root = NULL; // Create empty AVL Tree int result = 0; // Initialize result // Starting from first element, insert all elements one by // one in an AVL tree. for (int i=0; i using namespace std; // Binary Search int binarySearch(int inorder[], int l, int r, int d) { int mid = (l + r)>>1; if (inorder[mid] == d) return mid; else if (inorder[mid] > d) return binarySearch(inorder, l, mid - 1, d); else return binarySearch(inorder, mid + 1, r, d); } // Function to print Leaf Nodes by doing preorder // traversal of tree using preorder and inorder arrays. void leafNodesRec(int preorder[], int inorder[], int l, int r, int *ind, int n) { // If l == r, therefore no right or left subtree. // So, it must be leaf Node, print it. if(l == r) { printf(""%d "", inorder[l]); *ind = *ind + 1; return; } // If array is out of bound, return. if (l < 0 || l > r || r >= n) return; // Finding the index of preorder element // in inorder array using binary search. int loc = binarySearch(inorder, l, r, preorder[*ind]); // Incrementing the index. *ind = *ind + 1; // Finding on the left subtree. leafNodesRec(preorder, inorder, l, loc - 1, ind, n); // Finding on the right subtree. leafNodesRec(preorder, inorder, loc + 1, r, ind, n); } // Finds leaf nodes from given preorder traversal. void leafNodes(int preorder[], int n) { int inorder[n]; // To store inorder traversal // Copy the preorder into another array. for (int i = 0; i < n; i++) inorder[i] = preorder[i]; // Finding the inorder by sorting the array. sort(inorder, inorder + n); // Point to the index in preorder. int ind = 0; // Print the Leaf Nodes. leafNodesRec(preorder, inorder, 0, n - 1, &ind, n); } // Driven Program int main() { int preorder[] = { 890, 325, 290, 530, 965 }; int n = sizeof(preorder)/sizeof(preorder[0]); leafNodes(preorder, n); return 0; }",linear,nlogn "// CPP program to find number of pairs and minimal // possible value #include using namespace std; // function for finding pairs and min value void pairs(int arr[], int n, int k) { // initialize smallest and count int smallest = INT_MAX; int count = 0; // iterate over all pairs for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { // is abs value is smaller than smallest // update smallest and reset count to 1 if (abs(arr[i] + arr[j] - k) < smallest) { smallest = abs(arr[i] + arr[j] - k); count = 1; } // if abs value is equal to smallest // increment count value else if (abs(arr[i] + arr[j] - k) == smallest) count++; } // print result cout << ""Minimal Value = "" << smallest << ""\n""; cout << ""Total Pairs = "" << count << ""\n""; } // driver program int main() { int arr[] = { 3, 5, 7, 5, 1, 9, 9 }; int k = 12; int n = sizeof(arr) / sizeof(arr[0]); pairs(arr, n, k); return 0; }",constant,quadratic "// C++ program to find number of pairs // and minimal possible value #include using namespace std; // function for finding pairs and min value void pairs(int arr[], int n, int k) { // initialize smallest and count int smallest = INT_MAX, count = 0; set s; // iterate over all pairs s.insert(arr[0]); for (int i = 1; i < n; i++) { // Find the closest elements to k - arr[i] int lower = *lower_bound(s.begin(), s.end(), k - arr[i]); int upper = *upper_bound(s.begin(), s.end(), k - arr[i]); // Find absolute value of the pairs formed // with closest greater and smaller elements. int curr_min = min(abs(lower + arr[i] - k), abs(upper + arr[i] - k)); // is abs value is smaller than smallest // update smallest and reset count to 1 if (curr_min < smallest) { smallest = curr_min; count = 1; } // if abs value is equal to smallest // increment count value else if (curr_min == smallest) count++; s.insert(arr[i]); } // print result cout << ""Minimal Value = "" << smallest << ""\n""; cout << ""Total Pairs = "" << count << ""\n""; } // driver program int main() { int arr[] = { 3, 5, 7, 5, 1, 9, 9 }; int k = 12; int n = sizeof(arr) / sizeof(arr[0]); pairs(arr, n, k); return 0; }",linear,nlogn "// CPP program to find rank of an // element in a stream. #include using namespace std; struct Node { int data; Node *left, *right; int leftSize; }; Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; temp->leftSize = 0; return temp; } // Inserting a new Node. Node* insert(Node*& root, int data) { if (!root) return newNode(data); // Updating size of left subtree. if (data <= root->data) { root->left = insert(root->left, data); root->leftSize++; } else root->right = insert(root->right, data); return root; } // Function to get Rank of a Node x. int getRank(Node* root, int x) { // Step 1. if (root->data == x) return root->leftSize; // Step 2. if (x < root->data) { if (!root->left) return -1; else return getRank(root->left, x); } // Step 3. else { if (!root->right) return -1; else { int rightSize = getRank(root->right, x); if(rightSize == -1 ) return -1; return root->leftSize + 1 + rightSize; } } } // Driver code int main() { int arr[] = { 5, 1, 4, 4, 5, 9, 7, 13, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 4; Node* root = NULL; for (int i = 0; i < n; i++) root = insert(root, arr[i]); cout << ""Rank of "" << x << "" in stream is: "" << getRank(root, x) << endl; x = 13; cout << ""Rank of "" << x << "" in stream is: "" << getRank(root, x) << endl; x = 8; cout << ""Rank of "" << x << "" in stream is: "" << getRank(root, x) << endl; return 0; }",linear,linear "// C++ program to find rank of an // element in a stream. #include using namespace std; // Driver code int main() { int a[] = {5, 1, 14, 4, 15, 9, 7, 20, 11}; int key = 20; int arraySize = sizeof(a)/sizeof(a[0]); int count = 0; for(int i = 0; i < arraySize; i++) { if(a[i] <= key) { count += 1; } } cout << ""Rank of "" << key << "" in stream is: "" << count-1 << endl; return 0; } // This code is contributed by // Ashwin Loganathan.",constant,linear "// C++ program to insert element in Binary Tree #include #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node* left; Node* right; }; // Function to create a new node Node* CreateNode(int data) { Node* newNode = new Node(); if (!newNode) { cout << ""Memory error\n""; return NULL; } newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // Function to insert element in binary tree Node* InsertNode(Node* root, int data) { // If the tree is empty, assign new node address to root if (root == NULL) { root = CreateNode(data); return root; } // Else, do level order traversal until we find an empty // place, i.e. either left child or right child of some // node is pointing to NULL. queue q; q.push(root); while (!q.empty()) { Node* temp = q.front(); q.pop(); if (temp->left != NULL) q.push(temp->left); else { temp->left = CreateNode(data); return root; } if (temp->right != NULL) q.push(temp->right); else { temp->right = CreateNode(data); return root; } } } /* Inorder traversal of a binary tree */ void inorder(Node* temp) { if (temp == NULL) return; inorder(temp->left); cout << temp->data << ' '; inorder(temp->right); } // Driver code int main() { Node* root = CreateNode(10); root->left = CreateNode(11); root->left->left = CreateNode(7); root->right = CreateNode(9); root->right->left = CreateNode(15); root->right->right = CreateNode(8); cout << ""Inorder traversal before insertion: ""; inorder(root); cout << endl; int key = 12; root = InsertNode(root, key); cout << ""Inorder traversal after insertion: ""; inorder(root); cout << endl; return 0; }",logn,linear "// C++ program to delete element in binary tree #include using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */ struct Node { int key; struct Node *left, *right; }; /* function to create a new node of tree and return pointer */ struct Node* newNode(int key) { struct Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp; }; /* Inorder traversal of a binary tree*/ void inorder(struct Node* temp) { if (!temp) return; inorder(temp->left); cout << temp->key << "" ""; inorder(temp->right); } /* function to delete the given deepest node (d_node) in binary tree */ void deletDeepest(struct Node* root, struct Node* d_node) { queue q; q.push(root); // Do level order traversal until last node struct Node* temp; while (!q.empty()) { temp = q.front(); q.pop(); if (temp == d_node) { temp = NULL; delete (d_node); return; } if (temp->right) { if (temp->right == d_node) { temp->right = NULL; delete (d_node); return; } else q.push(temp->right); } if (temp->left) { if (temp->left == d_node) { temp->left = NULL; delete (d_node); return; } else q.push(temp->left); } } } /* function to delete element in binary tree */ Node* deletion(struct Node* root, int key) { if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { if (root->key == key) return NULL; else return root; } queue q; q.push(root); struct Node* temp; struct Node* key_node = NULL; // Do level order traversal to find deepest // node(temp) and node to be deleted (key_node) while (!q.empty()) { temp = q.front(); q.pop(); if (temp->key == key) key_node = temp; if (temp->left) q.push(temp->left); if (temp->right) q.push(temp->right); } if (key_node != NULL) { int x = temp->key; deletDeepest(root, temp); key_node->key = x; } return root; } // Driver code int main() { struct Node* root = newNode(10); root->left = newNode(11); root->left->left = newNode(7); root->left->right = newNode(12); root->right = newNode(9); root->right->left = newNode(15); root->right->right = newNode(8); cout << ""Inorder traversal before deletion : ""; inorder(root); int key = 11; root = deletion(root, key); cout << endl; cout << ""Inorder traversal after deletion : ""; inorder(root); return 0; }",linear,linear "// C++ program to delete element in binary tree #include using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; }; /* function to create a new node of tree and return pointer */ struct Node* newNode(int key) { struct Node* temp = new Node; temp->data = key; temp->left = temp->right = NULL; return temp; }; /* Inorder traversal of a binary tree*/ void inorder(struct Node* temp) { if (!temp) return; inorder(temp->left); cout << temp->data << "" ""; inorder(temp->right); } struct Node* deletion(struct Node* root, int key) { if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) { if (root->data == key) return NULL; else return root; } Node* key_node = NULL; Node* temp; Node* last; queue q; q.push(root); // Do level order traversal to find deepest // node(temp), node to be deleted (key_node) // and parent of deepest node(last) while (!q.empty()) { temp = q.front(); q.pop(); if (temp->data == key) key_node = temp; if (temp->left) { last = temp; // storing the parent node q.push(temp->left); } if (temp->right) { last = temp; // storing the parent node q.push(temp->right); } } if (key_node != NULL) { key_node->data = temp->data; // replacing key_node's data to // deepest node's data if (last->right == temp) last->right = NULL; else last->left = NULL; delete (temp); } return root; } // Driver code int main() { struct Node* root = newNode(9); root->left = newNode(2); root->left->left = newNode(4); root->left->right = newNode(7); root->right = newNode(8); cout << ""Inorder traversal before deletion : ""; inorder(root); int key = 7; root = deletion(root, key); cout << endl; cout << ""Inorder traversal after deletion : ""; inorder(root); return 0; }",linear,linear "// C++ implementation of tree using array // numbering starting from 0 to n-1. #include using namespace std; char tree[10]; int root(char key) { if (tree[0] != '\0') cout << ""Tree already had root""; else tree[0] = key; return 0; } int set_left(char key, int parent) { if (tree[parent] == '\0') cout << ""\nCan't set child at "" << (parent * 2) + 1 << "" , no parent found""; else tree[(parent * 2) + 1] = key; return 0; } int set_right(char key, int parent) { if (tree[parent] == '\0') cout << ""\nCan't set child at "" << (parent * 2) + 2 << "" , no parent found""; else tree[(parent * 2) + 2] = key; return 0; } int print_tree() { cout << ""\n""; for (int i = 0; i < 10; i++) { if (tree[i] != '\0') cout << tree[i]; else cout << ""-""; } return 0; } // Driver Code int main() { root('A'); set_left('B',0); set_right('C', 0); set_left('D', 1); set_right('E', 1); set_right('F', 2); print_tree(); return 0; }",linear,logn "// C++ program to evaluate an expression tree #include using namespace std; // Class to represent the nodes of syntax tree class node { public: string info; node *left = NULL, *right = NULL; node(string x) { info = x; } }; // Utility function to return the integer value // of a given string int toInt(string s) { int num = 0; // Check if the integral value is // negative or not // If it is not negative, generate the number // normally if(s[0]!='-') for (int i=0; ileft && !root->right) return toInt(root->info); // Evaluate left subtree int l_val = eval(root->left); // Evaluate right subtree int r_val = eval(root->right); // Check which operator to apply if (root->info==""+"") return l_val+r_val; if (root->info==""-"") return l_val-r_val; if (root->info==""*"") return l_val*r_val; return l_val/r_val; } //driver function to check the above program int main() { // create a syntax tree node *root = new node(""+""); root->left = new node(""*""); root->left->left = new node(""5""); root->left->right = new node(""-4""); root->right = new node(""-""); root->right->left = new node(""100""); root->right->right = new node(""20""); cout << eval(root) << endl; delete(root); root = new node(""+""); root->left = new node(""*""); root->left->left = new node(""5""); root->left->right = new node(""4""); root->right = new node(""-""); root->right->left = new node(""100""); root->right->right = new node(""/""); root->right->right->left = new node(""20""); root->right->right->right = new node(""2""); cout << eval(root); return 0; }",constant,linear "// C++ program to check if a given Binary Tree is symmetric // or not #include using namespace std; // A Binary Tree Node struct Node { int key; struct Node *left, *right; }; // Utility function to create new Node Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } // Returns true if trees with roots as root1 and root2 are // mirror bool isMirror(struct Node* root1, struct Node* root2) { // If both trees are empty, then they are mirror images if (root1 == NULL && root2 == NULL) return true; // For two trees to be mirror images, the following // three conditions must be true // 1.) Their root node's key must be same // 2.) left subtree of left tree and right subtree of // right tree have to be mirror images // 3.) right subtree of left tree and left subtree of // right tree have to be mirror images if (root1 && root2 && root1->key == root2->key) return isMirror(root1->left, root2->right) && isMirror(root1->right, root2->left); // if none of above conditions is true then root1 // and root2 are not mirror images return false; } // Returns true if a tree is symmetric i.e. mirror image of itself bool isSymmetric(struct Node* root) { // Check if tree is mirror of itself return isMirror(root, root); } // Driver code int main() { // Let us construct the Tree shown in the above figure Node* root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(4); root->right->left = newNode(4); root->right->right = newNode(3); if (isSymmetric(root)) cout << ""Symmetric""; else cout << ""Not symmetric""; return 0; } // This code is contributed by Sania Kumari Gupta",logn,linear "// C++ program to print inorder traversal // using stack. #include using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; Node (int data) { this->data = data; left = right = NULL; } }; /* Iterative function for inorder tree traversal */ void inOrder(struct Node *root) { stack s; Node *curr = root; while (curr != NULL || s.empty() == false) { /* Reach the left most Node of the curr Node */ while (curr != NULL) { /* place pointer to a tree node on the stack before traversing the node's left subtree */ s.push(curr); curr = curr->left; } /* Current must be NULL at this point */ curr = s.top(); s.pop(); cout << curr->data << "" ""; /* we have visited the node and its left subtree. Now, it's right subtree's turn */ curr = curr->right; } /* end of while */ } /* Driver program to test above functions*/ int main() { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); inOrder(root); return 0; }",linear,linear "// C++ program for finding postorder // traversal of BST from preorder traversal #include using namespace std; // Function to find postorder traversal from // preorder traversal. void findPostOrderUtil(int pre[], int n, int minval, int maxval, int& preIndex) { // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex] < minval || pre[preIndex] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. int val = pre[preIndex]; preIndex++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); cout << val << "" ""; } // Function to find postorder traversal. void findPostOrder(int pre[], int n) { // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. int preIndex = 0; findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex); } // Driver code int main() { int pre[] = { 40, 30, 35, 80, 100 }; int n = sizeof(pre) / sizeof(pre[0]); // Calling function findPostOrder(pre, n); return 0; }",linear,linear "// C++ implementation to replace each node // in binary tree with the sum of its inorder // predecessor and successor #include using namespace std; // node of a binary tree struct Node { int data; struct Node* left, *right; }; // function to get a new node of a binary tree struct Node* getNode(int data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node; } // function to store the inorder traversal // of the binary tree in 'arr' void storeInorderTraversal(struct Node* root, vector& arr) { // if root is NULL if (!root) return; // first recur on left child storeInorderTraversal(root->left, arr); // then store the root's data in 'arr' arr.push_back(root->data); // now recur on right child storeInorderTraversal(root->right, arr); } // function to replace each node with the sum of its // inorder predecessor and successor void replaceNodeWithSum(struct Node* root, vector arr, int* i) { // if root is NULL if (!root) return; // first recur on left child replaceNodeWithSum(root->left, arr, i); // replace node's data with the sum of its // inorder predecessor and successor root->data = arr[*i - 1] + arr[*i + 1]; // move 'i' to point to the next 'arr' element ++*i; // now recur on right child replaceNodeWithSum(root->right, arr, i); } // Utility function to replace each node in binary // tree with the sum of its inorder predecessor // and successor void replaceNodeWithSumUtil(struct Node* root) { // if tree is empty if (!root) return; vector arr; // store the value of inorder predecessor // for the leftmost leaf arr.push_back(0); // store the inorder traversal of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.push_back(0); // replace each node with the required sum int i = 1; replaceNodeWithSum(root, arr, &i); } // function to print the preorder traversal // of a binary tree void preorderTraversal(struct Node* root) { // if root is NULL if (!root) return; // first print the data of node cout << root->data << "" ""; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right); } // Driver program to test above int main() { // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \ / \ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << ""Preorder Traversal before tree modification:n""; preorderTraversal(root); replaceNodeWithSumUtil(root); cout << ""\nPreorder Traversal after tree modification:n""; preorderTraversal(root); return 0; }",linear,linear "// C++ implementation to replace each node // in binary tree with the sum of its inorder // predecessor and successor #include using namespace std; // node of a binary tree struct Node { int data; struct Node* left, *right; }; // function to get a new node of a binary tree struct Node* getNode(int data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node; } // function to print the preorder traversal // of a binary tree void preorderTraversal(struct Node* root) { // if root is NULL if (!root) return; // first print the data of node cout << root->data << "" ""; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right); } void inOrderTraverse(struct Node* root, struct Node* &prev, int &prevVal) { if(root == NULL) return; inOrderTraverse(root->left, prev, prevVal); if(prev == NULL) { prev = root; prevVal = 0; } else { int temp = prev->data; prev->data = prevVal + root->data; prev = root; prevVal = temp; } inOrderTraverse(root->right, prev, prevVal); } // Driver program to test above int main() { // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \ / \ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << ""Preorder Traversal before tree modification:\n""; preorderTraversal(root); struct Node* prev = NULL; int prevVal = -1; inOrderTraverse(root, prev, prevVal); // update righmost node. prev->data = prevVal; cout << ""\nPreorder Traversal after tree modification:\n""; preorderTraversal(root); return 0; }",linear,linear "// Recursive CPP program for level // order traversal of Binary Tree #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node *left, *right; }; /* Function prototypes */ void printCurrentLevel(node* root, int level); int height(node* node); node* newNode(int data); /* Function to print level order traversal a tree*/ void printLevelOrder(node* root) { int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i); } /* Print nodes at a current level */ void printCurrentLevel(node* root, int level) { if (root == NULL) return; if (level == 1) cout << root->data << "" ""; else if (level > 1) { printCurrentLevel(root->left, level - 1); printCurrentLevel(root->right, level - 1); } } /* Compute the ""height"" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(node* node) { if (node == NULL) return 0; else { /* compute the height of each subtree */ int lheight = height(node->left); int rheight = height(node->right); /* use the larger one */ if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node); } /* Driver code*/ int main() { node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << ""Level Order traversal of binary tree is \n""; printLevelOrder(root); return 0; } // This code is contributed by rathbhupendra",linear,quadratic "/* C++ program to print level order traversal using STL */ #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // Iterative method to find height of Binary Tree void printLevelOrder(Node* root) { // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue q; // Enqueue Root and initialize height q.push(root); while (q.empty() == false) { // Print front of queue and remove it from queue Node* node = q.front(); cout << node->data << "" ""; q.pop(); /* Enqueue left child */ if (node->left != NULL) q.push(node->left); /*Enqueue right child */ if (node->right != NULL) q.push(node->right); } } // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver program to test above functions int main() { // Let us create binary tree shown in above diagram Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << ""Level Order traversal of binary tree is \n""; printLevelOrder(root); return 0; }",linear,linear "// C++ program for recursive level // order traversal in spiral form #include using namespace std; // A binary tree node has data, // pointer to left child and a // pointer to right child struct node { int data; struct node* left; struct node* right; }; // Function prototypes void printGivenLevel(struct node* root, int level, int ltr); int height(struct node* node); struct node* newNode(int data); // Function to print spiral traversal of a tree void printSpiral(struct node* root) { int h = height(root); int i; // ltr -> Left to Right. If this variable // is set,then the given level is traversed // from left to right. bool ltr = false; for (i = 1; i <= h; i++) { printGivenLevel(root, i, ltr); // Revert ltr to traverse next // level in opposite order ltr = !ltr; } } // Print nodes at a given level void printGivenLevel(struct node* root, int level, int ltr) { if (root == NULL) return; if (level == 1) cout << root->data << "" ""; else if (level > 1) { if (ltr) { printGivenLevel(root->left, level - 1, ltr); printGivenLevel(root->right, level - 1, ltr); } else { printGivenLevel(root->right, level - 1, ltr); printGivenLevel(root->left, level - 1, ltr); } } } // Compute the ""height"" of a tree -- the number of // nodes along the longest path from the root node // down to the farthest leaf node. int height(struct node* node) { if (node == NULL) return 0; else { // Compute the height of each subtree int lheight = height(node->left); int rheight = height(node->right); // Use the larger one if (lheight > rheight) return (lheight + 1); else return (rheight + 1); } } // Helper function that allocates a new // node with the given data and NULL left // and right pointers. struct node* newNode(int data) { node* newnode = new node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return (newnode); } // Driver code int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); printf(""Spiral Order traversal of "" ""binary tree is \n""); printSpiral(root); return 0; } // This code is contributed by samrat2825",linear,quadratic "// C++ implementation of a O(n) time method for spiral order // traversal #include #include using namespace std; // Binary Tree node struct node { int data; struct node *left, *right; }; void printSpiral(struct node* root) { if (root == NULL) return; // NULL check // Create two stacks to store alternate levels stack s1; // For levels to be printed from right to left stack s2; // For levels to be printed from left to right // Push first level to first stack 's1' s1.push(root); // Keep printing while any of the stacks has some nodes while (!s1.empty() || !s2.empty()) { // Print nodes of current level from s1 and push // nodes of next level to s2 while (!s1.empty()) { struct node* temp = s1.top(); s1.pop(); cout << temp->data << "" ""; // Note that is right is pushed before left if (temp->right) s2.push(temp->right); if (temp->left) s2.push(temp->left); } // Print nodes of current level from s2 and push // nodes of next level to s1 while (!s2.empty()) { struct node* temp = s2.top(); s2.pop(); cout << temp->data << "" ""; // Note that is left is pushed before right if (temp->left) s1.push(temp->left); if (temp->right) s1.push(temp->right); } } } // A utility function to create a new node struct node* newNode(int data) { struct node* node = new struct node; node->data = data; node->left = NULL; node->right = NULL; return (node); } int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << ""Spiral Order traversal of binary tree is \n""; printSpiral(root); return 0; }",linear,linear "// C++ implementation of above approach #include #include using namespace std; // Binary Tree node struct Node { int key; struct Node *left, *right; }; void spiralPrint(struct Node* root) { // Declare a deque deque dq; // Insert the root of the tree into the deque dq.push_back(root); // Create a variable that will switch in each iteration bool reverse = true; // Start iteration while (!dq.empty()) { // Save the size of the deque here itself, as in // further steps the size of deque will frequently // change int n = dq.size(); // If we are printing left to right if (!reverse) { // Iterate from left to right while (n--) { // Insert the child from the back of the // deque Left child first if (dq.front()->left != NULL) dq.push_back(dq.front()->left); if (dq.front()->right != NULL) dq.push_back(dq.front()->right); // Print the current processed element cout << dq.front()->key << "" ""; dq.pop_front(); } // Switch reverse for next traversal reverse = !reverse; } else { // If we are printing right to left // Iterate the deque in reverse order and insert // the children from the front while (n--) { // Insert the child in the front of the // deque Right child first if (dq.back()->right != NULL) dq.push_front(dq.back()->right); if (dq.back()->left != NULL) dq.push_front(dq.back()->left); // Print the current processed element cout << dq.back()->key << "" ""; dq.pop_back(); } // Switch reverse for next traversal reverse = !reverse; } } } // A utility function to create a new node struct Node* newNode(int data) { struct Node* node = new struct Node; node->key = data; node->left = NULL; node->right = NULL; return (node); } int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << ""Spiral Order traversal of binary tree is :\n""; spiralPrint(root); return 0; } // This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear "/* C++ program for special order traversal */ #include #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left; Node *right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node *newNode(int data) { Node *node = new Node; node->data = data; node->right = node->left = NULL; return node; } /* Given a perfect binary tree, print its nodes in specific level order */ void printSpecificLevelOrder(Node *root) { if (root == NULL) return; // Let us print root and next level first cout << root->data; // / Since it is perfect Binary Tree, right is not checked if (root->left != NULL) cout << "" "" << root->left->data << "" "" << root->right->data; // Do anything more if there are nodes at next level in // given perfect Binary Tree if (root->left->left == NULL) return; // Create a queue and enqueue left and right children of root queue q; q.push(root->left); q.push(root->right); // We process two nodes at a time, so we need two variables // to store two front items of queue Node *first = NULL, *second = NULL; // traversal loop while (!q.empty()) { // Pop two items from queue first = q.front(); q.pop(); second = q.front(); q.pop(); // Print children of first and second in reverse order cout << "" "" << first->left->data << "" "" << second->right->data; cout << "" "" << first->right->data << "" "" << second->left->data; // If first and second have grandchildren, enqueue them // in reverse order if (first->left->left != NULL) { q.push(first->left); q.push(second->right); q.push(first->right); q.push(second->left); } } } /* Driver program to test above functions*/ int main() { //Perfect Binary Tree of Height 4 Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); root->right->right->right = newNode(15); root->left->left->left->left = newNode(16); root->left->left->left->right = newNode(17); root->left->left->right->left = newNode(18); root->left->left->right->right = newNode(19); root->left->right->left->left = newNode(20); root->left->right->left->right = newNode(21); root->left->right->right->left = newNode(22); root->left->right->right->right = newNode(23); root->right->left->left->left = newNode(24); root->right->left->left->right = newNode(25); root->right->left->right->left = newNode(26); root->right->left->right->right = newNode(27); root->right->right->left->left = newNode(28); root->right->right->left->right = newNode(29); root->right->right->right->left = newNode(30); root->right->right->right->right = newNode(31); cout << ""Specific Level Order traversal of binary tree is \n""; printSpecificLevelOrder(root); return 0; }",linear,linear "// C++ program to reverse // alternate levels of a tree #include using namespace std; struct Node { char key; Node *left, *right; }; void preorder(struct Node *root1, struct Node* root2, int lvl) { // Base cases if (root1 == NULL || root2==NULL) return; // Swap subtrees if level is even if (lvl%2 == 0) swap(root1->key, root2->key); // Recur for left and right // subtrees (Note : left of root1 // is passed and right of root2 in // first call and opposite // in second call. preorder(root1->left, root2->right, lvl+1); preorder(root1->right, root2->left, lvl+1); } // This function calls preorder() // for left and right children // of root void reverseAlternate(struct Node *root) { preorder(root->left, root->right, 0); } // Inorder traversal (used to print initial and // modified trees) void printInorder(struct Node *root) { if (root == NULL) return; printInorder(root->left); cout << root->key << "" ""; printInorder(root->right); } // A utility function to create a new node Node *newNode(int key) { Node *temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp; } // Driver program to test above functions int main() { struct Node *root = newNode('a'); root->left = newNode('b'); root->right = newNode('c'); root->left->left = newNode('d'); root->left->right = newNode('e'); root->right->left = newNode('f'); root->right->right = newNode('g'); root->left->left->left = newNode('h'); root->left->left->right = newNode('i'); root->left->right->left = newNode('j'); root->left->right->right = newNode('k'); root->right->left->left = newNode('l'); root->right->left->right = newNode('m'); root->right->right->left = newNode('n'); root->right->right->right = newNode('o'); cout << ""Inorder Traversal of given tree\n""; printInorder(root); reverseAlternate(root); cout << ""\n\nInorder Traversal of modified tree\n""; printInorder(root); return 0; }",logn,linear "// C++ program to implement iterative preorder traversal #include using namespace std; /* A binary tree node has data, left child and right child */ struct node { int data; struct node* left; struct node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/ struct node* newNode(int data) { struct node* node = new struct node; node->data = data; node->left = NULL; node->right = NULL; return (node); } // An iterative process to print preorder traversal of Binary tree void iterativePreorder(node* root) { // Base Case if (root == NULL) return; // Create an empty stack and push root to it stack nodeStack; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ while (nodeStack.empty() == false) { // Pop the top item from stack and print it struct node* node = nodeStack.top(); printf(""%d "", node->data); nodeStack.pop(); // Push right and left children of the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); } } // Driver program to test above functions int main() { /* Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 */ struct node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(2); iterativePreorder(root); return 0; }",logn,linear "#include using namespace std; // Tree Node struct Node { int data; Node *left, *right; Node(int data) { this->data = data; this->left = this->right = NULL; } }; // Iterative function to do Preorder traversal of the tree void preorderIterative(Node* root) { if (root == NULL) return; stack st; // start from root node (set current node to root node) Node* curr = root; // run till stack is not empty or current is // not NULL while (!st.empty() || curr != NULL) { // Print left children while exist // and keep pushing right into the // stack. while (curr != NULL) { cout << curr->data << "" ""; if (curr->right) st.push(curr->right); curr = curr->left; } // We reach when curr is NULL, so We // take out a right child from stack if (st.empty() == false) { curr = st.top(); st.pop(); } } } // Driver Code int main() { Node* root = new Node(10); root->left = new Node(20); root->right = new Node(30); root->left->left = new Node(40); root->left->left->left = new Node(70); root->left->right = new Node(50); root->right->left = new Node(60); root->left->left->right = new Node(80); preorderIterative(root); return 0; }",logn,linear "// C++ program for diagonal // traversal of Binary Tree #include using namespace std; // Tree node struct Node { int data; Node *left, *right; }; /* root - root of the binary tree d - distance of current line from rightmost -topmost slope. diagonalPrint - multimap to store Diagonal elements (Passed by Reference) */ void diagonalPrintUtil(Node* root, int d, map> &diagonalPrint) { // Base case if (!root) return; // Store all nodes of same // line together as a vector diagonalPrint[d].push_back(root->data); // Increase the vertical // distance if left child diagonalPrintUtil(root->left, d + 1, diagonalPrint); // Vertical distance remains // same for right child diagonalPrintUtil(root->right, d, diagonalPrint); } // Print diagonal traversal // of given binary tree void diagonalPrint(Node* root) { // create a map of vectors // to store Diagonal elements map > diagonalPrint; diagonalPrintUtil(root, 0, diagonalPrint); cout << ""Diagonal Traversal of binary tree : \n""; for (auto it :diagonalPrint) { vector v=it.second; for(auto it:v) cout<data = data; node->left = node->right = NULL; return node; } // Driver program int main() { Node* root = newNode(8); root->left = newNode(3); root->right = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(14); root->right->right->left = newNode(13); root->left->right->left = newNode(4); root->left->right->right = newNode(7); /* Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(9); root->left->right = newNode(6); root->right->left = newNode(4); root->right->right = newNode(5); root->right->left->right = newNode(7); root->right->left->left = newNode(12); root->left->right->left = newNode(11); root->left->left->right = newNode(10);*/ diagonalPrint(root); return 0; }",linear,nlogn "#include using namespace std; // Tree node struct Node { int data; Node *left, *right; }; vector diagonal(Node* root) { vector diagonalVals; if (!root) return diagonalVals; // The leftQueue will be a queue which will store all // left pointers while traversing the tree, and will be // utilized when at any point right pointer becomes NULL queue leftQueue; Node* node = root; while (node) { // Add current node to output diagonalVals.push_back(node->data); // If left child available, add it to queue if (node->left) leftQueue.push(node->left); // if right child, transfer the node to right if (node->right) node = node->right; else { // If left child Queue is not empty, utilize it // to traverse further if (!leftQueue.empty()) { node = leftQueue.front(); leftQueue.pop(); } else { // All the right childs traversed and no // left child left node = NULL; } } } return diagonalVals; } // Utility method to create a new node Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // Driver program int main() { Node* root = newNode(8); root->left = newNode(3); root->right = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(14); root->right->right->left = newNode(13); root->left->right->left = newNode(4); root->left->right->right = newNode(7); /* Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(9); root->left->right = newNode(6); root->right->left = newNode(4); root->right->right = newNode(5); root->right->left->right = newNode(7); root->right->left->left = newNode(12); root->left->right->left = newNode(11); root->left->left->right = newNode(10);*/ vector diagonalValues = diagonal(root); for (int i = 0; i < diagonalValues.size(); i++) { cout << diagonalValues[i] << "" ""; } cout << endl; return 0; }",linear,nlogn "#include using namespace std; struct Node { int data; Node *left, *right; }; Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } vector > result; void diagonalPrint(Node* root) { if(root == NULL) return; queue q; q.push(root); while(!q.empty()) { int size = q.size(); vector answer; while(size--) { Node* temp = q.front(); q.pop(); // traversing each component; while(temp) { answer.push_back(temp->data); if(temp->left) q.push(temp->left); temp = temp->right; } } result.push_back(answer); } } int main() { Node* root = newNode(8); root->left = newNode(3); root->right = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(14); root->right->right->left = newNode(13); root->left->right->left = newNode(4); root->left->right->right = newNode(7); diagonalPrint(root); for(int i=0 ; i using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } // root node Node* root; // function to print in diagonal order void traverse() { // if the tree is empty, do not have to print // anything if (root == NULL) return; // if root is not empty, point curr node to the // root node Node* curr = root; // Maintain a queue to store left child queue q; // continue till the queue is empty and curr is null while (!q.empty() || curr != NULL) { // if curr is not null // 1. print the data of the curr node // 2. if left child is present, add it to the queue // 3. Move curr pointer to the right if (curr != NULL) { cout << curr->data << "" ""; if (curr->left != NULL) q.push(curr->left); curr = curr->right; } // if curr is null, remove a node from the queue // and point it to curr node else { curr = q.front(); q.pop(); } } } // Driver Code int main() { root = newNode(8); root->left = newNode(3); root->right = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(14); root->right->right->left = newNode(13); root->left->right->left = newNode(4); root->left->right->right = newNode(7); traverse(); } // This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear "#include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; }; // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = nullptr; return temp; } // A simple function to print leaf nodes of a binary tree void printLeaves(Node* root) { if (root == nullptr) return; printLeaves(root->left); // Print it if it is a leaf node if (!(root->left) && !(root->right)) cout << root->data << "" ""; printLeaves(root->right); } // A function to print all left boundary nodes, except a // leaf node. Print the nodes in TOP DOWN manner void printBoundaryLeft(Node* root) { if (root == nullptr) return; if (root->left) { // to ensure top down order, print the node // before calling itself for left subtree cout << root->data << "" ""; printBoundaryLeft(root->left); } else if (root->right) { cout << root->data << "" ""; printBoundaryLeft(root->right); } // do nothing if it is a leaf node, this way we avoid // duplicates in output } // A function to print all right boundary nodes, except a // leaf node Print the nodes in BOTTOM UP manner void printBoundaryRight(Node* root) { if (root == nullptr) return; if (root->right) { // to ensure bottom up order, first call for right // subtree, then print this node printBoundaryRight(root->right); cout << root->data << "" ""; } else if (root->left) { printBoundaryRight(root->left); cout << root->data << "" ""; } // do nothing if it is a leaf node, this way we avoid // duplicates in output } // A function to do boundary traversal of a given binary // tree void printBoundary(Node* root) { if (root == nullptr) return; cout << root->data << "" ""; // Print the left boundary in top-down manner. printBoundaryLeft(root->left); // Print all leaf nodes printLeaves(root->left); printLeaves(root->right); // Print the right boundary in bottom-up manner printBoundaryRight(root->right); } // Driver program to test above functions int main() { // Let us construct the tree given in the above diagram Node* root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printBoundary(root); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "#include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; }; // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = nullptr; return temp; } bool isLeaf(Node* node){ if(node->left == NULL && node->right==NULL){ return true; } return false; } void addLeftBound(Node * root, vector& ans){ //Go left left and no left then right but again check from left root = root->left; while(root!=NULL){ if(!isLeaf(root)) ans.push_back(root->data); if(root->left !=NULL) root = root->left; else root = root->right; } } void addRightBound(Node * root, vector& ans){ //Go right right and no right then left but again check from right root = root->right; //As we need the reverse of this for Anticlockwise stack stk; while(root!=NULL){ if(!isLeaf(root)) stk.push(root->data); if(root->right !=NULL) root = root->right; else root = root->left; } while(!stk.empty()){ ans.push_back(stk.top()); stk.pop(); } } //its kind of inorder void addLeaves(Node * root, vector& ans){ if(root==NULL){ return; } if(isLeaf(root)){ ans.push_back(root->data); //just store leaf nodes return; } addLeaves(root->left,ans); addLeaves(root->right,ans); } vector boundary(Node *root) { //Your code here vector ans; if(root==NULL) return ans; if(!isLeaf(root)) ans.push_back(root->data); // if leaf then its done by addLeaf addLeftBound(root,ans); addLeaves(root,ans); addRightBound(root,ans); return ans; } int main() { // Let us construct the tree given in the above diagram Node* root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); vectorans = boundary(root); for(int v : ans){ cout< // A binary tree node struct Node { int data; Node *left, *right; }; // Helper function to allocates a new node Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // Function to compute height and // size of a binary tree int heighAndSize(Node* node, int &size) { if (node==NULL) return 0; // compute height of each subtree int l = heighAndSize(node->left, size); int r = heighAndSize(node->right, size); //increase size by 1 size++; //return larger of the two return (l > r) ? l + 1 : r + 1; } //function to calculate density of a binary tree float density(Node* root) { if (root == NULL) return 0; int size = 0; // To store size // Finds height and size int _height = heighAndSize(root, size); return (float)size/_height; } // Driver code to test above methods int main() { Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); printf(""Density of given binary tree is %f"", density(root)); return 0; }",logn,linear "// C++ program to find height of full binary tree // using preorder #include using namespace std; // function to return max of left subtree height // or right subtree height int findDepthRec(char tree[], int n, int& index) { if (index >= n || tree[index] == 'l') return 0; // calc height of left subtree (In preorder // left subtree is processed before right) index++; int left = findDepthRec(tree, n, index); // calc height of right subtree index++; int right = findDepthRec(tree, n, index); return max(left, right) + 1; } // Wrapper over findDepthRec() int findDepth(char tree[], int n) { int index = 0; return findDepthRec(tree, n, index); } // Driver program int main() { // Your C++ Code char tree[] = ""nlnnlll""; int n = strlen(tree); cout << findDepth(tree, n) << endl; return 0; }",constant,linear "// C code to modify binary tree for // traversal using only right pointer #include using namespace std; // A binary tree node has data, // left child and right child struct Node { int data; struct Node* left; struct Node* right; }; // function that allocates a new node // with the given data and NULL left // and right pointers. struct Node* newNode(int data) { struct Node* node = new struct Node; node->data = data; node->left = NULL; node->right = NULL; return (node); } // Function to modify tree struct Node* modifytree(struct Node* root) { struct Node* right = root->right; struct Node* rightMost = root; // if the left tree exists if (root->left) { // get the right-most of the // original left subtree rightMost = modifytree(root->left); // set root right to left subtree root->right = root->left; root->left = NULL; } // if the right subtree does // not exists we are done! if (!right) return rightMost; // set right pointer of right-most // of the original left subtree rightMost->right = right; // modify the rightsubtree rightMost = modifytree(right); return rightMost; } // printing using right pointer only void printpre(struct Node* root) { while (root != NULL) { cout << root->data << "" ""; root = root->right; } } // Driver program to test above functions int main() { /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ struct Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); modifytree(root); printpre(root); return 0; }",linear,linear "// C++ code to modify binary tree for // traversal using only right pointer #include #include #include #include using namespace std; // A binary tree node has data, // left child and right child struct Node { int data; struct Node* left; struct Node* right; }; // Helper function that allocates a new // node with the given data and NULL // left and right pointers. struct Node* newNode(int data) { struct Node* node = new struct Node; node->data = data; node->left = NULL; node->right = NULL; return (node); } // An iterative process to set the right // pointer of Binary tree void modifytree(struct Node* root) { // Base Case if (root == NULL) return; // Create an empty stack and push root to it stack nodeStack; nodeStack.push(root); /* Pop all items one by one. Do following for every popped item a) print it b) push its right child c) push its left child Note that right child is pushed first so that left is processed first */ struct Node* pre = NULL; while (nodeStack.empty() == false) { // Pop the top item from stack struct Node* node = nodeStack.top(); nodeStack.pop(); // Push right and left children of // the popped node to stack if (node->right) nodeStack.push(node->right); if (node->left) nodeStack.push(node->left); // check if some previous node exists if (pre != NULL) { // set the right pointer of // previous node to current pre->right = node; } // set previous node as current node pre = node; } } // printing using right pointer only void printpre(struct Node* root) { while (root != NULL) { cout << root->data << "" ""; root = root->right; } } // Driver code int main() { /* Constructed binary tree is 10 / \ 8 2 / \ 3 5 */ struct Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); modifytree(root); printpre(root); return 0; }",linear,linear "/* C++ program to construct tree using inorder and preorder traversals */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: char data; node* left; node* right; }; /* Prototypes for utility functions */ int search(char arr[], int strt, int end, char value); node* newNode(char data); /* Recursive function to construct binary of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ node* buildTree(char in[], char pre[], int inStrt, int inEnd) { static int preIndex = 0; if (inStrt > inEnd) return NULL; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ node* tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode->data); /* Using index in Inorder traversal, construct left and right subtress */ tNode->left = buildTree(in, pre, inStrt, inIndex - 1); tNode->right = buildTree(in, pre, inIndex + 1, inEnd); return tNode; } /* UTILITY FUNCTIONS */ /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */ int search(char arr[], int strt, int end, char value) { int i; for (i = strt; i <= end; i++) { if (arr[i] == value) return i; } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(char data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node); } /* This function is here just to test buildTree() */ void printInorder(node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout<data<<"" ""; /* now recur on right child */ printInorder(node->right); } /* Driver code */ int main() { char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' }; char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' }; int len = sizeof(in) / sizeof(in[0]); node* root = buildTree(in, pre, 0, len - 1); /* Let us test the built tree by printing Inorder traversal */ cout << ""Inorder traversal of the constructed tree is \n""; printInorder(root); } // This is code is contributed by rathbhupendra",linear,quadratic "/* C++ program to construct tree using inorder and preorder traversals */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { char data; struct Node* left; struct Node* right; }; struct Node* newNode(char data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } /* Recursive function to construct binary of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ struct Node* buildTree(char in[], char pre[], int inStrt, int inEnd, unordered_map& mp) { static int preIndex = 0; if (inStrt > inEnd) return NULL; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ char curr = pre[preIndex++]; struct Node* tNode = newNode(curr); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = mp[curr]; /* Using index in Inorder traversal, construct left and right subtress */ tNode->left = buildTree(in, pre, inStrt, inIndex - 1, mp); tNode->right = buildTree(in, pre, inIndex + 1, inEnd, mp); return tNode; } // This function mainly creates an unordered_map, then // calls buildTree() struct Node* buldTreeWrap(char in[], char pre[], int len) { // Store indexes of all items so that we // we can quickly find later unordered_map mp; for (int i = 0; i < len; i++) mp[in[i]] = i; return buildTree(in, pre, 0, len - 1, mp); } /* This function is here just to test buildTree() */ void printInorder(struct Node* node) { if (node == NULL) return; printInorder(node->left); printf(""%c "", node->data); printInorder(node->right); } /* Driver program to test above functions */ int main() { char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' }; char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' }; int len = sizeof(in) / sizeof(in[0]); struct Node* root = buldTreeWrap(in, pre, len); /* Let us test the built tree by printing Inorder traversal */ printf(""Inorder traversal of the constructed tree is \n""); printInorder(root); }",linear,linear "// C++ program to construct a tree using // inorder and preorder traversal #include using namespace std; class TreeNode { public: int val; TreeNode* left; TreeNode* right; TreeNode(int x) { val = x; } }; set s; stack st; // Function to build tree using given traversal TreeNode* buildTree(int preorder[], int inorder[],int n) { TreeNode* root = NULL; for (int pre = 0, in = 0; pre < n;) { TreeNode* node = NULL; do { node = new TreeNode(preorder[pre]); if (root == NULL) { root = node; } if (st.size() > 0) { if (s.find(st.top()) != s.end()) { s.erase(st.top()); st.top()->right = node; st.pop(); } else { st.top()->left = node; } } st.push(node); } while (preorder[pre++] != inorder[in] && pre < n); node = NULL; while (st.size() > 0 && in < n && st.top()->val == inorder[in]) { node = st.top(); st.pop(); in++; } if (node != NULL) { s.insert(node); st.push(node); } } return root; } // Function to print tree in Inorder void printInorder(TreeNode* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout << node->val << "" ""; /* now recur on right child */ printInorder(node->right); } // Driver code int main() { int in[] = { 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 }; int pre[] = { 1, 2, 4, 8, 9, 5, 10, 10, 3, 6, 7, 12, 13 }; int len = sizeof(in)/sizeof(int); TreeNode *root = buildTree(pre, in, len); printInorder(root); return 0; } // This code is contributed by Arnab Kundu",linear,linear "/* program to construct tree using inorder and levelorder * traversals */ #include using namespace std; /* A binary tree node */ struct Node { int key; struct Node *left, *right; }; /* Function to find index of value in arr[start...end] */ int search(int arr[], int strt, int end, int value) { for (int i = strt; i <= end; i++) if (arr[i] == value) return i; return -1; } // n is size of level[], m is size of in[] and m < n. This // function extracts keys from level[] which are present in // in[]. The order of extracted keys must be maintained int* extrackKeys(int in[], int level[], int m, int n) { int *newlevel = new int[m], j = 0; for (int i = 0; i < n; i++) if (search(in, 0, m - 1, level[i]) != -1) newlevel[j] = level[i], j++; return newlevel; } /* function that allocates a new node with the given key */ Node* newNode(int key) { Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node); } /* Recursive function to construct binary tree of size n from Inorder traversal in[] and Level Order traversal level[]. inStrt and inEnd are start and end indexes of array in[] Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and levelorder do not form a tree */ Node* buildTree(int in[], int level[], int inStrt, int inEnd, int n) { // If start index is more than the end index if (inStrt > inEnd) return NULL; /* The first node in level order traversal is root */ Node* root = newNode(level[0]); /* If this node has no children then return */ if (inStrt == inEnd) return root; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, root->key); // Extract left subtree keys from level order traversal int* llevel = extrackKeys(in, level, inIndex, n); // Extract right subtree keys from level order traversal int* rlevel = extrackKeys(in + inIndex + 1, level, n - 1, n); /* construct left and right subtrees */ root->left = buildTree(in, llevel, inStrt, inIndex - 1, inIndex - inStrt); root->right = buildTree(in, rlevel, inIndex + 1, inEnd, inEnd - inIndex); // Free memory to avoid memory leak delete[] llevel; delete[] rlevel; return root; } /* utility function to print inorder traversal of binary * tree */ void printInorder(Node* node) { if (node == NULL) return; printInorder(node->left); cout << node->key << "" ""; printInorder(node->right); } /* Driver program to test above functions */ int main() { int in[] = { 4, 8, 10, 12, 14, 20, 22 }; int level[] = { 20, 8, 22, 4, 12, 10, 14 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, level, 0, n - 1, n); /* Let us test the built tree by printing Inorder * traversal */ cout << ""Inorder traversal of the constructed tree is "" ""\n""; printInorder(root); return 0; }",linear,cubic "// C++ program to create a Complete Binary tree from its Linked List // Representation #include #include #include using namespace std; // Linked list node struct ListNode { int data; ListNode* next; }; // Binary tree node structure struct BinaryTreeNode { int data; BinaryTreeNode *left, *right; }; // Function to insert a node at the beginning of the Linked List void push(struct ListNode** head_ref, int new_data) { // allocate node and assign data struct ListNode* new_node = new ListNode; new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node; } // method to create a new binary tree node from the given data BinaryTreeNode* newBinaryTreeNode(int data) { BinaryTreeNode *temp = new BinaryTreeNode; temp->data = data; temp->left = temp->right = NULL; return temp; } // converts a given linked list representing a complete binary tree into the // linked representation of binary tree. void convertList2Binary(ListNode *head, BinaryTreeNode* &root) { // queue to store the parent nodes queue q; // Base Case if (head == NULL) { root = NULL; // Note that root is passed by reference return; } // 1.) The first node is always the root node, and add it to the queue root = newBinaryTreeNode(head->data); q.push(root); // advance the pointer to the next node head = head->next; // until the end of linked list is reached, do the following steps while (head) { // 2.a) take the parent node from the q and remove it from q BinaryTreeNode* parent = q.front(); q.pop(); // 2.c) take next two nodes from the linked list. We will add // them as children of the current parent node in step 2.b. Push them // into the queue so that they will be parents to the future nodes BinaryTreeNode *leftChild = NULL, *rightChild = NULL; leftChild = newBinaryTreeNode(head->data); q.push(leftChild); head = head->next; if (head) { rightChild = newBinaryTreeNode(head->data); q.push(rightChild); head = head->next; } // 2.b) assign the left and right children of parent parent->left = leftChild; parent->right = rightChild; } } // Utility function to traverse the binary tree after conversion void inorderTraversal(BinaryTreeNode* root) { if (root) { inorderTraversal( root->left ); cout << root->data << "" ""; inorderTraversal( root->right ); } } // Driver program to test above functions int main() { // create a linked list shown in above diagram struct ListNode* head = NULL; push(&head, 36); /* Last node of Linked List */ push(&head, 30); push(&head, 25); push(&head, 15); push(&head, 12); push(&head, 10); /* First node of Linked List */ BinaryTreeNode *root; convertList2Binary(head, root); cout << ""Inorder Traversal of the constructed Binary Tree is: \n""; inorderTraversal(root); return 0; }",np,linear "// CPP program to construct binary // tree from given array in level // order fashion Tree Node #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node* left, * right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } // Function to insert nodes in level order Node* insertLevelOrder(int arr[], int i, int n) { Node *root = nullptr; // Base case for recursion if (i < n) { root = newNode(arr[i]); // insert left child root->left = insertLevelOrder(arr, 2 * i + 1, n); // insert right child root->right = insertLevelOrder(arr, 2 * i + 2, n); } return root; } // Function to print tree nodes in // InOrder fashion void inOrder(Node* root) { if (root != NULL) { inOrder(root->left); cout << root->data <<"" ""; inOrder(root->right); } } // Driver program to test above function int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 }; int n = sizeof(arr)/sizeof(arr[0]); Node* root = insertLevelOrder(arr, 0, n); inOrder(root); } // This code is contributed by Chhavi and improved by Thangaraj",linear,linear "// Program for construction of Full Binary Tree #include using namespace std; // A binary tree node has data, pointer to left child // and a pointer to right child class node { public: int data; node* left; node* right; }; // A utility function to create a node node* newNode(int data) { node* temp = new node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // A recursive function to construct Full from pre[] and // post[]. preIndex is used to keep track of index in pre[]. // l is low index and h is high index for the current // subarray in post[] node* constructTreeUtil(int pre[], int post[], int* preIndex, int l, int h, int size) { // Base case if (*preIndex >= size || l > h) return NULL; // The first node in preorder traversal is root. So take // the node at preIndex from preorder and make it root, // and increment preIndex node* root = newNode(pre[*preIndex]); ++*preIndex; // If the current subarray has only one element, no need // to recur if (l == h) return root; // Search the next element of pre[] in post[] int i; for (i = l; i <= h; ++i) if (pre[*preIndex] == post[i]) break; // Use the index of element found in postorder to divide // postorder array in two parts. Left subtree and right // subtree if (i <= h) { root->left = constructTreeUtil(pre, post, preIndex, l, i, size); root->right = constructTreeUtil(pre, post, preIndex, i + 1, h - 1, size); } return root; } // The main function to construct Full Binary Tree from // given preorder and postorder traversals. This function // mainly uses constructTreeUtil() node* constructTree(int pre[], int post[], int size) { int preIndex = 0; return constructTreeUtil(pre, post, &preIndex, 0, size - 1, size); } // A utility function to print inorder traversal of a Binary // Tree void printInorder(node* node) { if (node == NULL) return; printInorder(node->left); cout << node->data << "" ""; printInorder(node->right); } // Driver program to test above functions int main() { int pre[] = { 1, 2, 4, 8, 9, 5, 3, 6, 7 }; int post[] = { 8, 9, 4, 5, 2, 6, 7, 3, 1 }; int size = sizeof(pre) / sizeof(pre[0]); node* root = constructTree(pre, post, size); cout << ""Inorder traversal of the constructed tree: \n""; printInorder(root); return 0; }",logn,constant "// C++ program to construct full binary tree // using its preorder traversal and preorder // traversal of its mirror tree #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // Utility function to create a new tree node Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // A utility function to print inorder traversal // of a Binary Tree void printInorder(Node* node) { if (node == NULL) return; printInorder(node->left); printf(""%d "", node->data); printInorder(node->right); } // A recursive function to construct Full binary tree // from pre[] and preM[]. preIndex is used to keep // track of index in pre[]. l is low index and h is high //index for the current subarray in preM[] Node* constructBinaryTreeUtil(int pre[], int preM[], int &preIndex, int l,int h,int size) { // Base case if (preIndex >= size || l > h) return NULL; // The first node in preorder traversal is root. // So take the node at preIndex from preorder and // make it root, and increment preIndex Node* root = newNode(pre[preIndex]); ++(preIndex); // If the current subarray has only one element, // no need to recur if (l == h) return root; // Search the next element of pre[] in preM[] int i; for (i = l; i <= h; ++i) if (pre[preIndex] == preM[i]) break; // construct left and right subtrees recursively if (i <= h) { root->left = constructBinaryTreeUtil (pre, preM, preIndex, i, h, size); root->right = constructBinaryTreeUtil (pre, preM, preIndex, l+1, i-1, size); } // return root return root; } // function to construct full binary tree // using its preorder traversal and preorder // traversal of its mirror tree void constructBinaryTree(Node* root,int pre[], int preMirror[], int size) { int preIndex = 0; int preMIndex = 0; root = constructBinaryTreeUtil(pre,preMirror, preIndex,0,size-1,size); printInorder(root); } // Driver program to test above functions int main() { int preOrder[] = {1,2,4,5,3,6,7}; int preOrderMirror[] = {1,3,7,6,2,5,4}; int size = sizeof(preOrder)/sizeof(preOrder[0]); Node* root = new Node; constructBinaryTree(root,preOrder,preOrderMirror,size); return 0; }",linear,quadratic "// A program to construct Binary Tree from preorder traversal #include // A binary tree node structure struct node { int data; struct node *left; struct node *right; }; // Utility function to create a new Binary Tree node struct node* newNode (int data) { struct node *temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } /* A recursive function to create a Binary Tree from given pre[] preLN[] arrays. The function returns root of tree. index_ptr is used to update index values in recursive calls. index must be initially passed as 0 */ struct node *constructTreeUtil(int pre[], char preLN[], int *index_ptr, int n) { int index = *index_ptr; // store the current value of index in pre[] // Base Case: All nodes are constructed if (index == n) return NULL; // Allocate memory for this node and increment index for // subsequent recursive calls struct node *temp = newNode ( pre[index] ); (*index_ptr)++; // If this is an internal node, construct left and // right subtrees and link the subtrees if (preLN[index] == 'N') { temp->left = constructTreeUtil(pre, preLN, index_ptr, n); temp->right = constructTreeUtil(pre, preLN, index_ptr, n); } return temp; } // A wrapper over constructTreeUtil() struct node *constructTree(int pre[], char preLN[], int n) { /* Initialize index as 0. Value of index is used in recursion to maintain the current index in pre[] and preLN[] arrays. */ int index = 0; return constructTreeUtil (pre, preLN, &index, n); } // This function is used only for testing void printInorder (struct node* node) { if (node == NULL) return; // First recur on left child printInorder (node->left); // Print the data of node printf(""%d "", node->data); // Now recur on right child printInorder (node->right); } // Driver code int main() { struct node *root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ int pre[] = {10, 30, 20, 5, 15}; char preLN[] = {'N', 'N', 'L', 'L', 'L'}; int n = sizeof(pre)/sizeof(pre[0]); // construct the above tree root = constructTree (pre, preLN, n); // Test the constructed tree printf(""Inorder Traversal of the Constructed Binary Tree: \n""); printInorder (root); return 0; }",linear,linear "// A program to construct Binary Tree from preorder // traversal #include using namespace std; // A binary tree node structure struct node { int data; struct node* left; struct node* right; node(int x) { data = x; left = right = NULL; } }; struct node* constructTree(int pre[], char preLN[], int n) { // Taking an empty Stack stack st; // Setting up root node node* root = new node(pre[0]); // Checking if root is not leaf node if (preLN[0] != 'L') st.push(root); // Iterating over the given node values for (int i = 1; i < n; i++) { node* temp = new node(pre[i]); // Checking if the left position is NULL or not if (!st.top()->left) { st.top()->left = temp; // Checking for leaf node if (preLN[i] != 'L') st.push(temp); } // Checking if the right position is NULL or not else if (!st.top()->right) { st.top()->right = temp; if (preLN[i] != 'L') // Checking for leaf node st.push(temp); } // If left and right of top node is already filles else { while (st.top()->left && st.top()->right) st.pop(); st.top()->right = temp; // Checking for leaf node if (preLN[i] != 'L') st.push(temp); } } // Returning the root of tree return root; } // This function is used only for testing void printInorder(struct node* node) { if (node == NULL) return; // First recur on left child printInorder(node->left); // Print the data of node printf(""%d "", node->data); // Now recur on right child printInorder(node->right); } // Driver code int main() { struct node* root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ int pre[] = { 10, 30, 20, 5, 15 }; char preLN[] = { 'N', 'N', 'L', 'L', 'L' }; int n = sizeof(pre) / sizeof(pre[0]); // construct the above tree root = constructTree(pre, preLN, n); // Test the constructed tree printf(""Inorder Traversal of the Constructed Binary Tree: \n""); printInorder(root); return 0; } // This code is contributed by shubhamrajput6156",linear,linear "// Given an ancestor matrix for binary tree, construct // the tree. #include using namespace std; # define N 6 /* A binary tree node */ struct Node { int data; Node *left, *right; }; /* Helper function to create a new node */ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Constructs tree from ancestor matrix Node* ancestorTree(int mat[][N]) { // Binary array to determine whether // parent is set for node i or not int parent[N] = {0}; // Root will store the root of the constructed tree Node* root = NULL; // Create a multimap, sum is used as key and row // numbers are used as values multimap mm; for (int i = 0; i < N; i++) { int sum = 0; // Initialize sum of this row for (int j = 0; j < N; j++) sum += mat[i][j]; // insert(sum, i) pairs into the multimap mm.insert(pair(sum, i)); } // node[i] will store node for i in constructed tree Node* node[N]; // Traverse all entries of multimap. Note that values // are accessed in increasing order of sum for (auto it = mm.begin(); it != mm.end(); ++it) { // create a new node for every value node[it->second] = newNode(it->second); // To store last processed node. This node will be // root after loop terminates root = node[it->second]; // if non-leaf node if (it->first != 0) { // traverse row 'it->second' in the matrix for (int i = 0; i < N; i++) { // if parent is not set and ancestor exits if (!parent[i] && mat[it->second][i]) { // check for unoccupied left/right node // and set parent of node i if (!node[it->second]->left) node[it->second]->left = node[i]; else node[it->second]->right = node[i]; parent[i] = 1; } } } } return root; } /* Given a binary tree, print its nodes in inorder */ void printInorder(Node* node) { if (node == NULL) return; printInorder(node->left); printf(""%d "", node->data); printInorder(node->right); } // Driver code int main() { int mat[N][N] = {{ 0, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1, 0 }, { 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 1, 0 } }; Node* root = ancestorTree(mat); cout << ""Inorder traversal of tree is \n""; // Function call printInorder(root); return 0; }",quadratic,quadratic "// C++ program to construct ancestor matrix for // given tree. #include using namespace std; #define MAX 100 /* A binary tree node */ struct Node { int data; Node *left, *right; }; // Creating a global boolean matrix for simplicity bool mat[MAX][MAX]; // anc[] stores all ancestors of current node. This // function fills ancestors for all nodes. // It also returns size of tree. Size of tree is // used to print ancestor matrix. int ancestorMatrixRec(Node *root, vector &anc) { /* base case */ if (root == NULL) return 0;; // Update all ancestors of current node int data = root->data; for (int i=0; ileft, anc); int r = ancestorMatrixRec(root->right, anc); // Remove data from list the list of ancestors // as all descendants of it are processed now. anc.pop_back(); return l+r+1; } // This function mainly calls ancestorMatrixRec() void ancestorMatrix(Node *root) { // Create an empty ancestor array vector anc; // Fill ancestor matrix and find size of // tree. int n = ancestorMatrixRec(root, anc); // Print the filled values for (int i=0; idata = data; node->left = node->right = NULL; return (node); } /* Driver program to test above functions*/ int main() { /* Construct the following binary tree 5 / \ 1 2 / \ / 0 4 3 */ Node *root = newnode(5); root->left = newnode(1); root->right = newnode(2); root->left->left = newnode(0); root->left->right = newnode(4); root->right->left = newnode(3); ancestorMatrix(root); return 0; }",quadratic,quadratic "// C++ program to construct ancestor matrix for // given tree. #include using namespace std; #define size 6 int M[size][size]={0}; /* A binary tree node */ struct Node { int data; Node *left, *right; }; /* Helper function to create a new node */ Node* newnode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } void printMatrix(){ for(int i=0;idata; //Since there is no ancestor for root node, // so we doesn't assign it's value as 1 if(index==-1)index=root->data; else M[index][preData]=1; MatrixUtil(root->left,preData); MatrixUtil(root->right,preData); } void Matrix(Node *root){ // Call Func MatrixUtil MatrixUtil(root,-1); //Applying Transitive Closure for the given Matrix for(int i=0;ileft = newnode(1); root->right = newnode(2); root->left->left = newnode(0); root->left->right = newnode(4); root->right->left = newnode(3); Matrix(root); return 0; }",quadratic,quadratic "/* C++ program to construct tree from inorder traversal */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node* left; node* right; }; /* Prototypes of a utility function to get the maximum value in inorder[start..end] */ int max(int inorder[], int strt, int end); /* A utility function to allocate memory for a node */ node* newNode(int data); /* Recursive function to construct binary of size len from Inorder traversal inorder[]. Initial values of start and end should be 0 and len -1. */ node* buildTree (int inorder[], int start, int end) { if (start > end) return NULL; /* Find index of the maximum element from Binary Tree */ int i = max (inorder, start, end); /* Pick the maximum value and make it root */ node *root = newNode(inorder[i]); /* If this is the only element in inorder[start..end], then return it */ if (start == end) return root; /* Using index in Inorder traversal, construct left and right subtress */ root->left = buildTree (inorder, start, i - 1); root->right = buildTree (inorder, i + 1, end); return root; } /* UTILITY FUNCTIONS */ /* Function to find index of the maximum value in arr[start...end] */ int max (int arr[], int strt, int end) { int i, max = arr[strt], maxind = strt; for(i = strt + 1; i <= end; i++) { if(arr[i] > max) { max = arr[i]; maxind = i; } } return maxind; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode (int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return Node; } /* This function is here just to test buildTree() */ void printInorder (node* node) { if (node == NULL) return; /* first recur on left child */ printInorder (node->left); /* then print the data of node */ cout<data<<"" ""; /* now recur on right child */ printInorder (node->right); } /* Driver code*/ int main() { /* Assume that inorder traversal of following tree is given 40 / \ 10 30 / \ 5 28 */ int inorder[] = {5, 10, 40, 30, 28}; int len = sizeof(inorder)/sizeof(inorder[0]); node *root = buildTree(inorder, 0, len - 1); /* Let us test the built tree by printing Inorder traversal */ cout << ""Inorder traversal of the constructed tree is \n""; printInorder(root); return 0; } // This is code is contributed by rathbhupendra",linear,quadratic "// C++ program to construct a Binary Tree from parent array #include using namespace std; struct Node { int data; struct Node* left = NULL; struct Node* right = NULL; Node() {} Node(int x) { data = x; } }; // Function to construct binary tree from parent array. Node* createTree(int parent[], int n) { // Create an array to store the reference // of all newly created nodes corresponding // to node value vector ref; // This root represent the root of the // newly constructed tree Node* root = new Node(); // Create n new tree nodes, each having // a value from 0 to n-1, and store them // in ref for (int i = 0; i < n; i++) { Node* temp = new Node(i); ref.push_back(temp); } // Traverse the parent array and build the tree for (int i = 0; i < n; i++) { // If the parent is -1, set the root // to the current node having // the value i which is stored in ref[i] if (parent[i] == -1) { root = ref[i]; } else { // Check if the parent's left child // is NULL then map the left child // to its parent. if (ref[parent[i]]->left == NULL) ref[parent[i]]->left = ref[i]; else ref[parent[i]]->right = ref[i]; } } // Return the root of the newly constructed tree return root; } // Function for inorder traversal void inorder(Node* root) { if (root != NULL) { inorder(root->left); cout << root->data << "" ""; inorder(root->right); } } // Driver code int main() { int parent[] = { -1, 0, 0, 1, 1, 3, 5 }; int n = sizeof parent / sizeof parent[0]; Node* root = createTree(parent, n); cout << ""Inorder Traversal of constructed tree\n""; inorder(root); return 0; }",linear,linear "/* C++ program to construct tree using inorder and postorder traversals */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; // Utility function to create a new node Node* newNode(int data); /* Prototypes for utility functions */ int search(int arr[], int strt, int end, int value); /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ Node* buildUtil(int in[], int post[], int inStrt, int inEnd, int* pIndex) { // Base case if (inStrt > inEnd) return NULL; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ Node* node = newNode(post[*pIndex]); (*pIndex)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = search(in, inStrt, inEnd, node->data); /* Using index in Inorder traversal, construct left and right subtrees */ node->right = buildUtil(in, post, iIndex + 1, inEnd, pIndex); node->left = buildUtil(in, post, inStrt, iIndex - 1, pIndex); return node; } // This function mainly initializes index of root // and calls buildUtil() Node* buildTree(int in[], int post[], int n) { int pIndex = n - 1; return buildUtil(in, post, 0, n - 1, &pIndex); } /* Function to find index of value in arr[start...end] The function assumes that value is postsent in in[] */ int search(int arr[], int strt, int end, int value) { int i; for (i = strt; i <= end; i++) { if (arr[i] == value) break; } return i; } /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } /* This function is here just to test */ void preOrder(Node* node) { if (node == NULL) return; printf(""%d "", node->data); preOrder(node->left); preOrder(node->right); } // Driver code int main() { int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, post, n); cout << ""Preorder of the constructed tree : \n""; preOrder(root); return 0; }",linear,quadratic "/* C++ program to construct tree using inorder and postorder traversals */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; // Utility function to create a new node Node* newNode(int data); /* Recursive function to construct binary of size n from Inorder traversal in[] and Postorder traversal post[]. Initial values of inStrt and inEnd should be 0 and n -1. The function doesn't do any error checking for cases where inorder and postorder do not form a tree */ Node* buildUtil(int in[], int post[], int inStrt, int inEnd, int* pIndex, unordered_map& mp) { // Base case if (inStrt > inEnd) return NULL; /* Pick current node from Postorder traversal using postIndex and decrement postIndex */ int curr = post[*pIndex]; Node* node = newNode(curr); (*pIndex)--; /* If this node has no children then return */ if (inStrt == inEnd) return node; /* Else find the index of this node in Inorder traversal */ int iIndex = mp[curr]; /* Using index in Inorder traversal, construct left and right subtrees */ node->right = buildUtil(in, post, iIndex + 1, inEnd, pIndex, mp); node->left = buildUtil(in, post, inStrt, iIndex - 1, pIndex, mp); return node; } // This function mainly creates an unordered_map, then // calls buildTreeUtil() struct Node* buildTree(int in[], int post[], int len) { // Store indexes of all items so that we // we can quickly find later unordered_map mp; for (int i = 0; i < len; i++) mp[in[i]] = i; int index = len - 1; // Index in postorder return buildUtil(in, post, 0, len - 1, &index, mp); } /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } /* This function is here just to test */ void preOrder(Node* node) { if (node == NULL) return; printf(""%d "", node->data); preOrder(node->left); preOrder(node->right); } // Driver code int main() { int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); Node* root = buildTree(in, post, n); cout << ""Preorder of the constructed tree : \n""; preOrder(root); return 0; }",linear,linear "// C++ program for above approach #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; } }; /*Tree building function*/ Node *buildTree(int in[], int post[], int n) { // Create Stack of type Node* stack st; // Create Set of type Node* set s; // Initialise postIndex with n - 1 int postIndex = n - 1; // Initialise root with NULL Node* root = NULL; for (int p = n - 1, i = n - 1; p>=0;) { // Initialise node with NULL Node* node = NULL; // Run do-while loop do { // Initialise node with // new Node(post[p]); node = new Node(post[p]); // Check is root is // equal to NULL if (root == NULL) { root = node; } // If size of set // is greater than 0 if (st.size() > 0) { // If st.top() is present in the // set s if (s.find(st.top()) != s.end()) { s.erase(st.top()); st.top()->left = node; st.pop(); } else { st.top()->right = node; } } st.push(node); } while (post[p--] != in[i] && p >=0); node = NULL; // If the stack is not empty and // st.top()->data is equal to in[i] while (st.size() > 0 && i>=0 && st.top()->data == in[i]) { node = st.top(); // Pop elements from stack st.pop(); i--; } // if node not equal to NULL if (node != NULL) { s.insert(node); st.push(node); } } // Return root return root; } /* for print preOrder Traversal */ void preOrder(Node* node) { if (node == NULL) return; printf(""%d "", node->data); preOrder(node->left); preOrder(node->right); } // Driver Code int main() { int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 }; int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 }; int n = sizeof(in) / sizeof(in[0]); // Function Call Node* root = buildTree(in, post, n); cout << ""Preorder of the constructed tree : \n""; // Function Call for preOrder preOrder(root); return 0; }",linear,linear "// C++ program to create a doubly linked list out // of given a ternary tree. #include using namespace std; /* A ternary tree */ struct Node { int data; struct Node *left, *middle, *right; }; /* Helper function that allocates a new node with the given data and assign NULL to left, middle and right pointers.*/ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->middle = node->right = NULL; return node; } /* Utility function that constructs doubly linked list by inserting current node at the end of the doubly linked list by using a tail pointer */ void push(Node** tail_ref, Node* node) { // initialize tail pointer if (*tail_ref == NULL) { *tail_ref = node; // set left, middle and right child to point // to NULL node->left = node->middle = node->right = NULL; return; } // insert node in the end using tail pointer (*tail_ref)->right = node; // set prev of node node->left = (*tail_ref); // set middle and right child to point to NULL node->right = node->middle = NULL; // now tail pointer will point to inserted node (*tail_ref) = node; } /* Create a doubly linked list out of given a ternary tree. by traversing the tree in preorder fashion. */ void TernaryTreeToList(Node* root, Node** head_ref) { // Base case if (root == NULL) return; //create a static tail pointer static Node* tail = NULL; // store left, middle and right nodes // for future calls. Node* left = root->left; Node* middle = root->middle; Node* right = root->right; // set head of the doubly linked list // head will be root of the ternary tree if (*head_ref == NULL) *head_ref = root; // push current node in the end of DLL push(&tail, root); //recurse for left, middle and right child TernaryTreeToList(left, head_ref); TernaryTreeToList(middle, head_ref); TernaryTreeToList(right, head_ref); } // Utility function for printing double linked list. void printList(Node* head) { printf(""Created Double Linked list is:\n""); while (head) { printf(""%d "", head->data); head = head->right; } } // Driver program to test above functions int main() { // Constructing ternary tree as shown in above figure Node* root = newNode(30); root->left = newNode(5); root->middle = newNode(11); root->right = newNode(63); root->left->left = newNode(1); root->left->middle = newNode(4); root->left->right = newNode(8); root->middle->left = newNode(6); root->middle->middle = newNode(7); root->middle->right = newNode(15); root->right->left = newNode(31); root->right->middle = newNode(55); root->right->right = newNode(65); Node* head = NULL; TernaryTreeToList(root, &head); printList(head); return 0; }",linear,linear "// C++ program to create a tree with left child // right sibling representation. #include using namespace std; struct Node { int data; struct Node* next; struct Node* child; }; // Creating new Node Node* newNode(int data) { Node* newNode = new Node; newNode->next = newNode->child = NULL; newNode->data = data; return newNode; } // Adds a sibling to a list with starting with n Node* addSibling(Node* n, int data) { if (n == NULL) return NULL; while (n->next) n = n->next; return (n->next = newNode(data)); } // Add child Node to a Node Node* addChild(Node* n, int data) { if (n == NULL) return NULL; // Check if child list is not empty. if (n->child) return addSibling(n->child, data); else return (n->child = newNode(data)); } // Traverses tree in level order void traverseTree(Node* root) { // Corner cases if (root == NULL) return; cout << root->data << "" ""; if (root->child == NULL) return; // Create a queue and enqueue root queue q; Node* curr = root->child; q.push(curr); while (!q.empty()) { // Take out an item from the queue curr = q.front(); q.pop(); // Print next level of taken out item and enqueue // next level's children while (curr != NULL) { cout << curr->data << "" ""; if (curr->child != NULL) { q.push(curr->child); } curr = curr->next; } } } // Driver code int main() { Node* root = newNode(10); Node* n1 = addChild(root, 2); Node* n2 = addChild(root, 3); Node* n3 = addChild(root, 4); Node* n4 = addChild(n3, 6); Node* n5 = addChild(root, 5); Node* n6 = addChild(n5, 7); Node* n7 = addChild(n5, 8); Node* n8 = addChild(n5, 9); traverseTree(root); return 0; }",linear,linear "/* C++ program to construct a binary tree from the given string */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } /* This function is here just to test */ void preOrder(Node* node) { if (node == NULL) return; printf(""%d "", node->data); preOrder(node->left); preOrder(node->right); } // function to return the index of close parenthesis int findIndex(string str, int si, int ei) { if (si > ei) return -1; // Inbuilt stack stack s; for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s.top() == '(') { s.pop(); // if stack is empty, this is // the required index if (s.empty()) return i; } } } // if not found return -1 return -1; } // function to construct tree from string Node* treeFromString(string str, int si, int ei) { // Base case if (si > ei) return NULL; int num = 0; // In case the number is having more than 1 digit while(si <= ei && str[si] >= '0' && str[si] <= '9') { num *= 10; num += (str[si] - '0'); si++; } // new root Node* root = newNode(num); int index = -1; // if next char is '(' find the index of // its complement ')' if (si <= ei && str[si] == '(') index = findIndex(str, si, ei); // if index found if (index != -1) { // call for left subtree root->left = treeFromString(str, si + 1, index - 1); // call for right subtree root->right = treeFromString(str, index + 2, ei - 1); } return root; } // Driver Code int main() { string str = ""4(2(3)(1))(6(5))""; Node* root = treeFromString(str, 0, str.length() - 1); preOrder(root); }",linear,quadratic "// A simple inorder traversal based // program to convert a Binary Tree to DLL #include using namespace std; // A tree node class node { public: int data; node *left, *right; }; // A utility function to create // a new tree node node *newNode(int data) { node *Node = new node(); Node->data = data; Node->left = Node->right = NULL; return(Node); } // Standard Inorder traversal of tree void inorder(node *root) { if (root != NULL) { inorder(root->left); cout << ""\t"" << root->data; inorder(root->right); } } // Changes left pointers to work as // previous pointers in converted DLL // The function simply does inorder // traversal of Binary Tree and updates // left pointer using previously visited node void fixPrevPtr(node *root) { static node *pre = NULL; if (root != NULL) { fixPrevPtr(root->left); root->left = pre; pre = root; fixPrevPtr(root->right); } } // Changes right pointers to work // as next pointers in converted DLL node *fixNextPtr(node *root) { node *prev = NULL; // Find the right most node // in BT or last node in DLL while (root && root->right != NULL) root = root->right; // Start from the rightmost node, // traverse back using left pointers. // While traversing, change right pointer of nodes. while (root && root->left != NULL) { prev = root; root = root->left; root->right = prev; } // The leftmost node is head // of linked list, return it return (root); } // The main function that converts // BST to DLL and returns head of DLL node *BTToDLL(node *root) { // Set the previous pointer fixPrevPtr(root); // Set the next pointer and return head of DLL return fixNextPtr(root); } // Traverses the DLL from left to right void printList(node *root) { while (root != NULL) { cout<<""\t""<data; root = root->right; } } // Driver code int main(void) { // Let us create the tree // shown in above diagram node *root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); cout<<""\n\t\tInorder Tree Traversal\n\n""; inorder(root); node *head = BTToDLL(root); cout << ""\n\n\t\tDLL Traversal\n\n""; printList(head); return 0; } // This code is contributed by rathbhupendra",linear,linear "// A C++ program for in-place conversion of Binary Tree to // DLL #include using namespace std; /* A binary tree node has data, and left and right pointers */ struct node { int data; node* left; node* right; }; node * bToDLL(node *root) { stack> s; s.push({root, 0}); vector res; bool flag = true; node* head = NULL; node* prev = NULL; while(!s.empty()) { auto x = s.top(); node* t = x.first; int state = x.second; s.pop(); if(state == 3 or t == NULL) continue; s.push({t, state+1}); if(state == 0) s.push({t->left, 0}); else if(state == 1) { if(prev) prev->right = t; t->left = prev; prev = t; if(flag) { head = t; flag = false; } } else if(state == 2) s.push({t->right, 0}); } return head; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(int data) { node* new_node = new node; new_node->data = data; new_node->left = new_node->right = NULL; return (new_node); } /* Function to print nodes in a given doubly linked list */ void printList(node* node) { while (node != NULL) { cout << node->data << "" ""; node = node->right; } } // Driver Code int main() { // Let us create the tree shown in above diagram node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL node* head = bToDLL(root); // Print the converted list printList(head); return 0; }",linear,linear "// C++ program to convert a given Binary Tree to Doubly Linked List #include // Structure for tree and linked list struct Node { int data; Node *left, *right; }; // Utility function for allocating node for Binary // Tree. Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // A simple recursive function to convert a given // Binary tree to Doubly Linked List // root --> Root of Binary Tree // head --> Pointer to head node of created doubly linked list void BToDLL(Node* root, Node*& head) { // Base cases if (root == NULL) return; // Recursively convert right subtree BToDLL(root->right, head); // insert root into DLL root->right = head; // Change left pointer of previous head if (head != NULL) head->left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root->left, head); } // Utility function for printing double linked list. void printList(Node* head) { printf(""Extracted Double Linked list is:\n""); while (head) { printf(""%d "", head->data); head = head->right; } } // Driver program to test above function int main() { /* Constructing below tree 5 / \ 3 6 / \ \ 1 4 8 / \ / \ 0 2 7 9 */ Node* root = newNode(5); root->left = newNode(3); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->right->right = newNode(8); root->left->left->left = newNode(0); root->left->left->right = newNode(2); root->right->right->left = newNode(7); root->right->right->right = newNode(9); Node* head = NULL; BToDLL(root, head); printList(head); return 0; }",linear,linear "// C++ program to convert a binary tree // to its mirror #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 3 1 is changed to... 4 / \ 5 2 / \ 1 3 */ void mirror(struct Node* node) { if (node == NULL) return; else { struct Node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; } } /* Helper function to print Inorder traversal.*/ void inOrder(struct Node* node) { if (node == NULL) return; inOrder(node->left); cout << node->data << "" ""; inOrder(node->right); } // Driver Code int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ cout << ""Inorder traversal of the constructed"" << "" tree is"" << endl; inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ cout << ""\nInorder traversal of the mirror tree"" << "" is \n""; inOrder(root); return 0; } // This code is contributed by Akanksha Rai",linear,linear "// Iterative CPP program to convert a Binary // Tree to its mirror #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } /* Change a tree so that the roles of the left and right pointers are swapped at every node. So the tree... 4 / \ 2 5 / \ 1 3 is changed to... 4 / \ 5 2 / \ 3 1 */ void mirror(Node* root) { if (root == NULL) return; queue q; q.push(root); // Do BFS. While doing BFS, keep swapping // left and right children while (!q.empty()) { // pop top node from queue Node* curr = q.front(); q.pop(); // swap left child with right child swap(curr->left, curr->right); // push left and right children if (curr->left) q.push(curr->left); if (curr->right) q.push(curr->right); } } /* Helper function to print Inorder traversal.*/ void inOrder(struct Node* node) { if (node == NULL) return; inOrder(node->left); cout << node->data << "" ""; inOrder(node->right); } /* Driver program to test mirror() */ int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); /* Print inorder traversal of the input tree */ cout << ""Inorder traversal of the"" "" constructed tree is \n""; inOrder(root); /* Convert tree to its mirror */ mirror(root); /* Print inorder traversal of the mirror tree */ cout << ""\nInorder traversal of the "" ""mirror tree is \n""; inOrder(root); return 0; }",linear,linear "/* c++ program to convert Binary Tree into Doubly Linked List where the nodes are represented spirally. */ #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; /* Given a reference to the head of a list and a node, inserts the node on the front of the list. */ void push(Node** head_ref, Node* node) { // Make right of given node as head and left as // NULL node->right = (*head_ref); node->left = NULL; // change left of head node to given node if ((*head_ref) != NULL) (*head_ref)->left = node ; // move the head to point to the given node (*head_ref) = node; } // Function to prints contents of DLL void printList(Node *node) { while (node != NULL) { cout << node->data << "" ""; node = node->right; } } /* Function to print corner node at each level */ void spiralLevelOrder(Node *root) { // Base Case if (root == NULL) return; // Create an empty deque for doing spiral // level order traversal and enqueue root deque q; q.push_front(root); // create a stack to store Binary Tree nodes // to insert into DLL later stack stk; int level = 0; while (!q.empty()) { // nodeCount indicates number of Nodes // at current level. int nodeCount = q.size(); // Dequeue all Nodes of current level and // Enqueue all Nodes of next level if (level&1) //odd level { while (nodeCount > 0) { // dequeue node from front & push it to // stack Node *node = q.front(); q.pop_front(); stk.push(node); // insert its left and right children // in the back of the deque if (node->left != NULL) q.push_back(node->left); if (node->right != NULL) q.push_back(node->right); nodeCount--; } } else //even level { while (nodeCount > 0) { // dequeue node from the back & push it // to stack Node *node = q.back(); q.pop_back(); stk.push(node); // inserts its right and left children // in the front of the deque if (node->right != NULL) q.push_front(node->right); if (node->left != NULL) q.push_front(node->left); nodeCount--; } } level++; } // head pointer for DLL Node* head = NULL; // pop all nodes from stack and // push them in the beginning of the list while (!stk.empty()) { push(&head, stk.top()); stk.pop(); } cout << ""Created DLL is:\n""; printList(head); } // Utility function to create a new tree Node Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver program to test above functions int main() { // Let us create binary tree shown in above diagram Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->left->left->left = newNode(8); root->left->left->right = newNode(9); root->left->right->left = newNode(10); root->left->right->right = newNode(11); //root->right->left->left = newNode(12); root->right->left->right = newNode(13); root->right->right->left = newNode(14); //root->right->right->right = newNode(15); spiralLevelOrder(root); return 0; }",linear,linear "// C++ Program to convert a Binary Tree // to a Circular Doubly Linked List #include using namespace std; // To represents a node of a Binary Tree struct Node { struct Node *left, *right; int data; }; // A function that appends rightList at the end // of leftList. Node* concatenate(Node* leftList, Node* rightList) { // If either of the list is empty // then return the other list if (leftList == NULL) return rightList; if (rightList == NULL) return leftList; // Store the last Node of left List Node* leftLast = leftList->left; // Store the last Node of right List Node* rightLast = rightList->left; // Connect the last node of Left List // with the first Node of the right List leftLast->right = rightList; rightList->left = leftLast; // Left of first node points to // the last node in the list leftList->left = rightLast; // Right of last node refers to the first // node of the List rightLast->right = leftList; return leftList; } // Function converts a tree to a circular Linked List // and then returns the head of the Linked List Node* bTreeToCList(Node* root) { if (root == NULL) return NULL; // Recursively convert left and right subtrees Node* left = bTreeToCList(root->left); Node* right = bTreeToCList(root->right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root->left = root->right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List void displayCList(Node* head) { cout << ""Circular Linked List is :\n""; Node* itr = head; do { cout << itr->data << "" ""; itr = itr->right; } while (head != itr); cout << ""\n""; } // Create a new Node and return its address Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver Program to test above function int main() { Node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); Node* head = bTreeToCList(root); displayCList(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",logn,linear "// A C++ program for in-place conversion of Binary Tree to // CDLL #include using namespace std; /* A binary tree node has - data , left and right pointers */ struct Node { int data; Node* left; Node* right; }; // A utility function that converts given binary tree to // a doubly linked list // root --> the root of the binary tree // head --> head of the created doubly linked list Node* BTree2DoublyLinkedList(Node* root, Node** head) { // Base case if (root == NULL) return root; // Initialize previously visited node as NULL. This is // static so that the same value is accessible in all // recursive calls static Node* prev = NULL; // Recursively convert left subtree BTree2DoublyLinkedList(root->left, head); // Now convert this node if (prev == NULL) *head = root; else { root->left = prev; prev->right = root; } prev = root; // Finally convert right subtree BTree2DoublyLinkedList(root->right, head); return prev; } // A simple recursive function to convert a given Binary // tree to Circular Doubly Linked List using a utility // function root --> Root of Binary Tree tail --> Pointer to // tail node of created circular doubly linked list Node* BTree2CircularDoublyLinkedList(Node* root) { Node* head = NULL; Node* tail = BTree2DoublyLinkedList(root, &head); // make the changes to convert a DLL to CDLL tail->right = head; head->left = tail; // return the head of the created CDLL return head; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node* newNode(int data) { Node* new_node = new Node; new_node->data = data; new_node->left = new_node->right = NULL; return (new_node); } /* Function to print nodes in a given circular doubly linked * list */ void printList(Node* head) { if (head == NULL) return; Node* ptr = head; do { cout << ptr->data << "" ""; ptr = ptr->right; } while (ptr != head); } /* Driver program to test above functions*/ int main() { // Let us create the tree shown in above diagram Node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL Node* head = BTree2CircularDoublyLinkedList(root); // Print the converted list printList(head); return 0; } // This code was contributed by Abhijeet // Kumar(abhijeet19403)",logn,linear "// C++ program to convert a ternary expression to // a tree. #include using namespace std; // tree structure struct Node { char data; Node *left, *right; }; // function create a new node Node *newNode(char Data) { Node *new_node = new Node; new_node->data = Data; new_node->left = new_node->right = NULL; return new_node; } // Function to convert Ternary Expression to a Binary // Tree. It return the root of tree // Notice that we pass index i by reference because we // want to skip the characters in the subtree Node *convertExpression(string str, int & i) { // store current character of expression_string // [ 'a' to 'z'] Node * root =newNode(str[i]); //If it was last character return //Base Case if(i==str.length()-1) return root; // Move ahead in str i++; //If the next character is '?'.Then there will be subtree for the current node if(str[i]=='?') { //skip the '?' i++; // construct the left subtree // Notice after the below recursive call i will point to ':' // just before the right child of current node since we pass i by reference root->left = convertExpression(str,i); //skip the ':' character i++; //construct the right subtree root->right = convertExpression(str,i); return root; } //If the next character is not '?' no subtree just return it else return root; } // function print tree void printTree( Node *root) { if (!root) return ; cout << root->data <<"" ""; printTree(root->left); printTree(root->right); } // Driver program to test above function int main() { string expression = ""a?b?c:d:e""; int i=0; Node *root = convertExpression(expression, i); printTree(root) ; return 0; }",linear,linear "// C++ program for Minimum swap required // to convert binary tree to binary search tree #include using namespace std; // Inorder Traversal of Binary Tree void inorder(int a[], std::vector &v, int n, int index) { // if index is greater or equal to vector size if(index >= n) return; inorder(a, v, n, 2 * index + 1); // push elements in vector v.push_back(a[index]); inorder(a, v, n, 2 * index + 2); } // Function to find minimum swaps to sort an array int minSwaps(std::vector &v) { std::vector > t(v.size()); int ans = 0; for(int i = 0; i < v.size(); i++) t[i].first = v[i], t[i].second = i; sort(t.begin(), t.end()); for(int i = 0; i < t.size(); i++) { // second element is equal to i if(i == t[i].second) continue; else { // swapping of elements swap(t[i].first, t[t[i].second].first); swap(t[i].second, t[t[i].second].second); } // Second is not equal to i if(i != t[i].second) --i; ans++; } return ans; } // Driver code int main() { int a[] = { 5, 6, 7, 8, 9, 10, 11 }; int n = sizeof(a) / sizeof(a[0]); std::vector v; inorder(a, v, n, 0); cout << minSwaps(v) << endl; } // This code is contributed by code_freak",linear,nlogn "/* Program to check children sum property */ #include using namespace std; /* A binary tree node has data, left child and right child */ struct node { int data; struct node* left; struct node* right; }; /* returns 1 if children sum property holds for the given node and both of its children*/ int isSumProperty(struct node* node) { /* left_data is left child data and right_data is for right child data*/ int sum = 0; /* If node is NULL or it's a leaf node then return true */ if (node == NULL || (node->left == NULL && node->right == NULL)) return 1; else { /* If left child is not present then 0 is used as data of left child */ if (node->left != NULL) sum += node->left->data; /* If right child is not present then 0 is used as data of right child */ if (node->right != NULL) sum += node->right->data; /* if the node and both of its children satisfy the property return 1 else 0*/ return ((node->data == sum) && isSumProperty(node->left) && isSumProperty(node->right)); } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Driver Code int main() { struct node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->right = newNode(2); // Function call if (isSumProperty(root)) cout << ""The given tree satisfies "" << ""the children sum property ""; else cout << ""The given tree does not satisfy "" << ""the children sum property ""; getchar(); return 0; } // This code is contributed by Akanksha Rai",logn,linear "// C++ program to check if two Nodes in a binary tree are // cousins #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // A utility function to create a new Binary Tree Node struct Node* newNode(int item) { struct Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } // Recursive function to check if two Nodes are siblings int isSibling(struct Node* root, struct Node* a, struct Node* b) { // Base case if (root == NULL) return 0; return ((root->left == a && root->right == b) || (root->left == b && root->right == a) || isSibling(root->left, a, b) || isSibling(root->right, a, b)); } // Recursive function to find level of Node 'ptr' in a // binary tree int level(struct Node* root, struct Node* ptr, int lev) { // base cases if (root == NULL) return 0; if (root == ptr) return lev; // Return level if Node is present in left subtree int l = level(root->left, ptr, lev + 1); if (l != 0) return l; // Else search in right subtree return level(root->right, ptr, lev + 1); } // Returns 1 if a and b are cousins, otherwise 0 int isCousin(struct Node* root, struct Node* a, struct Node* b) { // 1. The two Nodes should be on the same level in the // binary tree. // 2. The two Nodes should not be siblings (means that // they should // not have the same parent Node). if ((level(root, a, 1) == level(root, b, 1)) && !(isSibling(root, a, b))) return 1; else return 0; } // Driver Program to test above functions int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->right = newNode(15); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); struct Node *Node1, *Node2; Node1 = root->left->left; Node2 = root->right->right; if (isCousin(root, Node1, Node2)) printf(""Yes\n""); else printf(""No\n""); return 0; } // This code is contributed by ajaymakwana",linear,linear "// C++ program to check if all leaves // are at same level #include using namespace std; // A binary tree node struct Node { int data; struct Node *left, *right; }; // A utility function to allocate // a new tree node struct Node* newNode(int data) { struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node; } /* Recursive function which checks whether all leaves are at same level */ bool checkUtil(struct Node *root, int level, int *leafLevel) { // Base case if (root == NULL) return true; // If a leaf node is encountered if (root->left == NULL && root->right == NULL) { // When a leaf node is found // first time if (*leafLevel == 0) { *leafLevel = level; // Set first found leaf's level return true; } // If this is not first leaf node, compare // its level with first leaf's level return (level == *leafLevel); } // If this node is not leaf, recursively // check left and right subtrees return checkUtil(root->left, level + 1, leafLevel) && checkUtil(root->right, level + 1, leafLevel); } /* The main function to check if all leafs are at same level. It mainly uses checkUtil() */ bool check(struct Node *root) { int level = 0, leafLevel = 0; return checkUtil(root, level, &leafLevel); } // Driver Code int main() { // Let us create tree shown in third example struct Node *root = newNode(12); root->left = newNode(5); root->left->left = newNode(3); root->left->right = newNode(9); root->left->left->left = newNode(1); root->left->right->left = newNode(1); if (check(root)) cout << ""Leaves are at same level\n""; else cout << ""Leaves are not at same level\n""; getchar(); return 0; } // This code is contributed // by Akanksha Rai",linear,linear "// C++ program to check if all leaf nodes are at // same level of binary tree #include using namespace std; // tree node struct Node { int data; Node *left, *right; }; // returns a new tree Node Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // return true if all leaf nodes are // at same level, else false int checkLevelLeafNode(Node* root) { if (!root) return 1; // create a queue for level order traversal queue q; q.push(root); int result = INT_MAX; int level = 0; // traverse until the queue is empty while (!q.empty()) { int size = q.size(); level += 1; // traverse for complete level while(size > 0){ Node* temp = q.front(); q.pop(); // check for left child if (temp->left) { q.push(temp->left); // if its leaf node if(!temp->left->right && !temp->left->left){ // if it's first leaf node, then update result if (result == INT_MAX) result = level; // if it's not first leaf node, then compare // the level with level of previous leaf node else if (result != level) return 0; } } // check for right child if (temp->right){ q.push(temp->right); // if it's leaf node if (!temp->right->left && !temp->right->right) // if it's first leaf node till now, // then update the result if (result == INT_MAX) result = level; // if it is not the first leaf node, // then compare the level with level // of previous leaf node else if(result != level) return 0; } size -= 1; } } return 1; } // driver program int main() { // construct a tree Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); int result = checkLevelLeafNode(root); if (result) cout << ""All leaf nodes are at same level\n""; else cout << ""Leaf nodes not at same level\n""; return 0; }",linear,linear "// C++ program to check if there exist an edge whose // removal creates two trees of same size #include using namespace std; struct Node { int data; struct Node* left, *right; }; // utility function to create a new node struct Node* newNode(int x) { struct Node* temp = new Node; temp->data = x; temp->left = temp->right = NULL; return temp; }; // To calculate size of tree with given root int count(Node* root) { if (root==NULL) return 0; return count(root->left) + count(root->right) + 1; } // This function returns true if there is an edge // whose removal can divide the tree in two halves // n is size of tree bool checkRec(Node* root, int n) { // Base cases if (root ==NULL) return false; // Check for root if (count(root) == n-count(root)) return true; // Check for rest of the nodes return checkRec(root->left, n) || checkRec(root->right, n); } // This function mainly uses checkRec() bool check(Node *root) { // Count total nodes in given tree int n = count(root); // Now recursively check all nodes return checkRec(root, n); } // Driver code int main() { struct Node* root = newNode(5); root->left = newNode(1); root->right = newNode(6); root->left->left = newNode(3); root->right->left = newNode(7); root->right->right = newNode(4); check(root)? printf(""YES"") : printf(""NO""); return 0; }",linear,quadratic "// C++ program to check if there exist an edge whose // removal creates two trees of same size #include using namespace std; struct Node { int data; struct Node* left, *right; }; // utility function to create a new node struct Node* newNode(int x) { struct Node* temp = new Node; temp->data = x; temp->left = temp->right = NULL; return temp; }; // To calculate size of tree with given root int count(Node* root) { if (root==NULL) return 0; return count(root->left) + count(root->right) + 1; } // This function returns size of tree rooted with given // root. It also set ""res"" as true if there is an edge // whose removal divides tree in two halves. // n is size of tree int checkRec(Node* root, int n, bool &res) { // Base case if (root == NULL) return 0; // Compute sizes of left and right children int c = checkRec(root->left, n, res) + 1 + checkRec(root->right, n, res); // If required property is true for current node // set ""res"" as true if (c == n-c) res = true; // Return size return c; } // This function mainly uses checkRec() bool check(Node *root) { // Count total nodes in given tree int n = count(root); // Initialize result and recursively check all nodes bool res = false; checkRec(root, n, res); return res; } // Driver code int main() { struct Node* root = newNode(5); root->left = newNode(1); root->right = newNode(6); root->left->left = newNode(3); root->right->left = newNode(7); root->right->right = newNode(4); check(root)? printf(""YES"") : printf(""NO""); return 0; }",linear,linear "/* C++ program to check if all three given traversals are of the same tree */ #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // Utility function to create a new tree node Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } /* Function to find index of value in arr[start...end] The function assumes that value is present in in[] */ int search(int arr[], int strt, int end, int value) { for (int i = strt; i <= end; i++) { if(arr[i] == value) return i; } } /* Recursive function to construct binary tree of size len from Inorder traversal in[] and Preorder traversal pre[]. Initial values of inStrt and inEnd should be 0 and len -1. The function doesn't do any error checking for cases where inorder and preorder do not form a tree */ Node* buildTree(int in[], int pre[], int inStrt, int inEnd) { static int preIndex = 0; if(inStrt > inEnd) return NULL; /* Pick current node from Preorder traversal using preIndex and increment preIndex */ Node *tNode = newNode(pre[preIndex++]); /* If this node has no children then return */ if (inStrt == inEnd) return tNode; /* Else find the index of this node in Inorder traversal */ int inIndex = search(in, inStrt, inEnd, tNode->data); /* Using index in Inorder traversal, construct left and right subtress */ tNode->left = buildTree(in, pre, inStrt, inIndex-1); tNode->right = buildTree(in, pre, inIndex+1, inEnd); return tNode; } /* function to compare Postorder traversal on constructed tree and given Postorder */ int checkPostorder(Node* node, int postOrder[], int index) { if (node == NULL) return index; /* first recur on left child */ index = checkPostorder(node->left,postOrder,index); /* now recur on right child */ index = checkPostorder(node->right,postOrder,index); /* Compare if data at current index in both Postorder traversals are same */ if (node->data == postOrder[index]) index++; else return -1; return index; } // Driver program to test above functions int main() { int inOrder[] = {4, 2, 5, 1, 3}; int preOrder[] = {1, 2, 4, 5, 3}; int postOrder[] = {4, 5, 2, 3, 1}; int len = sizeof(inOrder)/sizeof(inOrder[0]); // build tree from given // Inorder and Preorder traversals Node *root = buildTree(inOrder, preOrder, 0, len - 1); // compare postorder traversal on constructed // tree with given Postorder traversal int index = checkPostorder(root,postOrder,0); // If both postorder traversals are same if (index == len) cout << ""Yes""; else cout << ""No""; return 0; }",linear,quadratic "#include using namespace std; struct Node { int data; Node *left, *right; Node(int val) { data = val; left = right = NULL; } }; Node* buildTreeFromInorderPreorder( int inStart, int inEnd, int& preIndex, int preorder[], unordered_map& inorderIndexMap, bool& notPossible) { if (inStart > inEnd) return NULL; // build the current Node int rootData = preorder[preIndex]; Node* root = new Node(rootData); preIndex++; // find the node in inorderIndexMap if (inorderIndexMap.find(rootData) == inorderIndexMap.end()) { notPossible = true; return root; } int inorderIndex = inorderIndexMap[rootData]; if (!(inStart <= inorderIndex && inorderIndex <= inEnd)) { notPossible = true; return root; } int leftInorderStart = inStart, leftInorderEnd = inorderIndex - 1, rightInorderStart = inorderIndex + 1, rightInorderEnd = inEnd; root->left = buildTreeFromInorderPreorder( leftInorderStart, leftInorderEnd, preIndex, preorder, inorderIndexMap, notPossible); if (notPossible) return root; root->right = buildTreeFromInorderPreorder( rightInorderStart, rightInorderEnd, preIndex, preorder, inorderIndexMap, notPossible); return root; } bool checkPostorderCorrect(Node* root, int& postIndex, int postorder[]) { if (!root) return true; if (!checkPostorderCorrect(root->left, postIndex, postorder)) return false; if (!checkPostorderCorrect(root->right, postIndex, postorder)) return false; return (root->data == postorder[postIndex++]); } void printPostorder(Node* root) { if (!root) return; printPostorder(root->left); printPostorder(root->right); cout << root->data << "", ""; } void printInorder(Node* root) { if (!root) return; printInorder(root->left); cout << root->data << "", ""; printInorder(root->right); } bool checktree(int preorder[], int inorder[], int postorder[], int N) { // Your code goes here if (N == 0) return true; unordered_map inorderIndexMap; for (int i = 0; i < N; i++) inorderIndexMap[inorder[i]] = i; int preIndex = 0; // return checkInorderPreorder(0, N - 1, preIndex, // preorder, inorderIndexMap) && // checkInorderPostorder(0, N - 1, postIndex, postorder, // inorderIndexMap); bool notPossible = false; Node* root = buildTreeFromInorderPreorder( 0, N - 1, preIndex, preorder, inorderIndexMap, notPossible); if (notPossible) return false; int postIndex = 0; return checkPostorderCorrect(root, postIndex, postorder); } // Driver program to test above functions int main() { int inOrder[] = { 4, 2, 5, 1, 3 }; int preOrder[] = { 1, 2, 4, 5, 3 }; int postOrder[] = { 4, 5, 2, 3, 1 }; int len = sizeof(inOrder) / sizeof(inOrder[0]); // If both postorder traversals are same if (checktree(preOrder, inOrder, postOrder, len)) cout << ""Yes""; else cout << ""No""; return 0; }",linear,linear "// C++ code to check if leaf traversals // of two Binary Trees are same or not. #include using namespace std; // Binary Tree Node struct Node { int data; Node* left; Node* right; }; // Returns new Node with data as // input to below function. Node* newNode(int d) { Node* temp = new Node; temp->data = d; temp->left = NULL; temp->right = NULL; return temp; } // checks if a given node is leaf or not. bool isLeaf(Node* root) { if (root == NULL) return false; if (!root->left && !root->right) return true; return false; } // iterative function. // returns true if leaf traversals // are same, else false. bool isSame(Node* root1, Node* root2) { stack s1; stack s2; // push root1 to empty stack s1. s1.push(root1); // push root2 to empty stack s2. s2.push(root2); // loop until either of stacks are non-empty. while (!s1.empty() || !s2.empty()) { // this means one of the stacks has // extra leaves, hence return false. if (s1.empty() || s2.empty()) return false; Node* temp1 = s1.top(); s1.pop(); while (temp1 != NULL && !isLeaf(temp1)) { // Push right child if exists if (temp1->right) s1.push(temp1->right); // Push left child if exists if (temp1->left) s1.push(temp1->left); // Note that right child(if exists) // is pushed before left child(if exists). temp1 = s1.top(); s1.pop(); } Node* temp2 = s2.top(); s2.pop(); while (temp2 != NULL && !isLeaf(temp2)) { // Push right child if exists if (temp2->right) s2.push(temp2->right); // Push left child if exists if (temp2->left) s2.push(temp2->left); temp2 = s2.top(); s2.pop(); } if (!temp1 && temp2 || temp1 && !temp2) return false; if (temp1 && temp2 && temp1->data!=temp2->data) { return false; } } // all leaves are matched return true; } // Driver Code int main() { Node* root1 = newNode(1); root1->left = newNode(2); root1->right = newNode(3); root1->left->left = newNode(4); root1->right->left = newNode(6); root1->right->right = newNode(7); Node* root2 = newNode(0); root2->left = newNode(1); root2->right = newNode(5); root2->left->right = newNode(4); root2->right->left = newNode(6); root2->right->right = newNode(7); if (isSame(root1, root2)) cout << ""Same""; else cout << ""Not Same""; return 0; } // This code is contributed // by AASTHA VARMA",nlogn,linear "// C++ program to check whether a given Binary Tree is full or not #include using namespace std; /* Tree node structure */ struct Node { int key; struct Node *left, *right; }; /* Helper function that allocates a new node with the given key and NULL left and right pointer. */ struct Node *newNode(char k) { struct Node *node = new Node; node->key = k; node->right = node->left = NULL; return node; } /* This function tests if a binary tree is a full binary tree. */ bool isFullTree (struct Node* root) { // If empty tree if (root == NULL) return true; // If leaf node if (root->left == NULL && root->right == NULL) return true; // If both left and right are not NULL, and left & right subtrees // are full if ((root->left) && (root->right)) return (isFullTree(root->left) && isFullTree(root->right)); // We reach here when none of the above if conditions work return false; } // Driver Program int main() { struct Node* root = NULL; root = newNode(10); root->left = newNode(20); root->right = newNode(30); root->left->right = newNode(40); root->left->left = newNode(50); root->right->left = newNode(60); root->right->right = newNode(70); root->left->left->left = newNode(80); root->left->left->right = newNode(90); root->left->right->left = newNode(80); root->left->right->right = newNode(90); root->right->left->left = newNode(80); root->right->left->right = newNode(90); root->right->right->left = newNode(80); root->right->right->right = newNode(90); if (isFullTree(root)) cout << ""The Binary Tree is full\n""; else cout << ""The Binary Tree is not full\n""; return(0); } // This code is contributed by shubhamsingh10",linear,linear "// c++ program to check whether a given BT is full or not #include using namespace std; // Tree node structure struct Node { int val; Node *left, *right; }; // fun that creates and returns a new node Node* newNode(int data) { Node* node = new Node(); node->val = data; node->left = node->right = NULL; return node; } // helper fun to check leafnode bool isleafnode(Node* root) { return !root->left && !root->right; } // fun checks whether the given BT is a full BT or not bool isFullTree(Node* root) { // if tree is empty if (!root) return true; queue q; q.push(root); while (!q.empty()) { root = q.front(); q.pop(); // null indicates - not a full BT if (root == NULL) return false; // if its not a leafnode then the current node // should contain both left and right pointers. if (!isleafnode(root)) { q.push(root->left); q.push(root->right); } } return true; } int main() { Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); if (isFullTree(root)) cout << ""The Binary Tree is full\n""; else cout << ""The Binary Tree is not full\n""; return 0; } // This code is contributed by Modem Upendra.",linear,linear "// C++ implementation to check whether a binary // tree is a full binary tree or not #include using namespace std; // structure of a node of binary tree struct Node { int data; Node *left, *right; }; // function to get a new node Node* getNode(int data) { // allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // function to check whether a binary tree // is a full binary tree or not bool isFullBinaryTree(Node* root) { // if tree is empty if (!root) return true; // queue used for level order traversal queue q; // push 'root' to 'q' q.push(root); // traverse all the nodes of the binary tree // level by level until queue is empty while (!q.empty()) { // get the pointer to 'node' at front // of queue Node* node = q.front(); q.pop(); // if it is a leaf node then continue if (node->left == NULL && node->right == NULL) continue; // if either of the child is not null and the // other one is null, then binary tree is not // a full binary tee if (node->left == NULL || node->right == NULL) return false; // push left and right childs of 'node' // on to the queue 'q' q.push(node->left); q.push(node->right); } // binary tree is a full binary tee return true; } // Driver program to test above int main() { Node* root = getNode(1); root->left = getNode(2); root->right = getNode(3); root->left->left = getNode(4); root->left->right = getNode(5); if (isFullBinaryTree(root)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,linear "// C++ program to check if a given binary tree is complete // or not #include using namespace std; // A binary tree node has data, pointer to left child and a // pointer to right child struct node { int data; struct node* left; struct node* right; }; // Given a binary tree, return true if the tree is complete // else false bool isCompleteBT(node* root) { // Base Case: An empty tree is complete Binary Tree if (root == NULL) return true; // Create an empty queue // int rear, front; // node **queue = createQueue(&front, &rear); queue q; q.push(root); // Create a flag variable which will be set true when a // non full node is seen bool flag = false; // Do level order traversal using queue. // enQueue(queue, &rear, root); while (!q.empty()) { node* temp = q.front(); q.pop(); /* Check if left child is present*/ if (temp->left) { // If we have seen a non full node, and we see a // node with non-empty left child, then the // given tree is not a complete Binary Tree if (flag == true) return false; q.push(temp->left); // Enqueue Left Child } // If this a non-full node, set the flag as true else flag = true; /* Check if right child is present*/ if (temp->right) { // If we have seen a non full node, and we see a // node with non-empty right child, then the // given tree is not a complete Binary Tree if (flag == true) return false; q.push(temp->right); // Enqueue Right Child } // If this a non-full node, set the flag as true else flag = true; } // If we reach here, then the tree is complete Binary // Tree return true; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } /* Driver code*/ int main() { /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ / 4 5 6 */ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); if (isCompleteBT(root) == true) cout << ""Complete Binary Tree""; else cout << ""NOT Complete Binary Tree""; return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)",linear,linear "/* Program to check if a given Binary Tree is balanced like a Red-Black Tree */ #include using namespace std; struct Node { int key; Node *left, *right; }; /* utility that allocates a new Node with the given key */ Node* newNode(int key) { Node* node = new Node; node->key = key; node->left = node->right = NULL; return (node); } // Returns returns tree if the Binary tree is balanced like a Red-Black // tree. This function also sets value in maxh and minh (passed by // reference). maxh and minh are set as maximum and minimum heights of root. bool isBalancedUtil(Node *root, int &maxh, int &minh) { // Base case if (root == NULL) { maxh = minh = 0; return true; } int lmxh, lmnh; // To store max and min heights of left subtree int rmxh, rmnh; // To store max and min heights of right subtree // Check if left subtree is balanced, also set lmxh and lmnh if (isBalancedUtil(root->left, lmxh, lmnh) == false) return false; // Check if right subtree is balanced, also set rmxh and rmnh if (isBalancedUtil(root->right, rmxh, rmnh) == false) return false; // Set the max and min heights of this node for the parent call maxh = max(lmxh, rmxh) + 1; minh = min(lmnh, rmnh) + 1; // See if this node is balanced if (maxh <= 2*minh) return true; return false; } // A wrapper over isBalancedUtil() bool isBalanced(Node *root) { int maxh, minh; return isBalancedUtil(root, maxh, minh); } /* Driver program to test above functions*/ int main() { Node * root = newNode(10); root->left = newNode(5); root->right = newNode(100); root->right->left = newNode(50); root->right->right = newNode(150); root->right->left->left = newNode(40); isBalanced(root)? cout << ""Balanced"" : cout << ""Not Balanced""; return 0; }",linear,linear "// C++ program to check if two trees are mirror // of each other #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node* left, *right; }; /* Given two trees, return true if they are mirror of each other */ /*As function has to return bool value instead integer value*/ bool areMirror(Node* a, Node* b) { /* Base case : Both empty */ if (a==NULL && b==NULL) return true; // If only one is empty if (a==NULL || b == NULL) return false; /* Both non-empty, compare them recursively Note that in recursive calls, we pass left of one tree and right of other tree */ return a->data == b->data && areMirror(a->left, b->right) && areMirror(a->right, b->left); } /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return(node); } /* Driver program to test areMirror() */ int main() { Node *a = newNode(1); Node *b = newNode(1); a->left = newNode(2); a->right = newNode(3); a->left->left = newNode(4); a->left->right = newNode(5); b->left = newNode(3); b->right = newNode(2); b->right->left = newNode(5); b->right->right = newNode(4); areMirror(a, b)? cout << ""Yes"" : cout << ""No""; return 0; }",logn,linear "// C++ implementation to check whether the two // binary trees are mirrors of each other or not #include using namespace std; // structure of a node in binary tree struct Node { int data; struct Node *left, *right; }; // Utility function to create and return // a new node for a binary tree struct Node* newNode(int data) { struct Node *temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // function to check whether the two binary trees // are mirrors of each other or not string areMirrors(Node *root1, Node *root2) { stack st1, st2; while (1) { // iterative inorder traversal of 1st tree and // reverse inorder traversal of 2nd tree while (root1 && root2) { // if the corresponding nodes in the two traversal // have different data values, then they are not // mirrors of each other. if (root1->data != root2->data) return ""No""; st1.push(root1); st2.push(root2); root1 = root1->left; root2 = root2->right; } // if at any point one root becomes null and // the other root is not null, then they are // not mirrors. This condition verifies that // structures of tree are mirrors of each other. if (!(root1 == NULL && root2 == NULL)) return ""No""; if (!st1.empty() && !st2.empty()) { root1 = st1.top(); root2 = st2.top(); st1.pop(); st2.pop(); /* we have visited the node and its left subtree. Now, it's right subtree's turn */ root1 = root1->right; /* we have visited the node and its right subtree. Now, it's left subtree's turn */ root2 = root2->left; } // both the trees have been completely traversed else break; } // trees are mirrors of each other return ""Yes""; } // Driver program to test above int main() { // 1st binary tree formation Node *root1 = newNode(1); /* 1 */ root1->left = newNode(3); /* / \ */ root1->right = newNode(2); /* 3 2 */ root1->right->left = newNode(5); /* / \ */ root1->right->right = newNode(4); /* 5 4 */ // 2nd binary tree formation Node *root2 = newNode(1); /* 1 */ root2->left = newNode(2); /* / \ */ root2->right = newNode(3); /* 2 3 */ root2->left->left = newNode(4); /* / \ */ root2->left->right = newNode(5); /* 4 5 */ cout << areMirrors(root1, root2); return 0; } ",linear,linear "// C++ program to check if a given Binary // Tree is symmetric or not #include using namespace std; // A Binary Tree Node struct Node { int key; struct Node* left, *right; }; // Utility function to create new Node Node *newNode(int key) { Node *temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } // Returns true if a tree is symmetric // i.e. mirror image of itself bool isSymmetric(struct Node* root) { if(root == NULL) return true; // If it is a single tree node, then // it is a symmetric tree. if(!root->left && !root->right) return true; queue q; // Add root to queue two times so that // it can be checked if either one child // alone is NULL or not. q.push(root); q.push(root); // To store two nodes for checking their // symmetry. Node* leftNode, *rightNode; while(!q.empty()){ // Remove first two nodes to check // their symmetry. leftNode = q.front(); q.pop(); rightNode = q.front(); q.pop(); // if both left and right nodes // exist, but have different // values--> inequality, return false if(leftNode->key != rightNode->key){ return false; } // Push left child of left subtree node // and right child of right subtree // node in queue. if(leftNode->left && rightNode->right){ q.push(leftNode->left); q.push(rightNode->right); } // If only one child is present alone // and other is NULL, then tree // is not symmetric. else if (leftNode->left || rightNode->right) return false; // Push right child of left subtree node // and left child of right subtree node // in queue. if(leftNode->right && rightNode->left){ q.push(leftNode->right); q.push(rightNode->left); } // If only one child is present alone // and other is NULL, then tree // is not symmetric. else if(leftNode->right || rightNode->left) return false; } return true; } // Driver program int main() { // Let us construct the Tree shown in // the above figure Node *root = newNode(1); root->left = newNode(2); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(4); root->right->left = newNode(4); root->right->right = newNode(3); if(isSymmetric(root)) cout << ""The given tree is Symmetric""; else cout << ""The given tree is not Symmetric""; return 0; } // This code is contributed by Nikhil jindal.",logn,linear "#include using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */ struct Node { int key; struct Node *left, *right; }; /* To create a newNode of tree and return pointer */ struct Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } // Takes two parameters - same initially and // calls recursively void printMiddleLevelUtil(Node* a, Node* b) { // Base case e if (a == NULL || b == NULL) return; // Fast pointer has reached the leaf so print // value at slow pointer if ((b->left == NULL) && (b->right == NULL)) { cout << a->key << "" ""; return; } // Recursive call // root.left.left and root.left.right will // print same value // root.right.left and root.right.right // will print same value // So we use any one of the condition if (b->left->left) { printMiddleLevelUtil(a->left, b->left->left); printMiddleLevelUtil(a->right, b->left->left); } else { printMiddleLevelUtil(a->left, b->left); printMiddleLevelUtil(a->right, b->left); } } // Main printing method that take a Tree as input void printMiddleLevel(Node* node) { printMiddleLevelUtil(node, node); } // Driver program to test above functions int main() { Node* n1 = newNode(1); Node* n2 = newNode(2); Node* n3 = newNode(3); Node* n4 = newNode(4); Node* n5 = newNode(5); Node* n6 = newNode(6); Node* n7 = newNode(7); n2->left = n4; n2->right = n5; n3->left = n6; n3->right = n7; n1->left = n2; n1->right = n3; printMiddleLevel(n1); } // This code is contributed by Prasad Kshirsagar",logn,linear "// C++ program to Print root to leaf path WITHOUT // using recursion #include using namespace std; /* A binary tree */ struct Node { int data; struct Node *left, *right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers.*/ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } /* Function to print root to leaf path for a leaf using parent nodes stored in map */ void printTopToBottomPath(Node* curr, map parent) { stack stk; // start from leaf node and keep on pushing // nodes into stack till root node is reached while (curr) { stk.push(curr); curr = parent[curr]; } // Start popping nodes from stack and print them while (!stk.empty()) { curr = stk.top(); stk.pop(); cout << curr->data << "" ""; } cout << endl; } /* An iterative function to do preorder traversal of binary tree and print root to leaf path without using recursion */ void printRootToLeaf(Node* root) { // Corner Case if (root == NULL) return; // Create an empty stack and push root to it stack nodeStack; nodeStack.push(root); // Create a map to store parent pointers of binary // tree nodes map parent; // parent of root is NULL parent[root] = NULL; /* Pop all items one by one. Do following for every popped item a) push its right child and set its parent pointer b) push its left child and set its parent pointer Note that right child is pushed first so that left is processed first */ while (!nodeStack.empty()) { // Pop the top item from stack Node* current = nodeStack.top(); nodeStack.pop(); // If leaf node encountered, print Top To // Bottom path if (!(current->left) && !(current->right)) printTopToBottomPath(current, parent); // Push right & left children of the popped node // to stack. Also set their parent pointer in // the map if (current->right) { parent[current->right] = current; nodeStack.push(current->right); } if (current->left) { parent[current->left] = current; nodeStack.push(current->left); } } } // Driver program to test above functions int main() { /* Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 */ Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(2); printRootToLeaf(root); return 0; }",linear,nlogn "// C++ program to print root to leaf path without using // recursion #include using namespace std; // A binary tree node structure struct Node { int data; Node *left, *right; }; // fun to create a new node Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // fun to check leaf node bool isleafnode(Node* root) { return !root->left && !root->right; } // fun to print root to leaf paths without using parent // pointers void printRootToLeaf(Node* root) { // base case if (!root) return; string path = """"; // create an empty stack to store a pair of tree nodes // and its path from root node. stack > s; // push the root node s.push({ root, path }); // loop untill stack becomes empty while (!s.empty()) { auto it = s.top(); s.pop(); root = it.first; path = it.second; // convert the curr root value to string string curr = to_string(root->data) + "" ""; // add the current node to the existing path path += curr; // print the path if a node is encountered if (isleafnode(root)) cout << path << endl; if (root->right) s.push({ root->right, path }); if (root->left) s.push({ root->left, path }); } } int main() { // create a tree Node* root = newNode(10); root->left = newNode(8); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(2); printRootToLeaf(root); return 0; } // This code is contributed by Modem Upendra",linear,linear "// C++ program to print all root to leaf paths // with there relative position #include using namespace std; #define MAX_PATH_SIZE 1000 // tree structure struct Node { char data; Node *left, *right; }; // function create new node Node * newNode(char data) { struct Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // store path information struct PATH { int Hd; // horizontal distance of node from root. char key; // store key }; // Prints given root to leaf path with underscores void printPath(vector < PATH > path, int size) { // Find the minimum horizontal distance value // in current root to leaf path int minimum_Hd = INT_MAX; PATH p; // find minimum horizontal distance for (int it=0; it &AllPath, int HD, int order ) { // base case if(root == NULL) return; // leaf node if (root->left == NULL && root->right == NULL) { // add leaf node and then print path AllPath[order] = (PATH { HD, root->data }); printPath(AllPath, order+1); return; } // store current path information AllPath[order] = (PATH { HD, root->data }); // call left sub_tree printAllPathsUtil(root->left, AllPath, HD-1, order+1); //call left sub_tree printAllPathsUtil(root->right, AllPath, HD+1, order+1); } void printAllPaths(Node *root) { // base case if (root == NULL) return; vector Allpaths(MAX_PATH_SIZE); printAllPathsUtil(root, Allpaths, 0, 0); } // Driver program to test above function int main() { Node *root = newNode('A'); root->left = newNode('B'); root->right = newNode('C'); root->left->left = newNode('D'); root->left->right = newNode('E'); root->right->left = newNode('F'); root->right->right = newNode('G'); printAllPaths(root); return 0; }",logn,constant "// Recursive C++ program to print odd level nodes #include using namespace std; struct Node { int data; Node* left, *right; }; void printOddNodes(Node *root, bool isOdd = true) { // If empty tree if (root == NULL) return; // If current node is of odd level if (isOdd) cout << root->data << "" "" ; // Recur for children with isOdd // switched. printOddNodes(root->left, !isOdd); printOddNodes(root->right, !isOdd); } // Utility method to create a node struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver code int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printOddNodes(root); return 0; }",linear,linear "// Iterative C++ program to print odd level nodes #include using namespace std; struct Node { int data; Node* left, *right; }; // Iterative method to do level order traversal line by line void printOddNodes(Node *root) { // Base Case if (root == NULL) return; // Create an empty queue for level // order traversal queue q; // Enqueue root and initialize level as odd q.push(root); bool isOdd = true; while (1) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { Node *node = q.front(); if (isOdd) cout << node->data << "" ""; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } isOdd = !isOdd; } } // Utility method to create a node struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver code int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printOddNodes(root); return 0; }",linear,linear "// A C++ program to find the all full nodes in // a given binary tree #include using namespace std; struct Node { int data; struct Node *left, *right; }; Node *newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Traverses given tree in Inorder fashion and // prints all nodes that have both children as // non-empty. void findFullNode(Node *root) { if (root != NULL) { findFullNode(root->left); if (root->left != NULL && root->right != NULL) cout << root->data << "" ""; findFullNode(root->right); } } // Driver program to test above function int main() { Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); findFullNode(root); return 0; }",linear,linear "#include #include using namespace std; struct Node { int key; struct Node *left, *right; }; // Utility function to create a new node Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } /*Function to find sum of all elements*/ int sumBT(Node* root) { //sum variable to track the sum of //all variables. int sum = 0; queue q; //Pushing the first level. q.push(root); //Pushing elements at each level from //the tree. while (!q.empty()) { Node* temp = q.front(); q.pop(); //After popping each element from queue //add its data to the sum variable. sum += temp->key; if (temp->left) { q.push(temp->left); } if (temp->right) { q.push(temp->right); } } return sum; } // Driver program int main() { // Let us create Binary Tree shown in above example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); cout << ""Sum of all elements in the binary tree is: "" << sumBT(root); } //This code is contributed by Sarthak Delori",linear,linear "// C++ implementation to find the sum of all // the parent nodes having child node x #include using namespace std; // Node of a binary tree struct Node { int data; Node *left, *right; }; // function to get a new node Node* getNode(int data) { // allocate memory for the node Node *newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // function to find the sum of all the // parent nodes having child node x void sumOfParentOfX(Node* root, int& sum, int x) { // if root == NULL if (!root) return; // if left or right child of root is 'x', then // add the root's data to 'sum' if ((root->left && root->left->data == x) || (root->right && root->right->data == x)) sum += root->data; // recursively find the required parent nodes // in the left and right subtree sumOfParentOfX(root->left, sum, x); sumOfParentOfX(root->right, sum, x); } // utility function to find the sum of all // the parent nodes having child node x int sumOfParentOfXUtil(Node* root, int x) { int sum = 0; sumOfParentOfX(root, sum, x); // required sum of parent nodes return sum; } // Driver program to test above int main() { // binary tree formation Node *root = getNode(4); /* 4 */ root->left = getNode(2); /* / \ */ root->right = getNode(5); /* 2 5 */ root->left->left = getNode(7); /* / \ / \ */ root->left->right = getNode(2); /* 7 2 2 3 */ root->right->left = getNode(2); root->right->right = getNode(3); int x = 2; cout << ""Sum = "" << sumOfParentOfXUtil(root, x); return 0; }",linear,linear "// CPP program to find total sum // of right leaf nodes #include using namespace std; // struct node of binary tree struct Node { int data; Node *left, *right; }; // return new node Node* addNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // utility function to calculate sum // of right leaf nodes void rightLeafSum(Node* root, int& sum) { if (!root) return; // check if the right child of root // is leaf node if (root->right) if (root->right->left == NULL && root->right->right == NULL) sum += root->right->data; rightLeafSum(root->left, sum); rightLeafSum(root->right, sum); } // driver program int main() { // construct binary tree Node* root = addNode(1); root->left = addNode(2); root->left->left = addNode(4); root->left->right = addNode(5); root->left->left->right = addNode(2); root->right = addNode(3); root->right->right = addNode(8); root->right->right->left = addNode(6); root->right->right->right = addNode(7); // variable to store sum of right // leaves int sum = 0; rightLeafSum(root, sum); cout << sum << endl; return 0; }",logn,linear "// C++ program to find total sum of right leaf nodes. #include using namespace std; // struct node of Binary Tree struct Node { int data; Node *left, *right; }; // fun to create and return a new node Node* addNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // fun to calculate sum of right leaf nodes int rightLeafSum(Node* root, bool isrightleaf) { // base case if (!root) return 0; // if it is a leaf node and right node, the return // root's data. if (!root->left && !root->right && isrightleaf) return root->data; // recur of left subtree and right subtree and do the // summation simultaniously. return rightLeafSum(root->left, false) + rightLeafSum(root->right, true); } int main() { // create a tree Node* root = addNode(1); root->left = addNode(2); root->left->left = addNode(4); root->left->right = addNode(5); root->left->left->right = addNode(2); root->right = addNode(3); root->right->right = addNode(8); root->right->right->left = addNode(6); root->right->right->right = addNode(7); cout << rightLeafSum(root, false); return 0; } // This code is contributed by Modem Upendra",logn,linear "// CPP program to find total sum // of right leaf nodes #include using namespace std; // struct node of binary tree struct Node { int data; Node *left, *right; }; // return new node Node* addNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // utility function to calculate sum // of right leaf nodes iteratively int rightLeafSum(Node* root) { // declaring sum to store sum of right leaves int sum = 0; // queue of Node* type queue q; q.push(root); while (!q.empty()) { Node* curr = q.front(); q.pop(); // check for left node if (curr->left) { q.push(curr->left); } // check for right node if (curr->right) { // check for right leaf node if (curr->right->right == NULL and curr->right->left == NULL) { // incrementing sum for found right leaf // node sum += curr->right->data; } q.push(curr->right); } } return sum; } // driver program int main() { // construct binary tree Node* root = addNode(1); root->left = addNode(2); root->left->left = addNode(4); root->left->right = addNode(5); root->left->left->right = addNode(2); root->right = addNode(3); root->right->right = addNode(8); root->right->right->left = addNode(6); root->right->right->right = addNode(7); int sum = rightLeafSum(root); cout << sum << endl; return 0; }",np,linear "#include using namespace std; //Building a tree node having left and right pointers set to null initially struct Node { Node* left; Node* right; int data; //constructor to set the data of the newly created tree node Node(int element){ data = element; this->left = nullptr; this->right = nullptr; } }; int longestPathLeaf(Node* root){ /* structure to store current Node,it's level and sum in the path*/ struct Element{ Node* data; int level; int sum; }; /* maxSumLevel stores maximum sum so far in the path maxLevel stores maximum level so far */ int maxSumLevel = root->data,maxLevel = 0; /* queue to implement level order traversal */ list que; Element e; /* Each element variable stores the current Node, it's level, sum in the path */ e.data = root; e.level = 0; e.sum = root->data; /* push the root element*/ que.push_back(e); /* do level order traversal on the tree*/ while(!que.empty()){ Element front = que.front(); Node* curr = front.data; que.pop_front(); /* if the level of current front element is greater than the maxLevel so far then update maxSum*/ if(front.level > maxLevel){ maxSumLevel = front.sum; maxLevel = front.level; } /* if another path competes then update if the sum is greater than the previous path of same height*/ else if(front.level == maxLevel && front.sum > maxSumLevel) maxSumLevel = front.sum; /* push the left element if exists*/ if(curr->left){ e.data = curr->left; e.sum = e.data->data; e.sum += front.sum; e.level = front.level+1; que.push_back(e); } /*push the right element if exists*/ if(curr->right){ e.data = curr->right; e.sum = e.data->data; e.sum += front.sum; e.level = front.level+1; que.push_back(e); } } /*return the answer*/ return maxSumLevel; } //Helper function int main() { Node* root = new Node(4); root->left = new Node(2); root->right = new Node(5); root->left->left = new Node(7); root->left->right = new Node(1); root->right->left = new Node(2); root->right->right = new Node(3); root->left->right->left = new Node(6); cout << longestPathLeaf(root) << ""\n""; return 0; }",linear,linear "// C++ program to find maximum path //sum between two leaves of a binary tree #include using namespace std; // A binary tree node struct Node { int data; struct Node* left, *right; }; // Utility function to allocate memory for a new node struct Node* newNode(int data) { struct Node* node = new(struct Node); node->data = data; node->left = node->right = NULL; return (node); } // Utility function to find maximum of two integers int max(int a, int b) { return (a >= b)? a: b; } // A utility function to find the maximum sum between any // two leaves.This function calculates two values: // 1) Maximum path sum between two leaves which is stored // in res. // 2) The maximum root to leaf path sum which is returned. // If one side of root is empty, then it returns INT_MIN int maxPathSumUtil(struct Node *root, int &res) { // Base cases if (root==NULL) return 0; if (!root->left && !root->right) return root->data; // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs int ls = maxPathSumUtil(root->left, res); int rs = maxPathSumUtil(root->right, res); // If both left and right children exist if (root->left && root->right) { // Update result if needed res = max(res, ls + rs + root->data); // Return maximum possible value for root being // on one side return max(ls, rs) + root->data; } // If any of the two children is empty, return // root sum for root being on one side return (!root->left)? rs + root->data: ls + root->data; } // The main function which returns sum of the maximum // sum path between two leaves. This function mainly // uses maxPathSumUtil() int maxPathSum(struct Node *root) { int res = INT_MIN; int val = maxPathSumUtil(root, res); //--- for test case --- // 7 // / \ // Null -3 // (case - 1) // value of res will be INT_MIN but the answer is 4 , which is returned by the // function maxPathSumUtil(). if(root->left && root->right) return res; return max(res, val); } // Driver Code int main() { struct Node *root = newNode(-15); root->left = newNode(5); root->right = newNode(6); root->left->left = newNode(-8); root->left->right = newNode(1); root->left->left->left = newNode(2); root->left->left->right = newNode(6); root->right->left = newNode(3); root->right->right = newNode(9); root->right->right->right= newNode(0); root->right->right->right->left= newNode(4); root->right->right->right->right= newNode(-1); root->right->right->right->right->left= newNode(10); cout << ""Max pathSum of the given binary tree is "" << maxPathSum(root); return 0; }",linear,linear "// C++ program to print all paths with sum k. #include using namespace std; // utility function to print contents of // a vector from index i to it's end void printVector(const vector& v, int i) { for (int j = i; j < v.size(); j++) cout << v[j] << "" ""; cout << endl; } // binary tree node struct Node { int data; Node *left, *right; Node(int x) { data = x; left = right = NULL; } }; // This function prints all paths that have sum k void printKPathUtil(Node* root, vector& path, int k) { // empty node if (!root) return; // add current node to the path path.push_back(root->data); // check if there's any k sum path // in the left sub-tree. printKPathUtil(root->left, path, k); // check if there's any k sum path // in the right sub-tree. printKPathUtil(root->right, path, k); // check if there's any k sum path that // terminates at this node // Traverse the entire path as // there can be negative elements too int f = 0; for (int j = path.size() - 1; j >= 0; j--) { f += path[j]; // If path sum is k, print the path if (f == k) printVector(path, j); } // Remove the current element from the path path.pop_back(); } // A wrapper over printKPathUtil() void printKPath(Node* root, int k) { vector path; printKPathUtil(root, path, k); } // Driver code int main() { Node* root = new Node(1); root->left = new Node(3); root->left->left = new Node(2); root->left->right = new Node(1); root->left->right->left = new Node(1); root->right = new Node(-1); root->right->left = new Node(4); root->right->left->left = new Node(1); root->right->left->right = new Node(2); root->right->right = new Node(5); root->right->right->right = new Node(2); int k = 5; printKPath(root, k); return 0; }",logn,linear "// C++ program to find if there is a subtree with // given sum #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left, *right; }; /* utility that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newnode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // function to check if there exist any subtree with given sum // cur_sum --> sum of current subtree from ptr as root // sum_left --> sum of left subtree from ptr as root // sum_right --> sum of right subtree from ptr as root bool sumSubtreeUtil(struct Node *ptr, int *cur_sum, int sum) { // base condition if (ptr == NULL) { *cur_sum = 0; return false; } // Here first we go to left sub-tree, then right subtree // then first we calculate sum of all nodes of subtree // having ptr as root and assign it as cur_sum // cur_sum = sum_left + sum_right + ptr->data // after that we check if cur_sum == sum int sum_left = 0, sum_right = 0; return ( sumSubtreeUtil(ptr->left, ∑_left, sum) || sumSubtreeUtil(ptr->right, ∑_right, sum) || ((*cur_sum = sum_left + sum_right + ptr->data) == sum)); } // Wrapper over sumSubtreeUtil() bool sumSubtree(struct Node *root, int sum) { // Initialize sum of subtree with root int cur_sum = 0; return sumSubtreeUtil(root, &cur_sum, sum); } // driver program to run the case int main() { struct Node *root = newnode(8); root->left = newnode(5); root->right = newnode(4); root->left->left = newnode(9); root->left->right = newnode(7); root->left->right->left = newnode(1); root->left->right->right = newnode(12); root->left->right->right->right = newnode(2); root->right->right = newnode(11); root->right->right->left = newnode(3); int sum = 22; if (sumSubtree(root, sum)) cout << ""Yes""; else cout << ""No""; return 0; }",logn,linear "// C++ implementation to count subtrees that // sum up to a given value x #include using namespace std; // structure of a node of binary tree struct Node { int data; Node *left, *right; }; // function to get a new node Node* getNode(int data) { // allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // function to count subtrees that // sum up to a given value x int countSubtreesWithSumX(Node* root, int& count, int x) { // if tree is empty if (!root) return 0; // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root->left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root->right, count, x); // sum of nodes in the subtree rooted // with 'root->data' int sum = ls + rs + root->data; // if true if (sum == x) count++; // return subtree's nodes sum return sum; } // utility function to count subtrees that // sum up to a given value x int countSubtreesWithSumXUtil(Node* root, int x) { // if tree is empty if (!root) return 0; int count = 0; // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root->left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root->right, count, x); // if tree's nodes sum == x if ((ls + rs + root->data) == x) count++; // required count of subtrees return count; } // Driver program to test above int main() { /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ Node* root = getNode(5); root->left = getNode(-10); root->right = getNode(3); root->left->left = getNode(9); root->left->right = getNode(8); root->right->left = getNode(-4); root->right->right = getNode(7); int x = 7; cout << ""Count = "" << countSubtreesWithSumXUtil(root, x); return 0; }",logn,linear "// C++ program to find if // there is a subtree with // given sum #include using namespace std; // Structure of a node of binary tree struct Node { int data; Node *left, *right; }; // Function to get a new node Node* getNode(int data) { // Allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // Put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // Utility function to count subtrees that // sum up to a given value x int countSubtreesWithSumXUtil(Node* root, int x) { static int count = 0; static Node* ptr = root; int l = 0, r = 0; if (root == NULL) return 0; l += countSubtreesWithSumXUtil(root->left, x); r += countSubtreesWithSumXUtil(root->right, x); if (l + r + root->data == x) count++; if (ptr != root) return l + root->data + r; return count; } // Driver code int main() { /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ Node* root = getNode(5); root->left = getNode(-10); root->right = getNode(3); root->left->left = getNode(9); root->left->right = getNode(8); root->right->left = getNode(-4); root->right->right = getNode(7); int x = 7; cout << ""Count = "" << countSubtreesWithSumXUtil(root, x); return 0; } // This code is contributed by Sadik Ali",logn,linear "// C++ implementation to find maximum spiral sum #include using namespace std; // structure of a node of binary tree struct Node { int data; Node *left, *right; }; // A utility function to create a new node Node* newNode(int data) { // allocate space Node* node = new Node; // put in the data node->data = data; node->left = node->right = NULL; return node; } // function to find the maximum sum contiguous subarray. // implements kadane's algorithm int maxSum(vector arr, int n) { // to store the maximum value that is ending // up to the current index int max_ending_here = INT_MIN; // to store the maximum value encountered so far int max_so_far = INT_MIN; // traverse the array elements for (int i = 0; i < n; i++) { // if max_ending_here < 0, then it could // not possibly contribute to the maximum // sum further if (max_ending_here < 0) max_ending_here = arr[i]; // else add the value arr[i] to max_ending_here else max_ending_here += arr[i]; // update max_so_far max_so_far = max(max_so_far, max_ending_here); } // required maximum sum contiguous subarray value return max_so_far; } // function to find maximum spiral sum int maxSpiralSum(Node* root) { // if tree is empty if (root == NULL) return 0; // Create two stacks to store alternate levels stack s1; // For levels from right to left stack s2; // For levels from left to right // vector to store spiral order traversal // of the binary tree vector arr; // Push first level to first stack 's1' s1.push(root); // traversing tree in spiral form until // there are elements in any one of the // stacks while (!s1.empty() || !s2.empty()) { // traverse current level from s1 and // push nodes of next level to s2 while (!s1.empty()) { Node* temp = s1.top(); s1.pop(); // push temp-data to 'arr' arr.push_back(temp->data); // Note that right is pushed before left if (temp->right) s2.push(temp->right); if (temp->left) s2.push(temp->left); } // traverse current level from s2 and // push nodes of next level to s1 while (!s2.empty()) { Node* temp = s2.top(); s2.pop(); // push temp-data to 'arr' arr.push_back(temp->data); // Note that left is pushed before right if (temp->left) s1.push(temp->left); if (temp->right) s1.push(temp->right); } } // required maximum spiral sum return maxSum(arr, arr.size()); } // Driver program to test above int main() { Node* root = newNode(-2); root->left = newNode(-3); root->right = newNode(4); root->left->left = newNode(5); root->left->right = newNode(1); root->right->left = newNode(-2); root->right->right = newNode(-1); root->left->left->left = newNode(-3); root->right->right->right = newNode(2); cout << ""Maximum Spiral Sum = "" << maxSpiralSum(root); return 0; }",linear,linear "// C++ implementation to find the sum of // leaf nodes at minimum level #include using namespace std; // structure of a node of binary tree struct Node { int data; Node *left, *right; }; // function to get a new node Node* getNode(int data) { // allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // function to find the sum of // leaf nodes at minimum level int sumOfLeafNodesAtMinLevel(Node* root) { // if tree is empty if (!root) return 0; // if there is only one node if (!root->left && !root->right) return root->data; // queue used for level order traversal queue q; int sum = 0; bool f = 0; // push root node in the queue 'q' q.push(root); while (f == 0) { // count number of nodes in the // current level int nc = q.size(); // traverse the current level nodes while (nc--) { // get front element from 'q' Node* top = q.front(); q.pop(); // if it is a leaf node if (!top->left && !top->right) { // accumulate data to 'sum' sum += top->data; // set flag 'f' to 1, to signify // minimum level for leaf nodes // has been encountered f = 1; } else { // if top's left and right child // exists, then push them to 'q' if (top->left) q.push(top->left); if (top->right) q.push(top->right); } } } // required sum return sum; } // Driver program to test above int main() { // binary tree creation Node* root = getNode(1); root->left = getNode(2); root->right = getNode(3); root->left->left = getNode(4); root->left->right = getNode(5); root->right->left = getNode(6); root->right->right = getNode(7); root->left->right->left = getNode(8); root->right->left->right = getNode(9); cout << ""Sum = "" << sumOfLeafNodesAtMinLevel(root); return 0; }",linear,linear "#include using namespace std; struct Node { int data; Node *left, *right; }; // function to get a new node Node* getNode(int data) { // allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } map > mp; void solve(Node* root, int level) { if(root == NULL) return; if(root->left == NULL && root->right == NULL) mp[level].push_back(root->data); solve(root->left, level+1); solve(root->right, level+1); } int minLeafSum(Node *root) { solve(root, 0); int sum = 0; for(auto i:mp) { for(auto j:i.second) { sum += j; } return sum; } } int main() { // binary tree creation Node* root = getNode(1); root->left = getNode(2); root->right = getNode(3); root->left->left = getNode(4); root->left->right = getNode(5); root->right->left = getNode(6); root->right->right = getNode(7); cout << ""Sum = ""<< minLeafSum(root); return 0; }",linear,linear "#include using namespace std; #define bool int /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node* left; node* right; }; /* Given a tree and a sum, return true if there is a path from the root down to a leaf, such that adding up all the values along the path equals the given sum. Strategy: subtract the node value from the sum when recurring down, and check to see if the sum is 0 when you when you reach the leaf node. */ bool hasPathSum(node* Node, int sum) { if (Node == NULL) return 0; bool ans = 0; int subSum = sum - Node->data; /* If we reach a leaf node and sum becomes 0 then return * true*/ if (subSum == 0 && Node->left == NULL && Node->right == NULL) return 1; /* otherwise check both subtrees */ if (Node->left) ans = ans || hasPathSum(Node->left, subSum); if (Node->right) ans = ans || hasPathSum(Node->right, subSum); return ans; } /* UTILITY FUNCTIONS */ /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newnode(int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node); } // Driver's Code int main() { int sum = 21; /* Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 */ node* root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->left->right = newnode(5); root->right->left = newnode(2); // Function call if (hasPathSum(root, sum)) cout << ""There is a root-to-leaf path with sum "" << sum; else cout << ""There is no root-to-leaf path with sum "" << sum; return 0; } // This code is contributed by rathbhupendra",logn,linear "// C++ program to find sum of all paths from root to leaves // A Binary tree node #include using namespace std; // A Binary tree node class Node { public: int data; Node *left, *right; // Constructor to create a new node Node(int val) { data = val; left = right = NULL; } }; void treePathsSumUtil(Node* root, vector currPath, vector> &allPath) { // Base Case if (root == NULL) return; // append the root data in string format in currPath currPath.push_back((to_string)(root->data)); // if we found a leaf node we copy the currPath to allPath if (root->left == NULL && root->right == NULL) allPath.push_back(currPath); // traverse in the left subtree treePathsSumUtil(root->left, currPath, allPath); // traverse in the right subtree treePathsSumUtil(root->right, currPath, allPath); // remove the current element from the path currPath.pop_back(); } int treePathsSum(Node* root) { // store all the root to leaf path in allPath vector> allPath; vector v; treePathsSumUtil(root, v, allPath); // store the sum int s = 0; for(auto pathNumber : allPath) { string k=""""; // join the pathNumbers to convert them // into the number to calculate sum for(auto x: pathNumber) k = k+x; s += stoi(k); } return s; } // Driver code int main() { Node *root = new Node(6); root->left = new Node(3); root->right = new Node(5); root->left->left = new Node(2); root->left->right = new Node(5); root->right->right = new Node(4); root->left->right->left = new Node(7); root->left->right->right = new Node(4); cout<<""Sum of all paths is ""< using namespace std; int findRoot(pair arr[], int n) { // Every node appears once as an id, and // every node except for the root appears // once in a sum. So if we subtract all // the sums from all the ids, we're left // with the root id. int root = 0; for (int i=0; i arr[] = {{1, 5}, {2, 0}, {3, 0}, {4, 0}, {5, 5}, {6, 5}}; int n = sizeof(arr)/sizeof(arr[0]); printf(""%d\n"", findRoot(arr, n)); return 0; }",constant,linear "// C++ implementation to replace each node // in binary tree with the sum of its inorder // predecessor and successor #include using namespace std; // node of a binary tree struct Node { int data; struct Node* left, *right; }; // function to get a new node of a binary tree struct Node* getNode(int data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node; } // function to store the inorder traversal // of the binary tree in 'arr' void storeInorderTraversal(struct Node* root, vector& arr) { // if root is NULL if (!root) return; // first recur on left child storeInorderTraversal(root->left, arr); // then store the root's data in 'arr' arr.push_back(root->data); // now recur on right child storeInorderTraversal(root->right, arr); } // function to replace each node with the sum of its // inorder predecessor and successor void replaceNodeWithSum(struct Node* root, vector arr, int* i) { // if root is NULL if (!root) return; // first recur on left child replaceNodeWithSum(root->left, arr, i); // replace node's data with the sum of its // inorder predecessor and successor root->data = arr[*i - 1] + arr[*i + 1]; // move 'i' to point to the next 'arr' element ++*i; // now recur on right child replaceNodeWithSum(root->right, arr, i); } // Utility function to replace each node in binary // tree with the sum of its inorder predecessor // and successor void replaceNodeWithSumUtil(struct Node* root) { // if tree is empty if (!root) return; vector arr; // store the value of inorder predecessor // for the leftmost leaf arr.push_back(0); // store the inorder traversal of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.push_back(0); // replace each node with the required sum int i = 1; replaceNodeWithSum(root, arr, &i); } // function to print the preorder traversal // of a binary tree void preorderTraversal(struct Node* root) { // if root is NULL if (!root) return; // first print the data of node cout << root->data << "" ""; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right); } // Driver program to test above int main() { // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \ / \ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << ""Preorder Traversal before tree modification:n""; preorderTraversal(root); replaceNodeWithSumUtil(root); cout << ""\nPreorder Traversal after tree modification:n""; preorderTraversal(root); return 0; }",linear,linear "// C++ implementation to replace each node // in binary tree with the sum of its inorder // predecessor and successor #include using namespace std; // node of a binary tree struct Node { int data; struct Node* left, *right; }; // function to get a new node of a binary tree struct Node* getNode(int data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node; } // function to print the preorder traversal // of a binary tree void preorderTraversal(struct Node* root) { // if root is NULL if (!root) return; // first print the data of node cout << root->data << "" ""; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right); } void inOrderTraverse(struct Node* root, struct Node* &prev, int &prevVal) { if(root == NULL) return; inOrderTraverse(root->left, prev, prevVal); if(prev == NULL) { prev = root; prevVal = 0; } else { int temp = prev->data; prev->data = prevVal + root->data; prev = root; prevVal = temp; } inOrderTraverse(root->right, prev, prevVal); } // Driver program to test above int main() { // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \ / \ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << ""Preorder Traversal before tree modification:\n""; preorderTraversal(root); struct Node* prev = NULL; int prevVal = -1; inOrderTraverse(root, prev, prevVal); // update righmost node. prev->data = prevVal; cout << ""\nPreorder Traversal after tree modification:\n""; preorderTraversal(root); return 0; }",linear,linear "// C++ Program for Lowest Common Ancestor // in a Binary Tree // A O(n) solution to find LCA // of two given values n1 and n2 #include using namespace std; // A Binary Tree node struct Node { int key; struct Node *left, *right; }; // Utility function creates a new binary tree node with // given key Node* newNode(int k) { Node* temp = new Node; temp->key = k; temp->left = temp->right = NULL; return temp; } // Finds the path from root node to given root of the tree, // Stores the path in a vector path[], returns true if path // exists otherwise false bool findPath(Node* root, vector& path, int k) { // base case if (root == NULL) return false; // Store this node in path vector. The node will be // removed if not in path from root to k path.push_back(root->key); // See if the k is same as root's key if (root->key == k) return true; // Check if k is found in left or right sub-tree if ((root->left && findPath(root->left, path, k)) || (root->right && findPath(root->right, path, k))) return true; // If not present in subtree rooted with root, remove // root from path[] and return false path.pop_back(); return false; } // Returns LCA if node n1, n2 are present in the given // binary tree, otherwise return -1 int findLCA(Node* root, int n1, int n2) { // to store paths to n1 and n2 from the root vector path1, path2; // Find paths from root to n1 and root to n2. If either // n1 or n2 is not present, return -1 if (!findPath(root, path1, n1) || !findPath(root, path2, n2)) return -1; /* Compare the paths to get the first different value */ int i; for (i = 0; i < path1.size() && i < path2.size(); i++) if (path1[i] != path2[i]) break; return path1[i - 1]; } // Driver program to test above functions int main() { // Let us create the Binary Tree shown in above diagram. Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); cout << ""LCA(4, 5) = "" << findLCA(root, 4, 5); cout << ""\nLCA(4, 6) = "" << findLCA(root, 4, 6); cout << ""\nLCA(3, 4) = "" << findLCA(root, 3, 4); cout << ""\nLCA(2, 4) = "" << findLCA(root, 2, 4); return 0; }",linear,linear "/* C++ Program to find LCA of n1 and n2 using one traversal * of Binary Tree */ #include using namespace std; // A Binary Tree Node struct Node { struct Node *left, *right; int key; }; // Utility function to create a new tree Node Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp; } // This function returns pointer to LCA of two given values // n1 and n2. This function assumes that n1 and n2 are // present in Binary Tree struct Node* findLCA(struct Node* root, int n1, int n2) { // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with root's key, report // the presence by returning root (Note that if a key is // ancestor of other, then the ancestor key becomes LCA if (root->key == n1 || root->key == n2) return root; // Look for keys in left and right subtrees Node* left_lca = findLCA(root->left, n1, n2); Node* right_lca = findLCA(root->right, n1, n2); // If both of the above calls return Non-NULL, then one // key is present in once subtree and other is present // in other, So this node is the LCA if (left_lca && right_lca) return root; // Otherwise check if left subtree or right subtree is // LCA return (left_lca != NULL) ? left_lca : right_lca; } // Driver program to test above functions int main() { // Let us create binary tree given in the above example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); cout << ""LCA(4, 5) = "" << findLCA(root, 4, 5)->key; cout << ""\nLCA(4, 6) = "" << findLCA(root, 4, 6)->key; cout << ""\nLCA(3, 4) = "" << findLCA(root, 3, 4)->key; cout << ""\nLCA(2, 4) = "" << findLCA(root, 2, 4)->key; return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",logn,linear "/* C++ program to find LCA of n1 and n2 using one traversal of Binary Tree. It handles all cases even when n1 or n2 is not there in Binary Tree */ #include using namespace std; // A Binary Tree Node struct Node { struct Node *left, *right; int key; }; // Utility function to create a new tree Node Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp; } // This function returns pointer to LCA of two given // valuesn1 and n2. struct Node* findLCAUtil(struct Node* root, int n1, int n2) { // Base case if (root == NULL) return NULL; // If either n1 or n2 matches with root's key, report // the presence by returning root if (root->key == n1 || root->key == n2) return root; // Look for keys in left and right subtrees Node* left_lca = findLCAUtil(root->left, n1, n2); Node* right_lca = findLCAUtil(root->right, n1, n2); // If both of the above calls return Non-NULL nodes, // then one key is present in once subtree and other is // present in other, So this node is the LCA if (left_lca and right_lca) return root; // Otherwise check if left subtree or right subtree is // LCA return (left_lca != NULL) ? left_lca : right_lca; } // Returns true if key k is present in tree rooted with root bool find(Node* root, int k) { // Base Case if (root == NULL) return false; // If key is present at root, or in left subtree or // right subtree, return true; if (root->key == k || find(root->left, k) || find(root->right, k)) return true; // Else return false return false; } // This function returns LCA of n1 and n2 only if both n1 // and n2 are present in tree, otherwise returns NULL; Node* findLCA(Node* root, int n1, int n2) { // Return LCA only if both n1 and n2 are present in tree if (find(root, n1) and find(root, n2)) return findLCAUtil(root, n1, n2); // Else return NULL return NULL; } // Driver program to test above functions int main() { // Let us create a binary tree given in the above // example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); Node* lca = findLCA(root, 4, 5); if (lca != NULL) cout << ""LCA(4, 5) = "" << lca->key; else cout << ""Keys are not present ""; lca = findLCA(root, 4, 10); if (lca != NULL) cout << ""\nLCA(4, 10) = "" << lca->key; else cout << ""\nKeys are not present ""; return 0; } // This code is contributed by Kshitij Dwivedi // (kshitijdwivedi28)",logn,linear "// C++ program to find maximum difference between node // and its ancestor #include using namespace std; /* A binary tree node has key, pointer to left child and a pointer to right child */ struct Node { int key; struct Node *left, *right; }; /* To create a newNode of tree and return pointer */ struct Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } /* Recursive function to calculate maximum ancestor-node difference in binary tree. It updates value at 'res' to store the result. The returned value of this function is minimum value in subtree rooted with 't' */ int maxDiffUtil(Node* t, int* res) { /* Returning Maximum int value if node is not there (one child case) */ if (t == NULL) return INT_MAX; /* If leaf node then just return node's value */ if (t->left == NULL && t->right == NULL) return t->key; /* Recursively calling left and right subtree for minimum value */ int val = min(maxDiffUtil(t->left, res), maxDiffUtil(t->right, res)); /* Updating res if (node value - minimum value from subtree) is bigger than res */ *res = max(*res, t->key - val); /* Returning minimum value got so far */ return min(val, t->key); } /* This function mainly calls maxDiffUtil() */ int maxDiff(Node* root) { // Initialising result with minimum int value int res = INT_MIN; maxDiffUtil(root, &res); return res; } /* Helper function to print inorder traversal of binary tree */ void inorder(Node* root) { if (root) { inorder(root->left); cout << root->key << "" ""; inorder(root->right); } } // Driver program to test above functions int main() { // Making above given diagram's binary tree Node* root; root = newNode(8); root->left = newNode(3); root->left->left = newNode(1); root->left->right = newNode(6); root->left->right->left = newNode(4); root->left->right->right = newNode(7); root->right = newNode(10); root->right->right = newNode(14); root->right->right->left = newNode(13); cout << maxDiff(root); }",linear,linear "// C++ program to count number of ways to color // a N node skewed tree with k colors such that // parent and children have different colors. #include using namespace std; // fast_way is recursive // method to calculate power int fastPow(int N, int K) { if (K == 0) return 1; int temp = fastPow(N, K / 2); if (K % 2 == 0) return temp * temp; else return N * temp * temp; } int countWays(int N, int K) { return K * fastPow(K - 1, N - 1); } // driver program int main() { int N = 3, K = 3; cout << countWays(N, K); return 0; }",constant,logn "// C++ program to print size of tree in iterative #include #include using namespace std; struct Node { int data; Node *left, *right; }; // A utility function to // create a new Binary Tree Node Node *newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } // return size of tree int sizeoftree(Node *root) { // if tree is empty it will // return 0 if(root == NULL) return 0; // Using level order Traversal. queue q; int count = 1; q.push(root); while(!q.empty()) { Node *temp = q.front(); if(temp->left) { // Enqueue left child q.push(temp->left); // Increment count count++; } if(temp->right) { // Enqueue right child q.push(temp->right); // Increment count count++; } q.pop(); } return count; } // Driver Code int main() { Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << ""Size of the tree is "" << sizeoftree(root) << endl; return 0; } // This code is contributed by SHAKEELMOHAMMAD",np,linear "// C++ program to find height of tree #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node* left; node* right; }; /* Compute the ""maxDepth"" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int maxDepth(node* node) { if (node == NULL) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node); } // Driver code int main() { node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << ""Height of tree is "" << maxDepth(root); return 0; } // This code is contributed by Amit Srivastav",linear,linear "#include #include using namespace std; // A Tree node struct Node { int key; struct Node *left, *right; }; // Utility function to create a new node Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } /*Function to find the height(depth) of the tree*/ int height(struct Node* root) { // Initialising a variable to count the // height of tree int depth = 0; queue q; // Pushing first level element along with NULL q.push(root); q.push(NULL); while (!q.empty()) { Node* temp = q.front(); q.pop(); // When NULL encountered, increment the value if (temp == NULL) { depth++; } // If NULL not encountered, keep moving if (temp != NULL) { if (temp->left) { q.push(temp->left); } if (temp->right) { q.push(temp->right); } } // If queue still have elements left, // push NULL again to the queue. else if (!q.empty()) { q.push(NULL); } } return depth; } // Driver program int main() { // Let us create Binary Tree shown in above example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << ""Height(Depth) of tree is: "" << height(root); }",linear,linear "// C++ program for above approach #include using namespace std; // A Tree node struct Node { int key; struct Node *left, *right; }; // Utility function to create a new node Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp); } /*Function to find the height(depth) of the tree*/ int height(Node* root) { // Initialising a variable to count the // height of tree queue q; q.push(root); int height = 0; while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; i++) { Node* temp = q.front(); q.pop(); if (temp->left != NULL) { q.push(temp->left); } if (temp->right != NULL) { q.push(temp->right); } } height++; } return height; } // Driver program int main() { // Let us create Binary Tree shown in above example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << ""Height(Depth) of tree is: "" << height(root); } // This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear "#include #include using namespace std; // This approach counts the number of nodes from root to the // leaf to calculate the height of the tree. // Defining the structure of a Node. class Node { public: int data; Node* left; Node* right; }; // Helper function to create a newnode. // Input: Data for the newnode. // Return: Address of the newly created node. Node* createNode(int data) { Node* newnode = new Node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return newnode; } // Function to calculate the height of given Binary Tree. // Input: Address of the root node of Binary Tree. // Return: Height of Binary Tree as a integer. This includes // the number of nodes from root to the leaf. int calculateHeight(Node* root) { queue nodesInLevel; int height = 0; int nodeCount = 0; // Calculate number of nodes in a level. Node* currentNode; // Pointer to store the address of a // node in the current level. if (root == NULL) { return 0; } nodesInLevel.push(root); while (!nodesInLevel.empty()) { // This while loop runs for every level and // increases the height by 1 in each iteration. If // the queue is empty then it implies that the last // level of tree has been parsed. height++; // Create another while loop which will insert all // the child nodes of the current level in the // queue. nodeCount = nodesInLevel.size(); while (nodeCount--) { currentNode = nodesInLevel.front(); // Check if the current nodes has left child and // insert it in the queue. if (currentNode->left != NULL) { nodesInLevel.push(currentNode->left); } // Check if the current nodes has right child // and insert it in the queue. if (currentNode->right != NULL) { nodesInLevel.push(currentNode->right); } // Once the children of the current node are // inserted. Delete the current node. nodesInLevel.pop(); } } return height; } // Driver Function. int main() { // Creating a binary tree. Node* root = NULL; root = createNode(1); root->left = createNode(2); root->left->left = createNode(4); root->left->right = createNode(5); root->right = createNode(3); cout << ""The height of the binary tree using iterative "" ""method is: "" << calculateHeight(root) << "".""; return 0; }",linear,linear "// CPP program to find height of complete // binary tree from total nodes. #include using namespace std; int height(int N) { return floor(log2(N)); } // driver node int main() { int N = 2; cout << height(N); return 0; }",constant,constant "/* Program to find height of the tree considering only even level leaves. */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; }; int heightOfTreeUtil(Node* root, bool isEven) { // Base Case if (!root) return 0; if (!root->left && !root->right) { if (isEven) return 1; else return 0; } /*left stores the result of left subtree, and right stores the result of right subtree*/ int left = heightOfTreeUtil(root->left, !isEven); int right = heightOfTreeUtil(root->right, !isEven); /*If both left and right returns 0, it means there is no valid path till leaf node*/ if (left == 0 && right == 0) return 0; return (1 + max(left, right)); } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } int heightOfTree(Node* root) { return heightOfTreeUtil(root, false); } /* Driver program to test above functions*/ int main() { // Let us create binary tree shown in above diagram struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->left = newNode(6); cout << ""Height of tree is "" << heightOfTree(root); return 0; }",linear,linear "/* CPP program to check if a tree is height-balanced or not */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; Node(int d) { int data = d; left = right = NULL; } }; // Function to calculate the height of a tree int height(Node* node) { // base case tree is empty if (node == NULL) return 0; // If tree is not empty then // height = 1 + max of left height // and right heights return 1 + max(height(node->left), height(node->right)); } // Returns true if binary tree // with root as root is height-balanced bool isBalanced(Node* root) { // for height of left subtree int lh; // for height of right subtree int rh; // If tree is empty then return true if (root == NULL) return 1; // Get the height of left and right sub trees lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; // If we reach here then tree is not height-balanced return 0; } // Driver code int main() { Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->left->left->left = new Node(8); if (isBalanced(root)) cout << ""Tree is balanced""; else cout << ""Tree is not balanced""; return 0; } // This code is contributed by rathbhupendra",linear,quadratic "// Recursive optimized C program to find the diameter of a // Binary Tree #include using namespace std; // A binary tree node has data, pointer to left child // and a pointer to right child struct node { int data; struct node *left, *right; }; // function to create a new node of tree and returns pointer struct node* newNode(int data); // returns max of two integers int max(int a, int b) { return (a > b) ? a : b; } // function to Compute height of a tree. int height(struct node* node); // Function to get diameter of a binary tree int diameter(struct node* tree) { // base case where tree is empty if (tree == NULL) return 0; // get the height of left and right sub-trees int lheight = height(tree->left); int rheight = height(tree->right); // get the diameter of left and right sub-trees int ldiameter = diameter(tree->left); int rdiameter = diameter(tree->right); // Return max of following three // 1) Diameter of left subtree // 2) Diameter of right subtree // 3) Height of left subtree + height of right subtree + // 1 return max(lheight + rheight + 1, max(ldiameter, rdiameter)); } // UTILITY FUNCTIONS TO TEST diameter() FUNCTION // The function Compute the ""height"" of a tree. Height is // the number f nodes along the longest path from the root // node down to the farthest leaf node. int height(struct node* node) { // base case tree is empty if (node == NULL) return 0; // If tree is not empty then height = 1 + max of left // height and right heights return 1 + max(height(node->left), height(node->right)); } // Helper function that allocates a new node with the // given data and NULL left and right pointers. struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Driver Code int main() { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); // Function Call cout << ""Diameter of the given binary tree is "" << diameter(root); return 0; } // This code is contributed by shivanisinghss2110",linear,quadratic "// Recursive optimized C++ program to find the diameter of a // Binary Tree #include using namespace std; // A binary tree node has data, pointer to left child // and a pointer to right child struct node { int data; struct node *left, *right; }; // function to create a new node of tree and returns pointer struct node* newNode(int data); int diameterOpt(struct node* root, int* height) { // lh --> Height of left subtree // rh --> Height of right subtree int lh = 0, rh = 0; // ldiameter --> diameter of left subtree // rdiameter --> Diameter of right subtree int ldiameter = 0, rdiameter = 0; if (root == NULL) { *height = 0; return 0; // diameter is also 0 } // Get the heights of left and right subtrees in lh and // rh And store the returned values in ldiameter and // ldiameter ldiameter = diameterOpt(root->left, &lh); rdiameter = diameterOpt(root->right, &rh); // Height of current node is max of heights of left and // right subtrees plus 1 *height = max(lh, rh) + 1; return max(lh + rh + 1, max(ldiameter, rdiameter)); } // Helper function that allocates a new node with the // given data and NULL left and right pointers. struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Driver Code int main() { /* Constructed binary tree is 1 / \ 2 3 / \ 4 5 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); int height = 0; // Function Call cout << ""Diameter of the given binary tree is "" << diameterOpt(root, &height); return 0; } // This code is contributed by probinsah.",linear,linear "// Simple C++ program to find diameter // of a binary tree. #include using namespace std; /* Tree node structure used in the program */ struct Node { int data; Node* left, *right; }; /* Function to find height of a tree */ int height(Node* root, int& ans) { if (root == NULL) return 0; int left_height = height(root->left, ans); int right_height = height(root->right, ans); // update the answer, because diameter of a // tree is nothing but maximum value of // (left_height + right_height + 1) for each node ans = max(ans, 1 + left_height + right_height); return 1 + max(left_height, right_height); } /* Computes the diameter of binary tree with given root. */ int diameter(Node* root) { if (root == NULL) return 0; int ans = INT_MIN; // This will store the final answer height(root, ans); return ans; } struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver code int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf(""Diameter is %d\n"", diameter(root)); return 0; }",logn,linear "// CPP program to find deepest right leaf // node of binary tree #include using namespace std; // tree node struct Node { int data; Node *left, *right; }; // returns a new tree Node Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // return the deepest right leaf node // of binary tree Node* getDeepestRightLeafNode(Node* root) { if (!root) return NULL; // create a queue for level order traversal queue q; q.push(root); Node* result = NULL; // traverse until the queue is empty while (!q.empty()) { Node* temp = q.front(); q.pop(); if (temp->left) { q.push(temp->left); } // Since we go level by level, the last // stored right leaf node is deepest one if (temp->right) { q.push(temp->right); if (!temp->right->left && !temp->right->right) result = temp->right; } } return result; } // driver program int main() { // construct a tree Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); Node* result = getDeepestRightLeafNode(root); if (result) cout << ""Deepest Right Leaf Node :: "" << result->data << endl; else cout << ""No result, right leaf not found\n""; return 0; }",linear,linear "// A C++ program to find value of the deepest node // in a given binary tree #include using namespace std; // A tree node struct Node { int data; struct Node *left, *right; }; // Utility function to create a new node Node *newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // maxLevel : keeps track of maximum level seen so far. // res : Value of deepest node so far. // level : Level of root void find(Node *root, int level, int &maxLevel, int &res) { if (root != NULL) { find(root->left, ++level, maxLevel, res); // Update level and rescue if (level > maxLevel) { res = root->data; maxLevel = level; } find(root->right, level, maxLevel, res); } } // Returns value of deepest node int deepestNode(Node *root) { // Initialize result and max level int res = -1; int maxLevel = -1; // Updates value ""res"" and ""maxLevel"" // Note that res and maxLen are passed // by reference. find(root, 0, maxLevel, res); return res; } // Driver program int main() { Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); cout << deepestNode(root); return 0; }",linear,linear "// A C++ program to find value of the // deepest node in a given binary tree #include using namespace std; // A tree node with constructor class Node { public: int data; Node *left, *right; // constructor Node(int key) { data = key; left = NULL; right = NULL; } }; // Function to return the deepest node Node* deepestNode(Node* root) { Node* tmp = NULL; if (root == NULL) return NULL; // Creating a Queue queue q; q.push(root); // Iterates until queue become empty while (q.size() > 0) { tmp = q.front(); q.pop(); if (tmp->left != NULL) q.push(tmp->left); if (tmp->right != NULL) q.push(tmp->right); } return tmp; } int main() { Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->right->left = new Node(5); root->right->right = new Node(6); root->right->left->right = new Node(7); root->right->right->right = new Node(8); root->right->left->right->left = new Node(9); Node* deepNode = deepestNode(root); cout << (deepNode->data); return 0; }",linear,linear "// CPP program to find deepest left leaf // node of binary tree #include using namespace std; // tree node struct Node { int data; Node *left, *right; }; // returns a new tree Node Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // return the deepest left leaf node // of binary tree Node* getDeepestLeftLeafNode(Node* root) { if (!root) return NULL; // create a queue for level order traversal queue q; q.push(root); Node* result = NULL; // traverse until the queue is empty while (!q.empty()) { Node* temp = q.front(); q.pop(); // Since we go level by level, the last // stored left leaf node is deepest one, if (temp->left) { q.push(temp->left); if (!temp->left->left && !temp->left->right) result = temp->left; } if (temp->right) q.push(temp->right); } return result; } // driver program int main() { // construct a tree Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(6); root->right->left->right = newNode(7); root->right->right->right = newNode(8); root->right->left->right->left = newNode(9); root->right->right->right->right = newNode(10); Node* result = getDeepestLeftLeafNode(root); if (result) cout << ""Deepest Left Leaf Node :: "" << result->data << endl; else cout << ""No result, left leaf not found\n""; return 0; }",linear,linear "// C++ program to calculate width of binary tree #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node* left; node* right; node (int d){ this->data = d; this->left = this->right = NULL; } }; /*Function prototypes*/ int getWidth(node* root, int level); int height(node* node); /* Function to get the maximum width of a binary tree*/ int getMaxWidth(node* root) { int maxWidth = 0; int width; int h = height(root); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(root, i); if (width > maxWidth) maxWidth = width; } return maxWidth; } /* Get width of a given level */ int getWidth(node* root, int level) { if (root == NULL) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(root->left, level - 1) + getWidth(root->right, level - 1); } /* UTILITY FUNCTIONS */ /* Compute the ""height"" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(node* node) { if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } /* Driver code*/ int main() { node* root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); root->right->right = new node(8); root->right->right->left = new node(6); root->right->right->right = new node(7); /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ // Function call cout << ""Maximum width is "" << getMaxWidth(root) << endl; return 0; } // This code is contributed by rathbhupendra",constant,quadratic "// A queue based C++ program to find maximum width // of a Binary Tree #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; Node(int d) { this->data = d; this->left = this->right = NULL; } }; // Function to find the maximum width of the tree // using level order traversal int maxWidth(struct Node* root) { // Base case if (root == NULL) return 0; // Initialize result int result = 0; // Do Level order traversal keeping track of number // of nodes at every level. queue q; q.push(root); while (!q.empty()) { // Get the size of queue when the level order // traversal for one level finishes int count = q.size(); // Update the maximum node count value result = max(count, result); // Iterate for all the nodes in the queue currently while (count--) { // Dequeue an node from queue Node* temp = q.front(); q.pop(); // Enqueue left and right children of // dequeued node if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } } return result; } // Driver code int main() { struct Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->right = new Node(8); root->right->right->left = new Node(6); root->right->right->right = new Node(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ // Function call cout << ""Maximum width is "" << maxWidth(root) << endl; return 0; } // This code is contributed by Nikhil Kumar // Singh(nickzuck_007)",np,linear "// C++ program to calculate width of binary tree #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node* left; node* right; node(int d) { this->data = d; this->left = this->right = NULL; } }; // A utility function to get // height of a binary tree int height(node* node); // A utility function that returns // maximum value in arr[] of size n int getMax(int arr[], int n); // A function that fills count array // with count of nodes at every // level of given binary tree void getMaxWidthRecur(node* root, int count[], int level); /* Function to get the maximum width of a binary tree*/ int getMaxWidth(node* root) { int width; int h = height(root); // Create an array that will // store count of nodes at each level int* count = new int[h]; int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(root, count, level); // Return the maximum value from count array return getMax(count, h); } // A function that fills count array // with count of nodes at every // level of given binary tree void getMaxWidthRecur(node* root, int count[], int level) { if (root) { count[level]++; getMaxWidthRecur(root->left, count, level + 1); getMaxWidthRecur(root->right, count, level + 1); } } /* UTILITY FUNCTIONS */ /* Compute the ""height"" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(node* node) { if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } // Return the maximum value from count array int getMax(int arr[], int n) { int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver code*/ int main() { node* root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); root->right->right = new node(8); root->right->right->left = new node(6); root->right->right->right = new node(7); cout << ""Maximum width is "" << getMaxWidth(root) << endl; return 0; } // This is code is contributed by rathbhupendra",logn,linear "// CPP program to print vertical width // of a tree #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // get vertical width void lengthUtil(Node* root, int& maximum, int& minimum, int curr = 0) { if (root == NULL) return; // traverse left lengthUtil(root->left, maximum, minimum, curr - 1); // if curr is decrease then get // value in minimum if (minimum > curr) minimum = curr; // if curr is increase then get // value in maximum if (maximum < curr) maximum = curr; // traverse right lengthUtil(root->right, maximum, minimum, curr + 1); } int getLength(Node* root) { int maximum = 0, minimum = 0; lengthUtil(root, maximum, minimum, 0); // 1 is added to include root in the width return (abs(minimum) + maximum) + 1; } // Utility function to create a new tree node Node* newNode(int data) { Node* curr = new Node; curr->data = data; curr->left = curr->right = NULL; return curr; } // Driver program to test above functions int main() { Node* root = newNode(7); root->left = newNode(6); root->right = newNode(5); root->left->left = newNode(4); root->left->right = newNode(3); root->right->left = newNode(2); root->right->right = newNode(1); cout << getLength(root) << ""\n""; return 0; }",logn,linear "// C++ program to find Vertical Height of a tree #include #include using namespace std; struct Node { int data; struct Node* left; struct Node* right; Node(int x) { data = x; left = right = NULL; } }; int verticalWidth(Node* root) { // Code here if (root == NULL) return 0; int maxLevel = 0, minLevel = 0; queue > q; q.push({ root, 0 }); // we take root as 0 // Level order traversal code while (q.empty() != true) { Node* cur = q.front().first; int count = q.front().second; q.pop(); if (cur->left) { minLevel = min(minLevel, count - 1); // as we go left, // level is decreased q.push({ cur->left, count - 1 }); } if (cur->right) { maxLevel = max(maxLevel, count + 1); // as we go right, // level is increased q.push({ cur->right, count + 1 }); } } return maxLevel + abs(minLevel) + 1; // +1 for the root node, we gave it a value // of zero } int main() { // making the tree Node* root = new Node(7); root->left = new Node(6); root->right = new Node(5); root->left->left = new Node(4); root->left->right = new Node(3); root->right->left = new Node(2); root->right->right = new Node(1); cout << ""Vertical width is : "" << verticalWidth(root) << endl; return 0; } // code contributed by Anshit Bansal",linear,linear "// CPP code to find vertical // width of a binary tree #include using namespace std; // Tree class class Node { public : int data; Node *left, *right; // Constructor Node(int data_new) { data = data_new; left = right = NULL; } }; // Function to fill hd in set. void fillSet(Node* root, unordered_set& s, int hd) { if (!root) return; fillSet(root->left, s, hd - 1); s.insert(hd); fillSet(root->right, s, hd + 1); } int verticalWidth(Node* root) { unordered_set s; // Third parameter is horizontal // distance fillSet(root, s, 0); return s.size(); } int main() { Node* root = NULL; // Creating the above tree root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); root->right->left->right = new Node(8); root->right->right->right = new Node(9); cout << verticalWidth(root) << ""\n""; return 0; }",linear,linear "// CPP program to determine whether // vertical level l of binary tree // is sorted or not. #include using namespace std; // Structure of a tree node. struct Node { int key; Node *left, *right; }; // Function to create new tree node. Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp; } // Helper function to determine if // vertical level l of given binary // tree is sorted or not. bool isSorted(Node* root, int level) { // If root is null, then the answer is an // empty subset and an empty subset is // always considered to be sorted. if (root == NULL) return true; // Variable to store previous // value in vertical level l. int prevVal = INT_MIN; // Variable to store current level // while traversing tree vertically. int currLevel; // Variable to store current node // while traversing tree vertically. Node* currNode; // Declare queue to do vertical order // traversal. A pair is used as element // of queue. The first element in pair // represents the node and the second // element represents vertical level // of that node. queue > q; // Insert root in queue. Vertical level // of root is 0. q.push(make_pair(root, 0)); // Do vertical order traversal until // all the nodes are not visited. while (!q.empty()) { currNode = q.front().first; currLevel = q.front().second; q.pop(); // Check if level of node extracted from // queue is required level or not. If it // is the required level then check if // previous value in that level is less // than or equal to value of node. if (currLevel == level) { if (prevVal <= currNode->key) prevVal = currNode->key; else return false; } // If left child is not NULL then push it // in queue with level reduced by 1. if (currNode->left) q.push(make_pair(currNode->left, currLevel - 1)); // If right child is not NULL then push it // in queue with level increased by 1. if (currNode->right) q.push(make_pair(currNode->right, currLevel + 1)); } // If the level asked is not present in the // given binary tree, that means that level // will contain an empty subset. Therefore answer // will be true. return true; } // Driver program int main() { /* 1 / \ 2 5 / \ 7 4 / 6 */ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(7); root->left->right = newNode(4); root->left->right->left = newNode(6); int level = -1; if (isSorted(root, level) == true) cout << ""Yes""; else cout << ""No""; return 0; }",linear,linear "// CPP program to determine whether // binary tree is level sorted or not. #include using namespace std; // Structure of a tree node. struct Node { int key; Node *left, *right; }; // Function to create new tree node. Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp; } // Function to determine if // given binary tree is level sorted // or not. int isSorted(Node* root) { // to store maximum value of previous // level. int prevMax = INT_MIN; // to store minimum value of current // level. int minval; // to store maximum value of current // level. int maxval; // to store number of nodes in current // level. int levelSize; // queue to perform level order traversal. queue q; q.push(root); while (!q.empty()) { // find number of nodes in current // level. levelSize = q.size(); minval = INT_MAX; maxval = INT_MIN; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q.front(); q.pop(); levelSize--; minval = min(minval, root->key); maxval = max(maxval, root->key); if (root->left) q.push(root->left); if (root->right) q.push(root->right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1; } // Driver program int main() { /* 1 / 4 \ 6 / \ 8 9 / \ 12 10 */ Node* root = newNode(1); root->left = newNode(4); root->left->right = newNode(6); root->left->right->left = newNode(8); root->left->right->right = newNode(9); root->left->right->left->left = newNode(12); root->left->right->right->right = newNode(10); if (isSorted(root)) cout << ""Sorted""; else cout << ""Not sorted""; return 0; }",linear,linear "// C++ Program to print Bottom View of Binary Tree #include using namespace std; // Tree node class struct Node { int data; //data of the node int hd; //horizontal distance of the node Node *left, *right; //left and right references // Constructor of tree node Node(int key) { data = key; hd = INT_MAX; left = right = NULL; } }; // Method that prints the bottom view. void bottomView(Node *root) { if (root == NULL) return; // Initialize a variable 'hd' with 0 // for the root element. int hd = 0; // TreeMap which stores key value pair // sorted on key value map m; // Queue to store tree nodes in level // order traversal queue q; // Assign initialized horizontal distance // value to root node and add it to the queue. root->hd = hd; q.push(root); // In STL, push() is used enqueue an item // Loop until the queue is empty (standard // level order loop) while (!q.empty()) { Node *temp = q.front(); q.pop(); // In STL, pop() is used dequeue an item // Extract the horizontal distance value // from the dequeued tree node. hd = temp->hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. Every // time we find a node having same horizontal // distance we need to replace the data in // the map. m[hd] = temp->data; // If the dequeued node has a left child, add // it to the queue with a horizontal distance hd-1. if (temp->left != NULL) { temp->left->hd = hd-1; q.push(temp->left); } // If the dequeued node has a right child, add // it to the queue with a horizontal distance // hd+1. if (temp->right != NULL) { temp->right->hd = hd+1; q.push(temp->right); } } // Traverse the map elements using the iterator. for (auto i = m.begin(); i != m.end(); ++i) cout << i->second << "" ""; } // Driver Code int main() { Node *root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(5); root->left->right = new Node(3); root->right->left = new Node(4); root->right->right = new Node(25); root->left->right->left = new Node(10); root->left->right->right = new Node(14); cout << ""Bottom view of the given binary tree :\n""; bottomView(root); return 0; }",linear,nlogn "// C++ Program to print Bottom View of Binary Tree #include #include using namespace std; // Tree node class struct Node { // data of the node int data; // horizontal distance of the node int hd; //left and right references Node * left, * right; // Constructor of tree node Node(int key) { data = key; hd = INT_MAX; left = right = NULL; } }; void printBottomViewUtil(Node * root, int curr, int hd, map > & m) { // Base case if (root == NULL) return; // If node for a particular // horizontal distance is not // present, add to the map. if (m.find(hd) == m.end()) { m[hd] = make_pair(root -> data, curr); } // Compare height for already // present node at similar horizontal // distance else { pair < int, int > p = m[hd]; if (p.second <= curr) { m[hd].second = curr; m[hd].first = root -> data; } } // Recur for left subtree printBottomViewUtil(root -> left, curr + 1, hd - 1, m); // Recur for right subtree printBottomViewUtil(root -> right, curr + 1, hd + 1, m); } void printBottomView(Node * root) { // Map to store Horizontal Distance, // Height and Data. map < int, pair < int, int > > m; printBottomViewUtil(root, 0, 0, m); // Prints the values stored by printBottomViewUtil() map < int, pair < int, int > > ::iterator it; for (it = m.begin(); it != m.end(); ++it) { pair < int, int > p = it -> second; cout << p.first << "" ""; } } int main() { Node * root = new Node(20); root -> left = new Node(8); root -> right = new Node(22); root -> left -> left = new Node(5); root -> left -> right = new Node(3); root -> right -> left = new Node(4); root -> right -> right = new Node(25); root -> left -> right -> left = new Node(10); root -> left -> right -> right = new Node(14); cout << ""Bottom view of the given binary tree :\n""; printBottomView(root); return 0; }",linear,nlogn "#include using namespace std; // Tree node class struct Node { // data of the node int data; // horizontal distance of the node int hd; //left and right references Node * left, * right; // Constructor of tree node Node(int key) { data = key; hd = INT_MAX; left = right = NULL; } }; void printBottomView(Node * root) { if(!root) return ;//if root is NULL unordered_map hash; // data> int leftmost = 0; // to store the leftmost index so that we move from left to right queue> q; // pair for level order traversal. q.push({root,0}); // push the root and 0 vertial index while(!q.empty()){ auto top = q.front(); // store q.front() in top variable q.pop(); Node *temp = top.first; // store the Node in temp for left and right nodes int ind = top.second; // store the vertical index of current node hash[ind] = temp->data; // store the latest vertical_index(key) -> root->data(value) leftmost = min(ind,leftmost); // have the leftmost vertical index if(temp->left){ q.push({temp->left,ind-1});}// check if any node of left then go in negative direction if(temp->right){ q.push({temp->right,ind+1});} //check if any node of left then go in positive direction } //teverse each value in hash from leftmost to positive side till key is available while(hash.find(leftmost)!=hash.end()){ cout< left = new Node(8); root -> right = new Node(22); root -> left -> left = new Node(5); root -> left -> right = new Node(3); root -> right -> left = new Node(4); root -> right -> right = new Node(25); root -> left -> right -> left = new Node(10); root -> left -> right -> right = new Node(14); cout << ""Bottom view of the given binary tree :\n""; printBottomView(root); return 0; }",linear,linear "// C++ program to count half nodes in a Binary Tree #include using namespace std; // A binary tree Node has data, pointer to left // child and a pointer to right child struct Node { int data; struct Node* left, *right; }; // Function to get the count of half Nodes in // a binary tree unsigned int gethalfCount(struct Node* node) { // If tree is empty if (!node) return 0; int count = 0; // Initialize count of half nodes // Do level order traversal starting from root queue q; q.push(node); while (!q.empty()) { struct Node *temp = q.front(); q.pop(); if (!temp->left && temp->right || temp->left && !temp->right) count++; if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } return count; } /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver program int main(void) { /* 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree shown in above example */ struct Node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left = newNode(1); root->left->right->right = newNode(11); root->right->right = newNode(9); root->right->right->left = newNode(4); cout << gethalfCount(root); return 0; }",linear,linear "// C++ program to count half nodes in a Binary Tree #include using namespace std; // A binary tree Node has data, pointer to left // child and a pointer to right child struct Node { int data; struct Node* left, *right; }; // Function to get the count of half Nodes in // a binary tree unsigned int gethalfCount(struct Node* root) { if (root == NULL) return 0; int res = 0; if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root->right == NULL)) res++; res += (gethalfCount(root->left) + gethalfCount(root->right)); return res; } /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver program int main(void) { /* 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree shown in above example */ struct Node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left = newNode(1); root->left->right->right = newNode(11); root->right->right = newNode(9); root->right->right->left = newNode(4); cout << gethalfCount(root); return 0; }",linear,linear "// C++ program to count // full nodes in a Binary Tree #include using namespace std; // A binary tree Node has data, pointer to left // child and a pointer to right child struct Node { int data; struct Node* left, *right; }; // Function to get the count of full Nodes in // a binary tree unsigned int getfullCount(struct Node* node) { // If tree is empty if (!node) return 0; queue q; // Do level order traversal starting from root int count = 0; // Initialize count of full nodes q.push(node); while (!q.empty()) { struct Node *temp = q.front(); q.pop(); if (temp->left && temp->right) count++; if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } return count; } /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver program int main(void) { /* 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree as shown */ struct Node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left = newNode(1); root->left->right->right = newNode(11); root->right->right = newNode(9); root->right->right->left = newNode(4); cout << getfullCount(root); return 0; }",linear,linear "// C++ program to count full nodes in a Binary Tree #include using namespace std; // A binary tree Node has data, pointer to left // child and a pointer to right child struct Node { int data; struct Node* left, *right; }; // Function to get the count of full Nodes in // a binary tree unsigned int getfullCount(struct Node* root) { if (root == NULL) return 0; int res = 0; if (root->left && root->right) res++; res += (getfullCount(root->left) + getfullCount(root->right)); return res; } /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver program int main(void) { /* 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree as shown */ struct Node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left = newNode(1); root->left->right->right = newNode(11); root->right->right = newNode(9); root->right->right->left = newNode(4); cout << getfullCount(root); return 0; }",linear,linear "// Connect nodes at same level using level order // traversal. #include using namespace std; struct Node { int data; struct Node* left, *right, *nextRight; }; // Sets nextRight of all nodes of a tree void connect(struct Node* root) { queue q; q.push(root); // null marker to represent end of current level q.push(NULL); // Do Level order of tree using NULL markers while (!q.empty()) { Node *p = q.front(); q.pop(); if (p != NULL) { // next element in queue represents next // node at current Level p->nextRight = q.front(); // push left and right children of current // node if (p->left) q.push(p->left); if (p->right) q.push(p->right); } // if queue is not empty, push NULL to mark // nodes at this level are visited else if (!q.empty()) q.push(NULL); } } /* UTILITY FUNCTIONS */ /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newnode(int data) { struct Node* node = (struct Node*) malloc(sizeof(struct Node)); node->data = data; node->left = node->right = node->nextRight = NULL; return (node); } /* Driver program to test above functions*/ int main() { /* Constructed binary tree is 10 / \ 8 2 / \ 3 90 */ struct Node* root = newnode(10); root->left = newnode(8); root->right = newnode(2); root->left->left = newnode(3); root->right->right = newnode(90); // Populates nextRight pointer in all nodes connect(root); // Let us check the values of nextRight pointers printf(""Following are populated nextRight pointers in \n"" ""the tree (-1 is printed if there is no nextRight) \n""); printf(""nextRight of %d is %d \n"", root->data, root->nextRight ? root->nextRight->data : -1); printf(""nextRight of %d is %d \n"", root->left->data, root->left->nextRight ? root->left->nextRight->data : -1); printf(""nextRight of %d is %d \n"", root->right->data, root->right->nextRight ? root->right->nextRight->data : -1); printf(""nextRight of %d is %d \n"", root->left->left->data, root->left->left->nextRight ? root->left->left->nextRight->data : -1); printf(""nextRight of %d is %d \n"", root->right->right->data, root->right->right->nextRight ? root->right->right->nextRight->data : -1); return 0; }",linear,linear "// Iterative CPP program to connect // nodes at same level using // constant extra space #include #include using namespace std; class node { public: int data; node* left; node* right; node *nextRight; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; this->nextRight = NULL; } }; /* This function returns the leftmost child of nodes at the same level as p. This function is used to getNExt right of p's right child If right child of is NULL then this can also be used for the left child */ node *getNextRight(node *p) { node *temp = p->nextRight; /* Traverse nodes at p's level and find and return the first node's first child */ while (temp != NULL) { if (temp->left != NULL) return temp->left; if (temp->right != NULL) return temp->right; temp = temp->nextRight; } // If all the nodes at p's level // are leaf nodes then return NULL return NULL; } /* Sets nextRight of all nodes of a tree with root as p */ void connectRecur(node* p) { node *temp; if (!p) return; // Set nextRight for root p->nextRight = NULL; // set nextRight of all levels one by one while (p != NULL) { node *q = p; /* Connect all children nodes of p and children nodes of all other nodes at same level as p */ while (q != NULL) { // Set the nextRight pointer // for p's left child if (q->left) { // If q has right child, then // right child is nextRight of // p and we also need to set // nextRight of right child if (q->right) q->left->nextRight = q->right; else q->left->nextRight = getNextRight(q); } if (q->right) q->right->nextRight = getNextRight(q); // Set nextRight for other // nodes in pre order fashion q = q->nextRight; } // start from the first // node of next level if (p->left) p = p->left; else if (p->right) p = p->right; else p = getNextRight(p); } } /* Driver code*/ int main() { /* Constructed binary tree is 10 / \ 8 2 / \ 3 90 */ node *root = new node(10); root->left = new node(8); root->right = new node(2); root->left->left = new node(3); root->right->right = new node(90); // Populates nextRight pointer in all nodes connectRecur(root); // Let us check the values of nextRight pointers cout << ""Following are populated nextRight pointers in the tree"" "" (-1 is printed if there is no nextRight) \n""; cout << ""nextRight of "" << root->data << "" is "" << (root->nextRight? root->nextRight->data: -1) <left->data << "" is "" << (root->left->nextRight? root->left->nextRight->data: -1) << endl; cout << ""nextRight of "" << root->right->data << "" is "" << (root->right->nextRight? root->right->nextRight->data: -1) << endl; cout << ""nextRight of "" << root->left->left->data<< "" is "" << (root->left->left->nextRight? root->left->left->nextRight->data: -1) << endl; cout << ""nextRight of "" << root->right->right->data << "" is "" << (root->right->right->nextRight? root->right->right->nextRight->data: -1) << endl; return 0; } // This code is contributed by rathbhupendra",constant,linear "/* Iterative program to connect all the adjacent nodes at * the same level in a binary tree*/ #include #include using namespace std; // A Binary Tree Node class node { public: int data; node* left; node* right; node* nextRight; /* Constructor that allocates a new node with the given data and NULL left and right pointers. */ node(int data) { this->data = data; this->left = NULL; this->right = NULL; this->nextRight = NULL; } }; // setting right pointer to next right node /* 10 ----------> NULL / \ 8 --->2 --------> NULL / 3 ----------------> NULL */ void connect(node* root) { // Base condition if (root == NULL) return; // Create an empty queue like level order traversal queue q; q.push(root); while (!q.empty()) { // size indicates no. of nodes at current level int size = q.size(); // for keeping track of previous node node* prev = NULL; while (size--) { node* temp = q.front(); q.pop(); if (temp->left) q.push(temp->left); if (temp->right) q.push(temp->right); if (prev != NULL) prev->nextRight = temp; prev = temp; } prev->nextRight = NULL; } } int main() { /* Constructed binary tree is 10 / \ 8 2 / 3 */ // Let us create binary tree shown above node* root = new node(10); root->left = new node(8); root->right = new node(2); root->left->left = new node(3); connect(root); // Let us check the values // of nextRight pointers cout << ""Following are populated nextRight pointers in "" ""the tree"" "" (-1 is printed if there is no nextRight)\n""; cout << ""nextRight of "" << root->data << "" is "" << (root->nextRight ? root->nextRight->data : -1) << endl; cout << ""nextRight of "" << root->left->data << "" is "" << (root->left->nextRight ? root->left->nextRight->data : -1) << endl; cout << ""nextRight of "" << root->right->data << "" is "" << (root->right->nextRight ? root->right->nextRight->data : -1) << endl; cout << ""nextRight of "" << root->left->left->data << "" is "" << (root->left->left->nextRight ? root->left->left->nextRight->data : -1) << endl; return 0; } // this code is contributed by Kapil Poonia",linear,linear "// C++ implementation to find the level // having maximum number of Nodes #include using namespace std; /* A binary tree Node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left; struct Node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node->left = NULL; node->right = NULL; return(node); } // function to find the level // having maximum number of Nodes int maxNodeLevel(Node *root) { if (root == NULL) return -1; queue q; q.push(root); // Current level int level = 0; // Maximum Nodes at same level int max = INT_MIN; // Level having maximum Nodes int level_no = 0; while (1) { // Count Nodes in a level int NodeCount = q.size(); if (NodeCount == 0) break; // If it is maximum till now // Update level_no to current level if (NodeCount > max) { max = NodeCount; level_no = level; } // Pop complete current level while (NodeCount > 0) { Node *Node = q.front(); q.pop(); if (Node->left != NULL) q.push(Node->left); if (Node->right != NULL) q.push(Node->right); NodeCount--; } // Increment for next level level++; } return level_no; } // Driver program to test above int main() { // binary tree formation struct Node *root = newNode(2); /* 2 */ root->left = newNode(1); /* / \ */ root->right = newNode(3); /* 1 3 */ root->left->left = newNode(4); /* / \ \ */ root->left->right = newNode(6); /* 4 6 8 */ root->right->right = newNode(8); /* / */ root->left->right->left = newNode(5);/* 5 */ printf(""Level having maximum number of Nodes : %d"", maxNodeLevel(root)); return 0; }",linear,linear "// C++ code for the above approach #include using namespace std; // A binary tree node has data, pointer to // left child and a pointer to right child struct Node { int val; struct Node *left, *right; }; // Initialising a map with key as levels of the tree map > mp; void avg(Node* r, int l) { // If the node is NULL if (r == NULL) return; // Add the current value to the sum of this level mp[l].first += r->val; // Increase the number of elements in the current level mp[l].second++; // Traverse left avg(r->left, l + 1); // Traverse right avg(r->right, l + 1); } void averageOfLevels(Node* root) { avg(root, 0); // Travaersing for levels in map for (auto i : mp) { // Printing average of all levels cout << (i.second.first / i.second.second) << ' '; } } // Function to create a new node Node* newNode(int data) { Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp; } int main() { /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); // Function Call averageOfLevels(root); } // This Code has been contributed by Alok Khansali",logn,nlogn "// C++ implementation to print largest // value in each level of Binary Tree #include using namespace std; // structure of a node of binary tree struct Node { int data; Node *left, *right; }; // function to get a new node Node* newNode(int data) { // allocate space Node* temp = new Node; // put in the data temp->data = data; temp->left = temp->right = NULL; return temp; } // function to print largest value // in each level of Binary Tree void largestValueInEachLevel(Node* root) { // if tree is empty if (!root) return; queue q; int nc, max; // push root to the queue 'q' q.push(root); while (1) { // node count for the current level nc = q.size(); // if true then all the nodes of // the tree have been traversed if (nc == 0) break; // maximum element for the current // level max = INT_MIN; while (nc--) { // get the front element from 'q' Node* front = q.front(); // remove front element from 'q' q.pop(); // if true, then update 'max' if (max < front->data) max = front->data; // if left child exists if (front->left) q.push(front->left); // if right child exists if (front->right) q.push(front->right); } // print maximum element of // current level cout << max << "" ""; } } // Driver code int main() { /* Construct a Binary Tree 4 / \ 9 2 / \ \ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(9); root->right = newNode(2); root->left->left = newNode(3); root->left->right = newNode(5); root->right->right = newNode(7); // Function call largestValueInEachLevel(root); return 0; }",constant,linear "// C++ program to Get Level of a node in a Binary Tree #include using namespace std; /* A tree node structure */ struct node { int data; struct node* left; struct node* right; }; // Helper function for getLevel(). It returns level of the // data if data is present in tree, otherwise returns 0. int getLevelUtil(struct node* node, int data, int level) { if (node == NULL) return 0; if (node->data == data) return level; int downlevel = getLevelUtil(node->left, data, level + 1); if (downlevel != 0) return downlevel; downlevel = getLevelUtil(node->right, data, level + 1); return downlevel; } /* Returns level of given data value */ int getLevel(struct node* node, int data) { return getLevelUtil(node, data, 1); } // Utility function to create a new Binary Tree node struct node* newNode(int data) { struct node* temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } // Driver Code int main() { struct node* root = new struct node; int x; // Constructing tree given in the above figure root = newNode(3); root->left = newNode(2); root->right = newNode(5); root->left->left = newNode(1); root->left->right = newNode(4); for (x = 1; x <= 5; x++) { int level = getLevel(root, x); if (level) cout << ""Level of "" << x << "" is "" << level << endl; else cout << x << ""is not present in tree"" << endl; } getchar(); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// C++ program to print level in which X is present in // binary tree using STL #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; int printLevel(Node* root, int X) { Node* node; // Base Case if (root == NULL) return 0; // Create an empty queue for level order traversal queue q; // Create a var represent current level of tree int currLevel = 1; // Enqueue Root q.push(root); while (q.empty() == false) { int size = q.size(); while (size--) { node = q.front(); if (node->data == X) return currLevel; q.pop(); /* Enqueue left child */ if (node->left != NULL) q.push(node->left); /*Enqueue right child */ if (node->right != NULL) q.push(node->right); } currLevel++; } return 0; } // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver program to test above functions int main() { // Let us create binary tree shown in above diagram Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(7); root->right->right = newNode(6); cout << printLevel(root, 6); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// CPP program to print level of given node // in binary tree iterative approach /* Example binary tree root is at level 1 20 / \ 10 30 / \ / \ 5 15 25 40 / 12 */ #include using namespace std; // node of binary tree struct node { int data; node* left; node* right; }; // utility function to create // a new node node* getnode(int data) { node* newnode = new node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; } // utility function to return level of given node int getlevel(node* root, int data) { queue q; int level = 1; q.push(root); // extra NULL is pushed to keep track // of all the nodes to be pushed before // level is incremented by 1 q.push(NULL); while (!q.empty()) { node* temp = q.front(); q.pop(); if (temp == NULL) { if (q.front() != NULL) { q.push(NULL); } level += 1; } else { if (temp->data == data) { return level; } if (temp->left) { q.push(temp->left); } if (temp->right) { q.push(temp->right); } } } return 0; } int main() { // create a binary tree node* root = getnode(20); root->left = getnode(10); root->right = getnode(30); root->left->left = getnode(5); root->left->right = getnode(15); root->left->right->left = getnode(12); root->right->left = getnode(25); root->right->right = getnode(40); // return level of node int level = getlevel(root, 30); (level != 0) ? (cout << ""level of node 30 is "" << level << endl) : (cout << ""node 30 not found"" << endl); level = getlevel(root, 12); (level != 0) ? (cout << ""level of node 12 is "" << level << endl) : (cout << ""node 12 not found"" << endl); level = getlevel(root, 25); (level != 0) ? (cout << ""level of node 25 is "" << level << endl) : (cout << ""node 25 not found"" << endl); level = getlevel(root, 27); (level != 0) ? (cout << ""level of node 27 is "" << level << endl) : (cout << ""node 27 not found"" << endl); return 0; }",linear,linear "// C++ program to remove all half nodes #include using namespace std; struct node { int data; struct node* left, *right; }; struct node* newNode(int data) { node* nod = new node(); nod->data = data; nod->left = nod->right = NULL; return(nod); } void printInoder(struct node*root) { if (root != NULL) { printInoder(root->left); cout<< root->data << "" ""; printInoder(root->right); } } // Removes all nodes with only one child and returns // new root (note that root may change) struct node* RemoveHalfNodes(struct node* root) { if (root==NULL) return NULL; root->left = RemoveHalfNodes(root->left); root->right = RemoveHalfNodes(root->right); if (root->left==NULL && root->right==NULL) return root; /* if current nodes is a half node with left child NULL left, then it's right child is returned and replaces it in the given tree */ if (root->left==NULL) { struct node *new_root = root->right; free(root); // To avoid memory leak return new_root; } /* if current nodes is a half node with right child NULL right, then it's right child is returned and replaces it in the given tree */ if (root->right==NULL) { struct node *new_root = root->left; free(root); // To avoid memory leak return new_root; } return root; } // Driver program int main(void) { struct node*NewRoot=NULL; struct node *root = newNode(2); root->left = newNode(7); root->right = newNode(5); root->left->right = newNode(6); root->left->right->left=newNode(1); root->left->right->right=newNode(11); root->right->right=newNode(9); root->right->right->left=newNode(4); cout<<""Inorder traversal of given tree \n""; printInoder(root); NewRoot = RemoveHalfNodes(root); cout<<""\nInorder traversal of the modified tree \n""; printInoder(NewRoot); return 0; }",constant,linear "/* C++ program to pairwise swap leaf nodes from left to right */ #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // function to swap two Node void Swap(Node **a, Node **b) { Node * temp = *a; *a = *b; *b = temp; } // two pointers to keep track of // first and second nodes in a pair Node **firstPtr; Node **secondPtr; // function to pairwise swap leaf // nodes from left to right void pairwiseSwap(Node **root, int &count) { // if node is null, return if (!(*root)) return; // if node is leaf node, increment count if(!(*root)->left&&!(*root)->right) { // initialize second pointer // by current node secondPtr = root; // increment count count++; // if count is even, swap first // and second pointers if (count%2 == 0) Swap(firstPtr, secondPtr); else // if count is odd, initialize // first pointer by second pointer firstPtr = secondPtr; } // if left child exists, check for leaf // recursively if ((*root)->left) pairwiseSwap(&(*root)->left, count); // if right child exists, check for leaf // recursively if ((*root)->right) pairwiseSwap(&(*root)->right, count); } // Utility function to create a new tree node Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // function to print inorder traversal // of binary tree void printInorder(Node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ printf(""%d "", node->data); /* now recur on right child */ printInorder(node->right); } // Driver program to test above functions int main() { // Let us create binary tree shown in // above diagram Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(5); root->right->right = newNode(8); root->right->left->left = newNode(6); root->right->left->right = newNode(7); root->right->right->left = newNode(9); root->right->right->right = newNode(10); // print inorder traversal before swapping cout << ""Inorder traversal before swap:\n""; printInorder(root); cout << ""\n""; // variable to keep track // of leafs traversed int c = 0; // Pairwise swap of leaf nodes pairwiseSwap(&root, c); // print inorder traversal after swapping cout << ""Inorder traversal after swap:\n""; printInorder(root); cout << ""\n""; return 0; }",linear,linear "// C++ program to find the length of longest // path with same values in a binary tree. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int val; struct Node *left, *right; }; /* Function to print the longest path of same values */ int length(Node *node, int *ans) { if (!node) return 0; // Recursive calls to check for subtrees int left = length(node->left, ans); int right = length(node->right, ans); // Variables to store maximum lengths in two directions int Leftmax = 0, Rightmax = 0; // If curr node and it's left child has same value if (node->left && node->left->val == node->val) Leftmax += left + 1; // If curr node and it's right child has same value if (node->right && node->right->val == node->val) Rightmax += right + 1; *ans = max(*ans, Leftmax + Rightmax); return max(Leftmax, Rightmax); } /* Driver function to find length of longest same value path*/ int longestSameValuePath(Node *root) { int ans = 0; length(root, &ans); return ans; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node *newNode(int data) { Node *temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp; } // Driver code int main() { /* Let us construct a Binary Tree 4 / \ 4 4 / \ \ 4 9 5 */ Node *root = NULL; root = newNode(4); root->left = newNode(4); root->right = newNode(4); root->left->left = newNode(4); root->left->right = newNode(9); root->right->right = newNode(5); cout << longestSameValuePath(root); return 0; }",logn,linear "// C++ program to find distance of a given // node from root. #include using namespace std; // A Binary Tree Node struct Node { int data; Node *left, *right; }; // A utility function to create a new Binary // Tree Node Node *newNode(int item) { Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } // Returns -1 if x doesn't exist in tree. Else // returns distance of x from root int findDistance(Node *root, int x) { // Base case if (root == NULL) return -1; // Initialize distance int dist = -1; // Check if x is present at root or in left // subtree or right subtree. if ((root->data == x) || (dist = findDistance(root->left, x)) >= 0 || (dist = findDistance(root->right, x)) >= 0) return dist + 1; return dist; } // Driver Program to test above functions int main() { Node *root = newNode(5); root->left = newNode(10); root->right = newNode(15); root->left->left = newNode(20); root->left->right = newNode(25); root->left->right->right = newNode(45); root->right->left = newNode(30); root->right->right = newNode(35); cout << findDistance(root, 45); return 0; }",constant,linear "// C program to print right sibling of a node #include // A Binary Tree Node struct Node { int data; Node *left, *right, *parent; }; // A utility function to create a new Binary // Tree Node Node* newNode(int item, Node* parent) { Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; temp->parent = parent; return temp; } // Method to find right sibling Node* findRightSibling(Node* node, int level) { if (node == NULL || node->parent == NULL) return NULL; // GET Parent pointer whose right child is not // a parent or itself of this node. There might // be case when parent has no right child, but, // current node is left child of the parent // (second condition is for that). while (node->parent->right == node || (node->parent->right == NULL && node->parent->left == node)) { if (node->parent == NULL || node->parent->parent == NULL) return NULL; node = node->parent; level--; } // Move to the required child, where right sibling // can be present node = node->parent->right; if (node == NULL) return NULL; // find right sibling in the given subtree(from current // node), when level will be 0 while (level < 0) { // Iterate through subtree if (node->left != NULL) node = node->left; else if (node->right != NULL) node = node->right; else // if no child are there, we cannot have right // sibling in this path break; level++; } if (level == 0) return node; // This is the case when we reach 9 node in the tree, // where we need to again recursively find the right // sibling return findRightSibling(node, level); } // Driver Program to test above functions int main() { Node* root = newNode(1, NULL); root->left = newNode(2, root); root->right = newNode(3, root); root->left->left = newNode(4, root->left); root->left->right = newNode(6, root->left); root->left->left->left = newNode(7, root->left->left); root->left->left->left->left = newNode(10, root->left->left->left); root->left->right->right = newNode(9, root->left->right); root->right->right = newNode(5, root->right); root->right->right->right = newNode(8, root->right->right); root->right->right->right->right = newNode(12, root->right->right->right); // passing 10 Node* res = findRightSibling(root->left->left->left->left, 0); if (res == NULL) printf(""No right sibling""); else printf(""%d"", res->data); return 0; }",constant,linear "/* C++ program to find next right of a given key using preorder traversal */ #include using namespace std; // A Binary Tree Node struct Node { struct Node *left, *right; int key; }; // Utility function to create a new tree node Node* newNode(int key) { Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp; } // Function to find next node for given node // in same level in a binary tree by using // pre-order traversal Node* nextRightNode(Node* root, int k, int level, int& value_level) { // return null if tree is empty if (root == NULL) return NULL; // if desired node is found, set value_level // to current level if (root->key == k) { value_level = level; return NULL; } // if value_level is already set, then current // node is the next right node else if (value_level) { if (level == value_level) return root; } // recurse for left subtree by increasing level by 1 Node* leftNode = nextRightNode(root->left, k, level + 1, value_level); // if node is found in left subtree, return it if (leftNode) return leftNode; // recurse for right subtree by increasing level by 1 return nextRightNode(root->right, k, level + 1, value_level); } // Function to find next node of given node in the // same level in given binary tree Node* nextRightNodeUtil(Node* root, int k) { int value_level = 0; return nextRightNode(root, k, 1, value_level); } // A utility function to test above functions void test(Node* root, int k) { Node* nr = nextRightNodeUtil(root, k); if (nr != NULL) cout << ""Next Right of "" << k << "" is "" << nr->key << endl; else cout << ""No next right node found for "" << k << endl; } // Driver program to test above functions int main() { // Let us create binary tree given in the // above example Node* root = newNode(10); root->left = newNode(2); root->right = newNode(6); root->right->right = newNode(5); root->left->left = newNode(8); root->left->right = newNode(4); test(root, 10); test(root, 2); test(root, 6); test(root, 5); test(root, 8); test(root, 4); return 0; }",constant,linear "// CPP Program to find Tilt of Binary Tree #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int val; struct Node *left, *right; }; /* Recursive function to calculate Tilt of whole tree */ int traverse(Node* root, int* tilt) { if (!root) return 0; // Compute tilts of left and right subtrees // and find sums of left and right subtrees int left = traverse(root->left, tilt); int right = traverse(root->right, tilt); // Add current tilt to overall *tilt += abs(left - right); // Returns sum of nodes under current tree return left + right + root->val; } /* Driver function to print Tilt of whole tree */ int Tilt(Node* root) { int tilt = 0; traverse(root, &tilt); return tilt; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node* newNode(int data) { Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp; } // Driver code int main() { /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); cout << ""The Tilt of whole tree is "" << Tilt(root); return 0; }",linear,linear "// C++ program to find averages of all levels // in a binary tree. #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left, *right; }; string inorder(Node* node, unordered_map& m) { if (!node) return """"; string str = ""(""; str += inorder(node->left, m); str += to_string(node->data); str += inorder(node->right, m); str += "")""; // Subtree already present (Note that we use // unordered_map instead of unordered_set // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m[str] == 1) cout << node->data << "" ""; m[str]++; return str; } // Wrapper over inorder() void printAllDups(Node* root) { unordered_map m; inorder(root, m); } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver code int main() { Node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(2); root->right->left->left = newNode(4); root->right->right = newNode(4); printAllDups(root); return 0; }",quadratic,quadratic "// CPP program to find largest three elements in // a binary tree. #include using namespace std; struct Node { int data; struct Node *left; struct Node *right; }; /* Helper function that allocates a new Node with the given data and NULL left and right pointers. */ struct Node *newNode(int data) { struct Node *node = new Node; node->data = data; node->left = NULL; node->right = NULL; return (node); } // function to find three largest element void threelargest(Node *root, int &first, int &second, int &third) { if (root == NULL) return; // if data is greater than first large number // update the top three list if (root->data > first) { third = second; second = first; first = root->data; } // if data is greater than second large number // and not equal to first update the bottom // two list else if (root->data > second && root->data != first) { third = second; second = root->data; } // if data is greater than third large number // and not equal to first & second update the // third highest list else if (root->data > third && root->data != first && root->data != second) third = root->data; threelargest(root->left, first, second, third); threelargest(root->right, first, second, third); } // driver function int main() { struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(4); root->right->right = newNode(5); int first = 0, second = 0, third = 0; threelargest(root, first, second, third); cout << ""three largest elements are "" << first << "" "" << second << "" "" << third; return 0; }",constant,linear "// C++ program to print DFS traversal from // a given vertex in a given graph #include using namespace std; // Graph class represents a directed graph // using adjacency list representation class Graph { public: map visited; map > adj; // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v void DFS(int v); }; void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::DFS(int v) { // Mark the current node as visited and // print it visited[v] = true; cout << v << "" ""; // Recur for all the vertices adjacent // to this vertex list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFS(*i); } // Driver's code int main() { // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << ""Following is Depth First Traversal"" "" (starting from vertex 2) \n""; // Function call g.DFS(2); return 0; } // improved by Vishnudev C",linear,linear "// C++ program to print DFS // traversal for a given // graph #include using namespace std; class Graph { // A function used by DFS void DFSUtil(int v); public: map visited; map > adj; // function to add an edge to graph void addEdge(int v, int w); // prints DFS traversal of the complete graph void DFS(); }; void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::DFSUtil(int v) { // Mark the current node as visited and print it visited[v] = true; cout << v << "" ""; // Recur for all the vertices adjacent to this vertex list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i); } // The function to do DFS traversal. It uses recursive // DFSUtil() void Graph::DFS() { // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (auto i : adj) if (visited[i.first] == false) DFSUtil(i.first); } // Driver's Code int main() { // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 9); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(9, 3); cout << ""Following is Depth First Traversal \n""; // Function call g.DFS(); return 0; } // improved by Vishnudev C",linear,linear "// C++ program to find a mother vertex in O(V+E) time #include using namespace std; class Graph { int V; // No. of vertices list* adj; // adjacency lists // A recursive function to print DFS starting from v void DFSUtil(int v, vector& visited); public: Graph(int V); void addEdge(int v, int w); int findMother(); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } // A recursive function to print DFS starting from v void Graph::DFSUtil(int v, vector& visited) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited); } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } // Returns a mother vertex if exists. Otherwise returns -1 int Graph::findMother() { // visited[] is used for DFS. Initially all are // initialized as not visited vector visited(V, false); // To store last finished vertex (or mother vertex) int v = 0; // Do a DFS traversal and find the last finished // vertex for (int i = 0; i < V; i++) { if (visited[i] == false) { DFSUtil(i, visited); v = i; } } // If there exist mother vertex (or vertices) in given // graph, then v must be one (or one of them) // Now check if v is actually a mother vertex (or graph // has a mother vertex). We basically check if every // vertex is reachable from v or not. // Reset all values in visited[] as false and do // DFS beginning from v to check if all vertices are // reachable from it or not. fill(visited.begin(), visited.end(), false); DFSUtil(v, visited); for (int i = 0; i < V; i++) if (visited[i] == false) return -1; return v; } // Driver code int main() { // Create a graph given in the above diagram Graph g(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(4, 1); g.addEdge(6, 4); g.addEdge(5, 6); g.addEdge(5, 2); g.addEdge(6, 0); // Function call cout << ""A mother vertex is "" << g.findMother(); return 0; }",linear,linear "/* * C++ program to count all paths from a source to a * destination. * https://www.geeksforgeeks.org/count-possible-paths-two-vertices/ * Note that the original example has been refactored. */ #include using namespace std; /* * A directed graph using adjacency list representation; * every vertex holds a list of all neighbouring vertices * that can be reached from it. */ class Graph { public: // Construct the graph given the number of vertices... Graph(int vertices); // Specify an edge between two vertices void add_edge(int src, int dst); // Call the recursive helper function to count all the // paths int count_paths(int src, int dst, int vertices); private: int m_vertices; list* m_neighbours; void path_counter(int src, int dst, int& path_count, vector& visited); }; Graph::Graph(int vertices) { m_vertices = vertices; // unused!! /* An array of linked lists - each element corresponds to a vertex and will hold a list of neighbours...*/ m_neighbours = new list[vertices]; } void Graph::add_edge(int src, int dst) { m_neighbours[src].push_back(dst); } int Graph::count_paths(int src, int dst, int vertices) { int path_count = 0; vector visited(vertices, false); path_counter(src, dst, path_count, visited); return path_count; } /* * A recursive function that counts all paths from src to * dst. Keep track of the count in the parameter. */ void Graph::path_counter(int src, int dst, int& path_count, vector& visited) { // If we've reached the destination, then increment // count... visited[src] = true; if (src == dst) { path_count++; } // ...otherwise recurse into all neighbours... else { for (auto neighbour : m_neighbours[src]) { if (!visited[neighbour]) path_counter(neighbour, dst, path_count, visited); } } visited[src] = false; } // Driver code int main() { // Create a graph given in the above diagram - see link Graph g(5); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(0, 4); g.add_edge(1, 3); g.add_edge(1, 4); g.add_edge(2, 3); g.add_edge(2, 1); g.add_edge(3, 2); // Function call cout << g.count_paths(0, 4, 5); return 0; }",linear,np "#include using namespace std; typedef pair pii; void printpath(map mp, pii u) { if (u.first == 0 && u.second == 0) { cout << 0 << "" "" << 0 << endl; return; } printpath(mp, mp[u]); cout << u.first << "" "" << u.second << endl; } void BFS(int a, int b, int target) { map m; bool isSolvable = false; map mp; queue q; q.push(make_pair(0, 0)); while (!q.empty()) { auto u = q.front(); // cout< a || u.second > b || u.first < 0 || u.second < 0)) continue; // cout< jug 2 int d = b - u.second; if (u.first >= d) { int c = u.first - d; if (m[{ c, b }] != 1) { q.push({ c, b }); mp[{ c, b }] = u; } } else { int c = u.first + u.second; if (m[{ 0, c }] != 1) { q.push({ 0, c }); mp[{ 0, c }] = u; } } // transfer jug 2 -> jug 1 d = a - u.first; if (u.second >= d) { int c = u.second - d; if (m[{ a, c }] != 1) { q.push({ a, c }); mp[{ a, c }] = u; } } else { int c = u.first + u.second; if (m[{ c, 0 }] != 1) { q.push({ c, 0 }); mp[{ c, 0 }] = u; } } // empty the jug 2 if (m[{ u.first, 0 }] != 1) { q.push({ u.first, 0 }); mp[{ u.first, 0 }] = u; } // empty the jug 1 if (m[{ 0, u.second }] != 1) { q.push({ 0, u.second }); mp[{ 0, u.second }] = u; } } if (!isSolvable) cout << ""No solution""; } int main() { int Jug1 = 4, Jug2 = 3, target = 2; cout << ""Path from initial state "" ""to solution state ::\n""; BFS(Jug1, Jug2, target); return 0; }",quadratic,quadratic "// CPP Program to determine level of each node // and print level #include using namespace std; // function to determine level of each node starting // from x using BFS void printLevels(vector graph[], int V, int x) { // array to store level of each node int level[V]; bool marked[V]; // create a queue queue que; // enqueue element x que.push(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (!que.empty()) { // get the first element of queue x = que.front(); // dequeue element que.pop(); // traverse neighbors of node x for (int i = 0; i < graph[x].size(); i++) { // b is neighbor of node x int b = graph[x][i]; // if b is not marked already if (!marked[b]) { // enqueue b in queue que.push(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels cout << ""Nodes"" << "" "" << ""Level"" << endl; for (int i = 0; i < V; i++) cout << "" "" << i << "" --> "" << level[i] << endl; } // Driver Code int main() { // adjacency graph for tree int V = 8; vector graph[V]; graph[0].push_back(1); graph[0].push_back(2); graph[1].push_back(3); graph[1].push_back(4); graph[1].push_back(5); graph[2].push_back(5); graph[2].push_back(6); graph[6].push_back(7); // call levels function with source as 0 printLevels(graph, V, 0); return 0; }",linear,linear "// C++ program to print all paths of source to // destination in given graph #include using namespace std; // utility function for printing // the found path in graph void printpath(vector& path) { int size = path.size(); for (int i = 0; i < size; i++) cout << path[i] << "" ""; cout << endl; } // utility function to check if current // vertex is already present in path int isNotVisited(int x, vector& path) { int size = path.size(); for (int i = 0; i < size; i++) if (path[i] == x) return 0; return 1; } // utility function for finding paths in graph // from source to destination void findpaths(vector >& g, int src, int dst, int v) { // create a queue which stores // the paths queue > q; // path vector to store the current path vector path; path.push_back(src); q.push(path); while (!q.empty()) { path = q.front(); q.pop(); int last = path[path.size() - 1]; // if last vertex is the desired destination // then print the path if (last == dst) printpath(path); // traverse to all the nodes connected to // current vertex and push new path to queue for (int i = 0; i < g[last].size(); i++) { if (isNotVisited(g[last][i], path)) { vector newpath(path); newpath.push_back(g[last][i]); q.push(newpath); } } } } // driver program int main() { vector > g; // number of vertices int v = 4; g.resize(4); // construct a graph g[0].push_back(3); g[0].push_back(1); g[0].push_back(2); g[1].push_back(3); g[2].push_back(0); g[2].push_back(1); int src = 2, dst = 3; cout << ""path from src "" << src << "" to dst "" << dst << "" are \n""; // function for finding the paths findpaths(g, src, dst, v); return 0; }",quadratic,np "// C++ program to find minimum edge // between given two vertex of Graph #include using namespace std; // function for finding minimum no. of edge // using BFS int minEdgeBFS(vector edges[], int u, int v, int n) { // visited[n] for keeping track of visited // node in BFS vector visited(n, 0); // Initialize distances as 0 vector distance(n, 0); // queue to do BFS. queue Q; distance[u] = 0; Q.push(u); visited[u] = true; while (!Q.empty()) { int x = Q.front(); Q.pop(); for (int i=0; i edges[], int u, int v) { edges[u].push_back(v); edges[v].push_back(u); } // Driver function int main() { // To store adjacency list of graph int n = 9; vector edges[9]; addEdge(edges, 0, 1); addEdge(edges, 0, 7); addEdge(edges, 1, 7); addEdge(edges, 1, 2); addEdge(edges, 2, 3); addEdge(edges, 2, 5); addEdge(edges, 2, 8); addEdge(edges, 3, 4); addEdge(edges, 3, 5); addEdge(edges, 4, 5); addEdge(edges, 5, 6); addEdge(edges, 6, 7); addEdge(edges, 7, 8); int u = 0; int v = 5; cout << minEdgeBFS(edges, u, v, n); return 0; }",linear,linear "// C++ program to find minimum steps to reach to // specific cell in minimum moves by Knight #include using namespace std; // structure for storing a cell's data struct cell { int x, y; int dis; cell() {} cell(int x, int y, int dis) : x(x) , y(y) , dis(dis) { } }; // Utility method returns true if (x, y) lies // inside Board bool isInside(int x, int y, int N) { if (x >= 1 && x <= N && y >= 1 && y <= N) return true; return false; } // Method returns minimum step // to reach target position int minStepToReachTarget(int knightPos[], int targetPos[], int N) { // x and y direction, where a knight can move int dx[] = { -2, -1, 1, 2, -2, -1, 1, 2 }; int dy[] = { -1, -2, -2, -1, 1, 2, 2, 1 }; // queue for storing states of knight in board queue q; // push starting position of knight with 0 distance q.push(cell(knightPos[0], knightPos[1], 0)); cell t; int x, y; bool visit[N + 1][N + 1]; // make all cell unvisited for (int i = 1; i <= N; i++) for (int j = 1; j <= N; j++) visit[i][j] = false; // visit starting state visit[knightPos[0]][knightPos[1]] = true; // loop until we have one element in queue while (!q.empty()) { t = q.front(); q.pop(); // if current cell is equal to target cell, // return its distance if (t.x == targetPos[0] && t.y == targetPos[1]) return t.dis; // loop for all reachable states for (int i = 0; i < 8; i++) { x = t.x + dx[i]; y = t.y + dy[i]; // If reachable state is not yet visited and // inside board, push that state into queue if (isInside(x, y, N) && !visit[x][y]) { visit[x][y] = true; q.push(cell(x, y, t.dis + 1)); } } } } // Driver code int main() { int N = 30; int knightPos[] = { 1, 1 }; int targetPos[] = { 30, 30 }; // Function call cout << minStepToReachTarget(knightPos, targetPos, N); return 0; }",quadratic,quadratic "// C++ Program to find the length of the largest // region in boolean 2D-matrix #include using namespace std; #define ROW 4 #define COL 5 // A function to check if // a given cell (row, col) // can be included in DFS int isSafe(int M[][COL], int row, int col, bool visited[][COL]) { // row number is in range, // column number is in // range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]); } // A utility function to // do DFS for a 2D boolean // matrix. It only considers // the 8 neighbours as // adjacent vertices void DFS(int M[][COL], int row, int col, bool visited[][COL], int& count) { // These arrays are used // to get row and column // numbers of 8 neighbours // of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // Increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited, count); } } } // The main function that returns // largest length region // of a given boolean 2D matrix int largestRegion(int M[][COL]) { // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize result as 0 and travesle through the // all cells of given matrix int result = INT_MIN; for (int i = 0; i < ROW; ++i) { for (int j = 0; j < COL; ++j) { // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new region found int count = 1; DFS(M, i, j, visited, count); // maximum region result = max(result, count); } } } return result; } // Driver code int main() { int M[][COL] = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; // Function call cout << largestRegion(M); return 0; }",quadratic,quadratic "// C++ program for the above approach #include using namespace std; // Function to find unit area of the largest region of 1s. int largestRegion(vector >& grid) { int m = grid.size(); int n = grid[0].size(); // creating a queue that will help in bfs traversal queue > q; int area = 0; int ans = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // if the value at any particular cell is 1 then // from here we need to do the BFS traversal if (grid[i][j] == 1) { ans = 0; // pushing the pair in the queue q.push(make_pair(i, j)); // marking the value 1 to -1 so that we // don't again push this cell in the queue grid[i][j] = -1; while (!q.empty()) { pair t = q.front(); q.pop(); ans++; int x = t.first; int y = t.second; // now we will check in all 8 directions if (x + 1 < m) { if (grid[x + 1][y] == 1) { q.push(make_pair(x + 1, y)); grid[x + 1][y] = -1; } } if (x - 1 >= 0) { if (grid[x - 1][y] == 1) { q.push(make_pair(x - 1, y)); grid[x - 1][y] = -1; } } if (y + 1 < n) { if (grid[x][y + 1] == 1) { q.push(make_pair(x, y + 1)); grid[x][y + 1] = -1; } } if (y - 1 >= 0) { if (grid[x][y - 1] == 1) { q.push(make_pair(x, y - 1)); grid[x][y - 1] = -1; } } if (x + 1 < m && y + 1 < n) { if (grid[x + 1][y + 1] == 1) { q.push(make_pair(x + 1, y + 1)); grid[x + 1][y + 1] = -1; } } if (x - 1 >= 0 && y + 1 < n) { if (grid[x - 1][y + 1] == 1) { q.push(make_pair(x - 1, y + 1)); grid[x - 1][y + 1] = -1; } } if (x - 1 >= 0 && y - 1 >= 0) { if (grid[x - 1][y - 1] == 1) { q.push(make_pair(x - 1, y - 1)); grid[x - 1][y - 1] = -1; } } if (x + 1 < m && y - 1 >= 0) { if (grid[x + 1][y - 1] == 1) { q.push(make_pair(x + 1, y - 1)); grid[x + 1][y - 1] = -1; } } } area = max(ans, area); ans = 0; } } } return area; } // Driver Code int main() { vector > M = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; // Function call cout << largestRegion(M); return 0; }",quadratic,quadratic "// A C++ Program to detect // cycle in an undirected graph #include #include #include using namespace std; // Class for an undirected graph class Graph { // No. of vertices int V; // Pointer to an array // containing adjacency lists list* adj; bool isCyclicUtil(int v, bool visited[], int parent); public: // Constructor Graph(int V); // To add an edge to graph void addEdge(int v, int w); // Returns true if there is a cycle bool isCyclic(); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int v, int w) { // Add w to v’s list. adj[v].push_back(w); // Add v to w’s list. adj[w].push_back(v); } // A recursive function that // uses visited[] and parent to detect // cycle in subgraph reachable // from vertex v. bool Graph::isCyclicUtil(int v, bool visited[], int parent) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices // adjacent to this vertex list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // If an adjacent vertex is not visited, // then recur for that adjacent if (!visited[*i]) { if (isCyclicUtil(*i, visited, v)) return true; } // If an adjacent vertex is visited and // is not parent of current vertex, // then there exists a cycle in the graph. else if (*i != parent) return true; } return false; } // Returns true if the graph contains // a cycle, else false. bool Graph::isCyclic() { // Mark all the vertices as not // visited and not part of recursion // stack bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper // function to detect cycle in different // DFS trees for (int u = 0; u < V; u++) { // Don't recur for u if // it is already visited if (!visited[u]) if (isCyclicUtil(u, visited, -1)) return true; } return false; } // Driver program to test above functions int main() { Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.isCyclic() ? cout << ""Graph contains cycle\n"" : cout << ""Graph doesn't contain cycle\n""; Graph g2(3); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.isCyclic() ? cout << ""Graph contains cycle\n"" : cout << ""Graph doesn't contain cycle\n""; return 0; }",linear,linear "// A DFS based approach to find if there is a cycle // in a directed graph. This approach strictly follows // the algorithm given in CLRS book. #include using namespace std; enum Color {WHITE, GRAY, BLACK}; // Graph class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices list* adj; // adjacency lists // DFS traversal of the vertices reachable from v bool DFSUtil(int v, int color[]); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); bool isCyclic(); }; // Constructor Graph::Graph(int V) { this->V = V; adj = new list[V]; } // Utility function to add an edge void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v's list. } // Recursive function to find if there is back edge // in DFS subtree tree rooted with 'u' bool Graph::DFSUtil(int u, int color[]) { // GRAY : This vertex is being processed (DFS // for this vertex has started, but not // ended (or this vertex is in function // call stack) color[u] = GRAY; // Iterate through all adjacent vertices list::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // An adjacent of u // If there is if (color[v] == GRAY) return true; // If v is not processed and there is a back // edge in subtree rooted with v if (color[v] == WHITE && DFSUtil(v, color)) return true; } // Mark this vertex as processed color[u] = BLACK; return false; } // Returns true if there is a cycle in graph bool Graph::isCyclic() { // Initialize color of all vertices as WHITE int *color = new int[V]; for (int i = 0; i < V; i++) color[i] = WHITE; // Do a DFS traversal beginning with all // vertices for (int i = 0; i < V; i++) if (color[i] == WHITE) if (DFSUtil(i, color) == true) return true; return false; } // Driver code to test above int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); if (g.isCyclic()) cout << ""Graph contains cycle""; else cout << ""Graph doesn't contain cycle""; return 0; }",linear,linear "// C++ program to check if there is a cycle of // total odd weight #include using namespace std; // This function returns true if the current subpart // of the forest is two colorable, else false. bool twoColorUtil(vectorG[], int src, int N, int colorArr[]) { // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and // enqueue source vertex for BFS traversal queue q; q.push(src); // Run while there are vertices in queue // (Similar to BFS) while (!q.empty()){ int u = q.front(); q.pop(); // Find all non-colored adjacent vertices for (int v = 0; v < G[u].size(); ++v){ // An edge from u to v exists and // destination v is not colored if (colorArr[G[u][v]] == -1){ // Assign alternate color to this // adjacent v of u colorArr[G[u][v]] = 1 - colorArr[u]; q.push(G[u][v]); } // An edge from u to v exists and destination // v is colored with same color as u else if (colorArr[G[u][v]] == colorArr[u]) return false; } } return true; } // This function returns true if graph G[V][V] is two // colorable, else false bool twoColor(vectorG[], int N){ // Create a color array to store colors assigned // to all vertices. Vertex number is used as index // in this array. The value '-1' of colorArr[i] // is used to indicate that no color is assigned // to vertex 'i'. The value 1 is used to indicate // first color is assigned and value 0 indicates // second color is assigned. int colorArr[N]; for (int i = 1; i <= N; ++i) colorArr[i] = -1; // As we are dealing with graph, the input might // come as a forest, thus start coloring from a // node and if true is returned we'll know that // we successfully colored the subpart of our // forest and we start coloring again from a new // uncolored node. This way we cover the entire forest. for (int i = 1; i <= N; i++) if (colorArr[i] == -1) if (twoColorUtil(G, i, N, colorArr) == false) return false; return true; } // Returns false if an odd cycle is present else true // int info[][] is the information about our graph // int n is the number of nodes // int m is the number of informations given to us bool isOddSum(int info[][3],int n,int m){ // Declaring adjacency list of a graph // Here at max, we can encounter all the edges with // even weight thus there will be 1 pseudo node // for each edge vector G[2*n]; int pseudo = n+1; int pseudo_count = 0; for (int i=0; i using namespace std; const int MAX_VERTEX = 101; // Arr to represent parent of index i int Arr[MAX_VERTEX]; // Size to represent the number of nodes // in subgraph rooted at index i int size[MAX_VERTEX]; // set parent of every node to itself and // size of node to one void initialize(int n) { for (int i = 0; i <= n; i++) { Arr[i] = i; size[i] = 1; } } // Each time we follow a path, find function // compresses it further until the path length // is greater than or equal to 1. int find(int i) { // while we reach a node whose parent is // equal to itself while (Arr[i] != i) { Arr[i] = Arr[Arr[i]]; // Skip one level i = Arr[i]; // Move to the new level } return i; } // A function that does union of two nodes x and y // where xr is root node of x and yr is root node of y void _union(int xr, int yr) { if (size[xr] < size[yr]) // Make yr parent of xr { Arr[xr] = Arr[yr]; size[yr] += size[xr]; } else // Make xr parent of yr { Arr[yr] = Arr[xr]; size[xr] += size[yr]; } } // The main function to check whether a given // graph contains cycle or not int isCycle(vector adj[], int V) { // Iterate through all edges of graph, find // nodes connecting them. // If root nodes of both are same, then there is // cycle in graph. for (int i = 0; i < V; i++) { for (int j = 0; j < adj[i].size(); j++) { int x = find(i); // find root of i int y = find(adj[i][j]); // find root of adj[i][j] if (x == y) return 1; // If same parent _union(x, y); // Make them connect } } return 0; } // Driver progxrm to test above functions int main() { int V = 3; // Initialize the values for array Arr and Size initialize(V); /* Let us create following graph 0 | \ | \ 1-----2 */ vector adj[V]; // Adjacency list for graph adj[0].push_back(1); adj[0].push_back(2); adj[1].push_back(2); // call is_cycle to check if it contains cycle if (isCycle(adj, V)) cout << ""Graph contains Cycle.\n""; else cout << ""Graph does not contain Cycle.\n""; return 0; }",constant,logn "// C++ program to find number of magical // indices in the given array. #include using namespace std; #define mp make_pair #define pb push_back #define mod 1000000007 // Function to count number of magical indices. int solve(int A[], int n) { int i, cnt = 0, j; // Array to store parent node of traversal. int parent[n + 1]; // Array to determine whether current node // is already counted in the cycle. int vis[n + 1]; // Initialize the arrays. memset(parent, -1, sizeof(parent)); memset(vis, 0, sizeof(vis)); for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (!vis[j]) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt; } int main() { int A[] = { 0, 0, 0, 2 }; int n = sizeof(A) / sizeof(A[0]); cout << solve(A, n); return 0; }",linear,linear "// C++ program to print all topological sorts of a graph #include using namespace std; class Graph { int V; // No. of vertices // Pointer to an array containing adjacency list list *adj; // Vector to store indegree of vertices vector indegree; // A function used by alltopologicalSort void alltopologicalSortUtil(vector& res, bool visited[]); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // Prints all Topological Sorts void alltopologicalSort(); }; // Constructor of graph Graph::Graph(int V) { this->V = V; adj = new list[V]; // Initialising all indegree with 0 for (int i = 0; i < V; i++) indegree.push_back(0); } // Utility function to add edge void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v's list. // increasing inner degree of w by 1 indegree[w]++; } // Main recursive function to print all possible // topological sorts void Graph::alltopologicalSortUtil(vector& res, bool visited[]) { // To indicate whether all topological are found // or not bool flag = false; for (int i = 0; i < V; i++) { // If indegree is 0 and not yet visited then // only choose that vertex if (indegree[i] == 0 && !visited[i]) { // reducing indegree of adjacent vertices list:: iterator j; for (j = adj[i].begin(); j != adj[i].end(); j++) indegree[*j]--; // including in result res.push_back(i); visited[i] = true; alltopologicalSortUtil(res, visited); // resetting visited, res and indegree for // backtracking visited[i] = false; res.erase(res.end() - 1); for (j = adj[i].begin(); j != adj[i].end(); j++) indegree[*j]++; flag = true; } } // We reach here if all vertices are visited. // So we print the solution here if (!flag) { for (int i = 0; i < res.size(); i++) cout << res[i] << "" ""; cout << endl; } } // The function does all Topological Sort. // It uses recursive alltopologicalSortUtil() void Graph::alltopologicalSort() { // Mark all the vertices as not visited bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; vector res; alltopologicalSortUtil(res, visited); } // Driver program to test above functions int main() { // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << ""All Topological sorts\n""; g.alltopologicalSort(); return 0; }",linear,quadratic "// A C++ program to print topological // sorting of a graph using indegrees. #include using namespace std; // Class to represent a graph class Graph { // No. of vertices' int V; // Pointer to an array containing // adjacency listsList list* adj; public: // Constructor Graph(int V); // Function to add an edge to graph void addEdge(int u, int v); // prints a Topological Sort of // the complete graph void topologicalSort(); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int u, int v) { adj[u].push_back(v); } // The function to do // Topological Sort. void Graph::topologicalSort() { // Create a vector to store // indegrees of all // vertices. Initialize all // indegrees as 0. vector in_degree(V, 0); // Traverse adjacency lists // to fill indegrees of // vertices. This step // takes O(V+E) time for (int u = 0; u < V; u++) { list::iterator itr; for (itr = adj[u].begin(); itr != adj[u].end(); itr++) in_degree[*itr]++; } // Create an queue and enqueue // all vertices with indegree 0 queue q; for (int i = 0; i < V; i++) if (in_degree[i] == 0) q.push(i); // Initialize count of visited vertices int cnt = 0; // Create a vector to store // result (A topological // ordering of the vertices) vector top_order; // One by one dequeue vertices // from queue and enqueue // adjacents if indegree of // adjacent becomes 0 while (!q.empty()) { // Extract front of queue // (or perform dequeue) // and add it to topological order int u = q.front(); q.pop(); top_order.push_back(u); // Iterate through all its // neighbouring nodes // of dequeued node u and // decrease their in-degree // by 1 list::iterator itr; for (itr = adj[u].begin(); itr != adj[u].end(); itr++) // If in-degree becomes zero, // add it to queue if (--in_degree[*itr] == 0) q.push(*itr); cnt++; } // Check if there was a cycle if (cnt != V) { cout << ""There exists a cycle in the graph\n""; return; } // Print topological order for (int i = 0; i < top_order.size(); i++) cout << top_order[i] << "" ""; cout << endl; } // Driver program to test above functions int main() { // Create a graph given in the // above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << ""Following is a Topological Sort of\n""; g.topologicalSort(); return 0; }",linear,linear "// A C++ program for Prim's Minimum // Spanning Tree (MST) algorithm. The program is // for adjacency matrix representation of the graph #include using namespace std; // Number of vertices in the graph #define V 5 // A utility function to find the vertex with // minimum key value, from the set of vertices // not yet included in MST int minKey(int key[], bool mstSet[]) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index; } // A utility function to print the // constructed MST stored in parent[] void printMST(int parent[], int graph[V][V]) { cout << ""Edge \tWeight\n""; for (int i = 1; i < V; i++) cout << parent[i] << "" - "" << i << "" \t"" << graph[i][parent[i]] << "" \n""; } // Function to construct and print MST for // a graph represented using adjacency // matrix representation void primMST(int graph[V][V]) { // Array to store constructed MST int parent[V]; // Key values used to pick minimum weight edge in cut int key[V]; // To represent set of vertices included in MST bool mstSet[V]; // Initialize all keys as INFINITE for (int i = 0; i < V; i++) key[i] = INT_MAX, mstSet[i] = false; // Always include first 1st vertex in MST. // Make key 0 so that this vertex is picked as first // vertex. key[0] = 0; parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum key vertex from the // set of vertices not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of // the adjacent vertices of the picked vertex. // Consider only those vertices which are not // yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent // vertices of m mstSet[v] is false for vertices // not yet included in MST Update the key only // if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph); } // Driver's code int main() { /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution primMST(graph); return 0; } // This code is contributed by rathbhupendra",linear,quadratic "// C++ program for the above approach #include using namespace std; // DSU data structure // path compression + rank by union class DSU { int* parent; int* rank; public: DSU(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = -1; rank[i] = 1; } } // Find function int find(int i) { if (parent[i] == -1) return i; return parent[i] = find(parent[i]); } // Union function void unite(int x, int y) { int s1 = find(x); int s2 = find(y); if (s1 != s2) { if (rank[s1] < rank[s2]) { parent[s1] = s2; rank[s2] += rank[s1]; } else { parent[s2] = s1; rank[s1] += rank[s2]; } } } }; class Graph { vector > edgelist; int V; public: Graph(int V) { this->V = V; } void addEdge(int x, int y, int w) { edgelist.push_back({ w, x, y }); } void kruskals_mst() { // 1. Sort all edges sort(edgelist.begin(), edgelist.end()); // Initialize the DSU DSU s(V); int ans = 0; cout << ""Following are the edges in the "" ""constructed MST"" << endl; for (auto edge : edgelist) { int w = edge[0]; int x = edge[1]; int y = edge[2]; // Take this edge in MST if it does // not forms a cycle if (s.find(x) != s.find(y)) { s.unite(x, y); ans += w; cout << x << "" -- "" << y << "" == "" << w << endl; } } cout << ""Minimum Cost Spanning Tree: "" << ans; } }; // Driver's code int main() { /* Let us create following weighted graph 10 0--------1 | \ | 6| 5\ |15 | \ | 2--------3 4 */ Graph g(4); g.addEdge(0, 1, 10); g.addEdge(1, 3, 15); g.addEdge(2, 3, 4); g.addEdge(2, 0, 6); g.addEdge(0, 3, 5); // Function call g.kruskals_mst(); return 0; }",linear,nlogn "/* C++ program to solve N Queen Problem using backtracking */ #include #define N 4 using namespace std; /* A utility function to print solution */ void printSolution(int board[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << "" "" << board[i][j] << "" ""; printf(""\n""); } } /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when ""col"" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */ bool isSafe(int board[N][N], int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true; } /* A recursive utility function to solve N Queen problem */ bool solveNQUtil(int board[N][N], int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen cannot be placed in any row in this column col then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { cout << ""Solution does not exist""; return false; } printSolution(board); return true; } // driver program to test above function int main() { solveNQ(); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",quadratic,np "/* C++ program to solve N Queen Problem using backtracking */ #include using namespace std; #define N 4 /* ld is an array where its indices indicate row-col+N-1 (N-1) is for shifting the difference to store negative indices */ int ld[30] = { 0 }; /* rd is an array where its indices indicate row+col and used to check whether a queen can be placed on right diagonal or not*/ int rd[30] = { 0 }; /*column array where its indices indicates column and used to check whether a queen can be placed in that row or not*/ int cl[30] = { 0 }; /* A utility function to print solution */ void printSolution(int board[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout<<"" ""<< board[i][j]<<"" ""; cout<= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { cout<<""Solution does not exist""; return false; } printSolution(board); return true; } // driver program to test above function int main() { solveNQ(); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,np "// C++ program for Dijkstra's single source shortest path // algorithm. The program is for adjacency matrix // representation of the graph #include using namespace std; #include // Number of vertices in the graph #define V 9 // A utility function to find the vertex with minimum // distance value, from the set of vertices not yet included // in shortest path tree int minDistance(int dist[], bool sptSet[]) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index; } // A utility function to print the constructed distance // array void printSolution(int dist[]) { cout << ""Vertex \t Distance from Source"" << endl; for (int i = 0; i < V; i++) cout << i << "" \t\t\t\t"" << dist[i] << endl; } // Function that implements Dijkstra's single source // shortest path algorithm for a graph represented using // adjacency matrix representation void dijkstra(int graph[V][V], int src) { int dist[V]; // The output array. dist[i] will hold the // shortest // distance from src to i bool sptSet[V]; // sptSet[i] will be true if vertex i is // included in shortest // path tree or shortest distance from src to i is // finalized // Initialize all distances as INFINITE and stpSet[] as // false for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex from the set of // vertices not yet processed. u is always equal to // src in the first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of the // picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, // there is an edge from u to v, and total // weight of path from src to v through u is // smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist); } // driver's code int main() { /* Let us create the example graph discussed above */ int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; // Function call dijkstra(graph, 0); return 0; } // This code is contributed by shivanisinghss2110",linear,quadratic "// C++ Program to find Dijkstra's shortest path using // priority_queue in STL #include using namespace std; #define INF 0x3f3f3f3f // iPair ==> Integer Pair typedef pair iPair; // This class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list >* adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // prints shortest path from s void shortestPath(int s); }; // Allocates memory for adjacency list Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int u, int v, int w) { adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w)); } // Prints shortest paths from src to all other vertices void Graph::shortestPath(int src) { // Create a priority queue to store vertices that // are being preprocessed. This is weird syntax in C++. // Refer below link for details of this syntax // https://www.geeksforgeeks.org/implement-min-heap-using-stl/ priority_queue, greater > pq; // Create a vector for distances and initialize all // distances as infinite (INF) vector dist(V, INF); // Insert source itself in priority queue and initialize // its distance as 0. pq.push(make_pair(0, src)); dist[src] = 0; /* Looping till priority queue becomes empty (or all distances are not finalized) */ while (!pq.empty()) { // The first vertex in pair is the minimum distance // vertex, extract it from priority queue. // vertex label is stored in second of pair (it // has to be done this way to keep the vertices // sorted distance (distance must be first item // in pair) int u = pq.top().second; pq.pop(); // 'i' is used to get all adjacent vertices of a // vertex list >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // Get vertex label and weight of current // adjacent of u. int v = (*i).first; int weight = (*i).second; // If there is shorted path to v through u. if (dist[v] > dist[u] + weight) { // Updating distance of v dist[v] = dist[u] + weight; pq.push(make_pair(dist[v], v)); } } } // Print shortest distances stored in dist[] printf(""Vertex Distance from Source\n""); for (int i = 0; i < V; ++i) printf(""%d \t\t %d\n"", i, dist[i]); } // Driver's code int main() { // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); // Function call g.shortestPath(0); return 0; }",linear,nlogn "// A C++ program for Bellman-Ford's single source // shortest path algorithm. #include using namespace std; // a structure to represent a weighted edge in graph struct Edge { int src, dest, weight; }; // a structure to represent a connected, directed and // weighted graph struct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. struct Edge* edge; }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[E]; return graph; } // A utility function used to print the solution void printArr(int dist[], int n) { printf(""Vertex Distance from Source\n""); for (int i = 0; i < n; ++i) printf(""%d \t\t %d\n"", i, dist[i]); } // The main function that finds shortest distances from src // to all other vertices using Bellman-Ford algorithm. The // function also detects negative weight cycle void BellmanFord(struct Graph* graph, int src) { int V = graph->V; int E = graph->E; int dist[V]; // Step 1: Initialize distances from src to all other // vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. A simple // shortest path from src to any other vertex can have // at-most |V| - 1 edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph->edge[j].src; int v = graph->edge[j].dest; int weight = graph->edge[j].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. The above // step guarantees shortest distances if graph doesn't // contain negative weight cycle. If we get a shorter // path, then there is a cycle. for (int i = 0; i < E; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; int weight = graph->edge[i].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { printf(""Graph contains negative weight cycle""); return; // If negative cycle is detected, simply // return } } printArr(dist, V); return; } // Driver's code int main() { /* Let us create the graph given in above example */ int V = 5; // Number of vertices in graph int E = 8; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph->edge[2].src = 1; graph->edge[2].dest = 2; graph->edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 2; // add edge 1-4 (or B-E in above figure) graph->edge[4].src = 1; graph->edge[4].dest = 4; graph->edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph->edge[5].src = 3; graph->edge[5].dest = 2; graph->edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph->edge[6].src = 3; graph->edge[6].dest = 1; graph->edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph->edge[7].src = 4; graph->edge[7].dest = 3; graph->edge[7].weight = -3; // Function call BellmanFord(graph, 0); return 0; }",linear,quadratic "// C++ Program for Floyd Warshall Algorithm #include using namespace std; // Number of vertices in the graph #define V 4 /* Define Infinite as a large enough value.This value will be used for vertices not connected to each other */ #define INF 99999 // A function to print the solution matrix void printSolution(int dist[][V]); // Solves the all-pairs shortest path // problem using Floyd Warshall algorithm void floydWarshall(int graph[][V]) { /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of // dist[i][j] if (dist[i][j] > (dist[i][k] + dist[k][j]) && (dist[k][j] != INF && dist[i][k] != INF)) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist); } /* A utility function to print solution */ void printSolution(int dist[][V]) { cout << ""The following matrix shows the shortest "" ""distances"" "" between every pair of vertices \n""; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == INF) cout << ""INF"" << "" ""; else cout << dist[i][j] << "" ""; } cout << endl; } } // Driver's code int main() { /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int graph[V][V] = { { 0, 5, INF, 10 }, { INF, 0, 3, INF }, { INF, INF, 0, 1 }, { INF, INF, INF, 0 } }; // Function call floydWarshall(graph); return 0; } // This code is contributed by Mythri J L",quadratic,cubic "// Dynamic Programming based C++ program to find shortest path with // exactly k edges #include #include using namespace std; // Define number of vertices in the graph and infinite value #define V 4 #define INF INT_MAX // A Dynamic programming based function to find the shortest path from // u to v with exactly k edges. int shortestPath(int graph[][V], int u, int v, int k) { // Table to be filled up using DP. The value sp[i][j][e] will store // weight of the shortest path from i to j with exactly k edges int sp[V][V][k+1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; //go to adjacent only when number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and a // should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } } } return sp[u][v][k]; } // driver program to test above function int main() { /* Let us create the graph shown in above diagram*/ int graph[V][V] = { {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; int u = 0, v = 3, k = 2; cout << shortestPath(graph, u, v, k); return 0; }",np,cubic "// CPP code for printing shortest path between // two vertices of unweighted graph #include using namespace std; // utility function to form edge between two vertices // source and dest void add_edge(vector adj[], int src, int dest) { adj[src].push_back(dest); adj[dest].push_back(src); } // a modified version of BFS that stores predecessor // of each vertex in array p // and its distance from source in array d bool BFS(vector adj[], int src, int dest, int v, int pred[], int dist[]) { // a queue to maintain queue of vertices whose // adjacency list is to be scanned as per normal // DFS algorithm list queue; // boolean array visited[] which stores the // information whether ith vertex is reached // at least once in the Breadth first search bool visited[v]; // initially all vertices are unvisited // so v[i] for all i is false // and as no path is yet constructed // dist[i] for all i set to infinity for (int i = 0; i < v; i++) { visited[i] = false; dist[i] = INT_MAX; pred[i] = -1; } // now source is first to be visited and // distance from source to itself should be 0 visited[src] = true; dist[src] = 0; queue.push_back(src); // standard BFS algorithm while (!queue.empty()) { int u = queue.front(); queue.pop_front(); for (int i = 0; i < adj[u].size(); i++) { if (visited[adj[u][i]] == false) { visited[adj[u][i]] = true; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.push_back(adj[u][i]); // We stop BFS when we find // destination. if (adj[u][i] == dest) return true; } } } return false; } // utility function to print the shortest distance // between source vertex and destination vertex void printShortestDistance(vector adj[], int s, int dest, int v) { // predecessor[i] array stores predecessor of // i and distance array stores distance of i // from s int pred[v], dist[v]; if (BFS(adj, s, dest, v, pred, dist) == false) { cout << ""Given source and destination"" << "" are not connected""; return; } // vector path stores the shortest path vector path; int crawl = dest; path.push_back(crawl); while (pred[crawl] != -1) { path.push_back(pred[crawl]); crawl = pred[crawl]; } // distance from source is in distance array cout << ""Shortest path length is : "" << dist[dest]; // printing path from source to destination cout << ""\nPath is::\n""; for (int i = path.size() - 1; i >= 0; i--) cout << path[i] << "" ""; } // Driver program to test above functions int main() { // no. of vertices int v = 8; // array of vectors is used to store the graph // in the form of an adjacency list vector adj[v]; // Creating graph given in the above diagram. // add_edge function takes adjacency list, source // and destination vertex as argument and forms // an edge between them. add_edge(adj, 0, 1); add_edge(adj, 0, 3); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 3, 7); add_edge(adj, 4, 5); add_edge(adj, 4, 6); add_edge(adj, 4, 7); add_edge(adj, 5, 6); add_edge(adj, 6, 7); int source = 0, dest = 7; printShortestDistance(adj, source, dest, v); return 0; }",linear,linear "// C++ program to get least cost path in a grid from // top-left to bottom-right #include using namespace std; #define ROW 5 #define COL 5 // structure for information of each cell struct cell { int x, y; int distance; cell(int x, int y, int distance) : x(x) , y(y) , distance(distance) { } }; // Utility method for comparing two cells bool operator<(const cell& a, const cell& b) { if (a.distance == b.distance) { if (a.x != b.x) return (a.x < b.x); else return (a.y < b.y); } return (a.distance < b.distance); } // Utility method to check whether a point is // inside the grid or not bool isInsideGrid(int i, int j) { return (i >= 0 && i < ROW && j >= 0 && j < COL); } // Method returns minimum cost to reach bottom // right from top left int shortest(int grid[ROW][COL], int row, int col) { int dis[row][col]; // initializing distance array by INT_MAX for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) dis[i][j] = INT_MAX; // direction arrays for simplification of getting // neighbour int dx[] = { -1, 0, 1, 0 }; int dy[] = { 0, 1, 0, -1 }; set st; // insert (0, 0) cell with 0 distance st.insert(cell(0, 0, 0)); // initialize distance of (0, 0) with its grid value dis[0][0] = grid[0][0]; // loop for standard dijkstra's algorithm while (!st.empty()) { // get the cell with minimum distance and delete // it from the set cell k = *st.begin(); st.erase(st.begin()); // looping through all neighbours for (int i = 0; i < 4; i++) { int x = k.x + dx[i]; int y = k.y + dy[i]; // if not inside boundary, ignore them if (!isInsideGrid(x, y)) continue; // If distance from current cell is smaller, // then update distance of neighbour cell if (dis[x][y] > dis[k.x][k.y] + grid[x][y]) { // If cell is already there in set, then // remove its previous entry if (dis[x][y] != INT_MAX) st.erase( st.find(cell(x, y, dis[x][y]))); // update the distance and insert new // updated cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y]; st.insert(cell(x, y, dis[x][y])); } } } // uncomment below code to print distance // of each cell from (0, 0) /* for (int i = 0; i < row; i++, cout << endl) for (int j = 0; j < col; j++) cout << dis[i][j] << "" ""; */ // dis[row - 1][col - 1] will represent final // distance of bottom right cell from top left cell return dis[row - 1][col - 1]; } // Driver code to test above methods int main() { int grid[ROW][COL] = { 31, 100, 65, 12, 18, 10, 13, 47, 157, 6, 100, 113, 174, 11, 33, 88, 124, 41, 20, 140, 99, 32, 111, 41, 20 }; cout << shortest(grid, ROW, COL) << endl; return 0; }",quadratic,quadratic "// C++ program to replace all of the O's in the matrix // with their shortest distance from a guard #include using namespace std; // store dimensions of the matrix #define M 5 #define N 5 // An Data Structure for queue used in BFS struct queueNode { // i, j and distance stores x and y-coordinates // of a matrix cell and its distance from guard // respectively int i, j, distance; }; // These arrays are used to get row and column // numbers of 4 neighbors of a given cell int row[] = { -1, 0, 1, 0}; int col[] = { 0, 1, 0, -1 }; // return true if row number and column number // is in range bool isValid(int i, int j) { if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true; } // return true if current cell is an open area and its // distance from guard is not calculated yet bool isSafe(int i, int j, char matrix[][N], int output[][N]) { if (matrix[i][j] != 'O' || output[i][j] != -1) return false; return true; } // Function to replace all of the O's in the matrix // with their shortest distance from a guard void findDistance(char matrix[][N]) { int output[M][N]; queue q; // finding Guards location and adding into queue for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { // initialize each cell as -1 output[i][j] = -1; if (matrix[i][j] == 'G') { queueNode pos = {i, j, 0}; q.push(pos); // guard has 0 distance output[i][j] = 0; } } } // do till queue is empty while (!q.empty()) { // get the front cell in the queue and update // its adjacent cells queueNode curr = q.front(); int x = curr.i, y = curr.j, dist = curr.distance; // do for each adjacent cell for (int i = 0; i < 4; i++) { // if adjacent cell is valid, has path and // not visited yet, en-queue it. if (isSafe(x + row[i], y + col[i], matrix, output) && isValid(x + row[i], y + col[i])) { output[x + row[i]][y + col[i]] = dist + 1; queueNode pos = {x + row[i], y + col[i], dist + 1}; q.push(pos); } } // dequeue the front cell as its distance is found q.pop(); } // print output matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) cout << std::setw(3) << output[i][j]; cout << endl; } } // Driver code int main() { char matrix[][N] = { {'O', 'O', 'O', 'O', 'G'}, {'O', 'W', 'W', 'O', 'O'}, {'O', 'O', 'O', 'W', 'O'}, {'G', 'W', 'W', 'W', 'O'}, {'O', 'O', 'O', 'O', 'G'} }; findDistance(matrix); return 0; }",quadratic,quadratic "// C++ program to find articulation points in an undirected graph #include using namespace std; // A recursive function that find articulation // points using DFS traversal // adj[] --> Adjacency List representation of the graph // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // low[] -- >> earliest visited vertex (the vertex with minimum // discovery time) that can be reached from subtree // rooted with current vertex // parent --> Stores the parent vertex in DFS tree // isAP[] --> Stores articulation points void APUtil(vector adj[], int u, bool visited[], int disc[], int low[], int& time, int parent, bool isAP[]) { // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this for (auto v : adj[u]) { // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; APUtil(adj, v, visited, disc, low, time, u, isAP); // Check if the subtree rooted with v has // a connection to one of the ancestors of u low[u] = min(low[u], low[v]); // If u is not root and low value of one of // its child is more than discovery value of u. if (parent != -1 && low[v] >= disc[u]) isAP[u] = true; } // Update low value of u for parent function calls. else if (v != parent) low[u] = min(low[u], disc[v]); } // If u is root of DFS tree and has two or more children. if (parent == -1 && children > 1) isAP[u] = true; } void AP(vector adj[], int V) { int disc[V] = { 0 }; int low[V]; bool visited[V] = { false }; bool isAP[V] = { false }; int time = 0, par = -1; // Adding this loop so that the // code works even if we are given // disconnected graph for (int u = 0; u < V; u++) if (!visited[u]) APUtil(adj, u, visited, disc, low, time, par, isAP); // Printing the APs for (int u = 0; u < V; u++) if (isAP[u] == true) cout << u << "" ""; } // Utility function to add an edge void addEdge(vector adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } int main() { // Create graphs given in above diagrams cout << ""Articulation points in first graph \n""; int V = 5; vector adj1[V]; addEdge(adj1, 1, 0); addEdge(adj1, 0, 2); addEdge(adj1, 2, 1); addEdge(adj1, 0, 3); addEdge(adj1, 3, 4); AP(adj1, V); cout << ""\nArticulation points in second graph \n""; V = 4; vector adj2[V]; addEdge(adj2, 0, 1); addEdge(adj2, 1, 2); addEdge(adj2, 2, 3); AP(adj2, V); cout << ""\nArticulation points in third graph \n""; V = 7; vector adj3[V]; addEdge(adj3, 0, 1); addEdge(adj3, 1, 2); addEdge(adj3, 2, 0); addEdge(adj3, 1, 3); addEdge(adj3, 1, 4); addEdge(adj3, 1, 6); addEdge(adj3, 3, 5); addEdge(adj3, 4, 5); AP(adj3, V); return 0; }",linear,linear "// C++ Program to count islands in boolean 2D matrix #include using namespace std; #define ROW 5 #define COL 5 // A function to check if a given // cell (row, col) can be included in DFS int isSafe(int M[][COL], int row, int col, bool visited[][COL]) { // row number is in range, column // number is in range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]); } // A utility function to do DFS for a // 2D boolean matrix. It only considers // the 8 neighbours as adjacent vertices void DFS(int M[][COL], int row, int col, bool visited[][COL]) { // These arrays are used to get // row and column numbers of 8 // neighbours of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited); } // The main function that returns // count of islands in a given boolean // 2D matrix int countIslands(int M[][COL]) { // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize count as 0 and // traverse through the all cells of // given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new island found // Visit all cells in this island. DFS(M, i, j, visited); // and increment island count ++count; } return count; } // Driver code int main() { int M[][COL] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << ""Number of islands is: "" << countIslands(M); return 0; } // This is code is contributed by rathbhupendra",quadratic,quadratic "// C++Program to count islands in boolean 2D matrix #include using namespace std; // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices void DFS(vector >& M, int i, int j, int ROW, int COL) { // Base condition // if i less than 0 or j less than 0 or i greater than // ROW-1 or j greater than COL- or if M[i][j] != 1 then // we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); // right side traversal DFS(M, i - 1, j, ROW, COL); // left side traversal DFS(M, i, j + 1, ROW, COL); // upward side traversal DFS(M, i, j - 1, ROW, COL); // downward side traversal DFS(M, i + 1, j + 1, ROW, COL); // upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); // downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); // downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); // upward-left side traversal } } int countIslands(vector >& M) { int ROW = M.size(); int COL = M[0].size(); int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i][j] == 1) { count++; DFS(M, i, j, ROW, COL); // traversal starts // from current cell } } } return count; } // Driver Code int main() { vector > M = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << ""Number of islands is: "" << countIslands(M); return 0; } // This code is contributed by ajaymakvana. // Code improved by Animesh Singh",quadratic,quadratic "// C++ program to find number of islands // using Disjoint Set data structure. #include using namespace std; // Class to represent // Disjoint Set Data structure class DisjointUnionSets { vector rank, parent; int n; public: DisjointUnionSets(int n) { rank.resize(n); parent.resize(n); this->n = n; makeSet(); } void makeSet() { // Initially, all elements // are in their own set. for (int i = 0; i < n; i++) parent[i] = i; } // Finds the representative of the set // that x is an element of int find(int x) { if (parent[x] != x) { // if x is not the parent of itself, // then x is not the representative of // its set. // so we recursively call Find on its parent // and move i's node directly under the // representative of this set parent[x]=find(parent[x]); } return parent[x]; } // Unites the set that includes x and the set // that includes y void Union(int x, int y) { // Find the representatives(or the root nodes) // for x an y int xRoot = find(x); int yRoot = find(y); // Elements are in the same set, // no need to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank // Then move x under y so that // depth of tree remains less if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; // Else if y's rank is less than x's rank // Then move y under x so that depth of tree // remains less else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else // Else if their ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } } }; // Returns number of islands in a[][] int countIslands(vector>a) { int n = a.size(); int m = a[0].size(); DisjointUnionSets *dus = new DisjointUnionSets(n * m); /* The following loop checks for its neighbours and unites the indexes if both are 1. */ for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { // If cell is 0, nothing to do if (a[j][k] == 0) continue; // Check all 8 neighbours and do a Union // with neighbour's set if neighbour is // also 1 if (j + 1 < n && a[j + 1][k] == 1) dus->Union(j * (m) + k, (j + 1) * (m) + k); if (j - 1 >= 0 && a[j - 1][k] == 1) dus->Union(j * (m) + k, (j - 1) * (m) + k); if (k + 1 < m && a[j][k + 1] == 1) dus->Union(j * (m) + k, (j) * (m) + k + 1); if (k - 1 >= 0 && a[j][k - 1] == 1) dus->Union(j * (m) + k, (j) * (m) + k - 1); if (j + 1 < n && k + 1 < m && a[j + 1][k + 1] == 1) dus->Union(j * (m) + k, (j + 1) * (m) + k + 1); if (j + 1 < n && k - 1 >= 0 && a[j + 1][k - 1] == 1) dus->Union(j * m + k, (j + 1) * (m) + k - 1); if (j - 1 >= 0 && k + 1 < m && a[j - 1][k + 1] == 1) dus->Union(j * m + k, (j - 1) * m + k + 1); if (j - 1 >= 0 && k - 1 >= 0 && a[j - 1][k - 1] == 1) dus->Union(j * m + k, (j - 1) * m + k - 1); } } // Array to note down frequency of each set int *c = new int[n * m]; int numberOfIslands = 0; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if (a[j][k] == 1) { int x = dus->find(j * m + k); // If frequency of set is 0, // increment numberOfIslands if (c[x] == 0) { numberOfIslands++; c[x]++; } else c[x]++; } } } return numberOfIslands; } // Driver Code int main(void) { vector>a = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; cout << ""Number of Islands is: "" << countIslands(a) << endl; } // This code is contributed by ankush_953",quadratic,quadratic "// C++ program to count walks from u to // v with exactly k edges #include using namespace std; // Number of vertices in the graph #define V 4 // A naive recursive function to count // walks from u to v with k edges int countwalks(int graph[][V], int u, int v, int k) { // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v]) return 1; if (k <= 0) return 0; // Initialize result int count = 0; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) if (graph[u][i] == 1) // Check if is adjacent of u count += countwalks(graph, i, v, k - 1); return count; } // driver program to test above function int main() { /* Let us create the graph shown in above diagram*/ int graph[V][V] = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0; }",linear,quadratic "// C++ program to count walks from // u to v with exactly k edges #include using namespace std; // Number of vertices in the graph #define V 4 // A Dynamic programming based function to count walks from u // to v with k edges int countwalks(int graph[][V], int u, int v, int k) { // Table to be filled up using DP. // The value count[i][j][e] will // store count of possible walks from // i to j with exactly k edges int count[V][V][k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value count[i][j][e] = 0; // from base cases if (e == 0 && i == j) count[i][j][e] = 1; if (e == 1 && graph[i][j]) count[i][j][e] = 1; // go to adjacent only when the // number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) // adjacent of source i if (graph[i][a]) count[i][j][e] += count[a][j][e - 1]; } } } } return count[u][v][k]; } // driver program to test above function int main() { /* Let us create the graph shown in above diagram*/ int graph[V][V] = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0; }",np,cubic "// C++ program to find length // of the shortest chain // transformation from source // to target #include using namespace std; // Returns length of shortest chain // to reach 'target' from 'start' // using minimum number of adjacent // moves. D is dictionary int shortestChainLen( string start, string target, set& D) { if(start == target) return 0; // If the target string is not // present in the dictionary if (D.find(target) == D.end()) return 0; // To store the current chain length // and the length of the words int level = 0, wordlength = start.size(); // Push the starting word into the queue queue Q; Q.push(start); // While the queue is non-empty while (!Q.empty()) { // Increment the chain length ++level; // Current size of the queue int sizeofQ = Q.size(); // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (int i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue string word = Q.front(); Q.pop(); // For every character of the word for (int pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position char orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; // If the new word is equal // to the target word if (word == target) return level + 1; // Remove the word from the set // if it is found in it if (D.find(word) == D.end()) continue; D.erase(word); // And push the newly generated word // which will be a part of the chain Q.push(word); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0; } // Driver program int main() { // make dictionary set D; D.insert(""poon""); D.insert(""plee""); D.insert(""same""); D.insert(""poie""); D.insert(""plie""); D.insert(""poin""); D.insert(""plea""); string start = ""toon""; string target = ""plea""; cout << ""Length of shortest chain is: "" << shortestChainLen(start, target, D); return 0; }",quadratic,cubic "// C++ program to find length // of the shortest chain // transformation from source // to target #include using namespace std; // Returns length of shortest chain // to reach 'target' from 'start' // using minimum number of adjacent // moves. D is dictionary int shortestChainLen( string start, string target, set& D) { if(start == target) return 0; // Map of intermediate words and // the list of original words map> umap; // Find all the intermediate // words for the start word for(int i = 0; i < start.size(); i++) { string str = start.substr(0,i) + ""*"" + start.substr(i+1); umap[str].push_back(start); } // Find all the intermediate words for // the words in the given Set for(auto it = D.begin(); it != D.end(); it++) { string word = *it; for(int j = 0; j < word.size(); j++) { string str = word.substr(0,j) + ""*"" + word.substr(j+1); umap[str].push_back(word); } } // Perform BFS and push (word, distance) queue> q; map visited; q.push(make_pair(start,1)); visited[start] = 1; // Traverse until queue is empty while(!q.empty()) { pair p = q.front(); q.pop(); string word = p.first; int dist = p.second; // If target word is found if(word == target) { return dist; } // Finding intermediate words for // the word in front of queue for(int i = 0; i < word.size(); i++) { string str = word.substr(0,i) + ""*"" + word.substr(i+1); vector vect = umap[str]; for(int j = 0; j < vect.size(); j++) { // If the word is not visited if(visited[vect[j]] == 0) { visited[vect[j]] = 1; q.push(make_pair(vect[j], dist + 1)); } } } } return 0; } // Driver code int main() { // Make dictionary set D; D.insert(""poon""); D.insert(""plee""); D.insert(""same""); D.insert(""poie""); D.insert(""plie""); D.insert(""poin""); D.insert(""plea""); string start = ""toon""; string target = ""plea""; cout << ""Length of shortest chain is: "" << shortestChainLen(start, target, D); return 0; }",quadratic,cubic "// C++ program to print all paths // from a source to destination. #include #include using namespace std; // A directed graph using // adjacency list representation class Graph { int V; // No. of vertices in graph list* adj; // Pointer to an array containing // adjacency lists // A recursive function used by printAllPaths() void printAllPathsUtil(int, int, bool[], int[], int&); public: Graph(int V); // Constructor void addEdge(int u, int v); void printAllPaths(int s, int d); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } void Graph::addEdge(int u, int v) { adj[u].push_back(v); // Add v to u’s list. } // Prints all paths from 's' to 'd' void Graph::printAllPaths(int s, int d) { // Mark all the vertices as not visited bool* visited = new bool[V]; // Create an array to store paths int* path = new int[V]; int path_index = 0; // Initialize path[] as empty // Initialize all vertices as not visited for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to print all paths printAllPathsUtil(s, d, visited, path, path_index); } // A recursive function to print all paths from 'u' to 'd'. // visited[] keeps track of vertices in current path. // path[] stores actual vertices and path_index is current // index in path[] void Graph::printAllPathsUtil(int u, int d, bool visited[], int path[], int& path_index) { // Mark the current node and store it in path[] visited[u] = true; path[path_index] = u; path_index++; // If current vertex is same as destination, then print // current path[] if (u == d) { for (int i = 0; i < path_index; i++) cout << path[i] << "" ""; cout << endl; } else // If current vertex is not destination { // Recur for all the vertices adjacent to current // vertex list::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (!visited[*i]) printAllPathsUtil(*i, d, visited, path, path_index); } // Remove current vertex from path[] and mark it as // unvisited path_index--; visited[u] = false; } // Driver program int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); int s = 2, d = 3; cout << ""Following are all different paths from "" << s << "" to "" << d << endl; g.printAllPaths(s, d); return 0; }",np,quadratic "// C++ code to check if cyclic order is possible among strings // under given constraints #include using namespace std; #define M 26 // Utility method for a depth first search among vertices void dfs(vector g[], int u, vector &visit) { visit[u] = true; for (int i = 0; i < g[u].size(); ++i) if(!visit[g[u][i]]) dfs(g, g[u][i], visit); } // Returns true if all vertices are strongly connected // i.e. can be made as loop bool isConnected(vector g[], vector &mark, int s) { // Initialize all vertices as not visited vector visit(M, false); // perform a dfs from s dfs(g, s, visit); // now loop through all characters for (int i = 0; i < M; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visit[i]) return false; } // If we reach that means graph is connected return true; } // return true if an order among strings is possible bool possibleOrderAmongString(string arr[], int N) { // Create an empty graph vector g[M]; // Initialize all vertices as not marked vector mark(M, false); // Initialize indegree and outdegree of every // vertex as 0. vector in(M, 0), out(M, 0); // Process all strings one by one for (int i = 0; i < N; i++) { // Find first and last characters int f = arr[i].front() - 'a'; int l = arr[i].back() - 'a'; // Mark the characters mark[f] = mark[l] = true; // increase indegree and outdegree count in[l]++; out[f]++; // Add an edge in graph g[f].push_back(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for (int i = 0; i < M; i++) if (in[i] != out[i]) return false; return isConnected(g, mark, arr[0].front() - 'a'); } // Driver code to test above methods int main() { // string arr[] = {""abc"", ""efg"", ""cde"", ""ghi"", ""ija""}; string arr[] = {""ab"", ""bc"", ""cd"", ""de"", ""ed"", ""da""}; int N = sizeof(arr) / sizeof(arr[0]); if (possibleOrderAmongString(arr, N) == false) cout << ""Ordering not possible\n""; else cout << ""Ordering is possible\n""; return 0; }",linear,linear "// C++ program to count cyclic points // in an array using Kosaraju's Algorithm #include using namespace std; // Most of the code is taken from below link // https://www.geeksforgeeks.org/strongly-connected-components/ class Graph { int V; list* adj; void fillOrder(int v, bool visited[], stack& Stack); int DFSUtil(int v, bool visited[]); public: Graph(int V); void addEdge(int v, int w); int countSCCNodes(); Graph getTranspose(); }; Graph::Graph(int V) { this->V = V; adj = new list[V]; } // Counts number of nodes reachable // from v int Graph::DFSUtil(int v, bool visited[]) { visited[v] = true; int ans = 1; list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) ans += DFSUtil(*i, visited); return ans; } Graph Graph::getTranspose() { Graph g(V); for (int v = 0; v < V; v++) { list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) g.adj[*i].push_back(v); } return g; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); } void Graph::fillOrder(int v, bool visited[], stack& Stack) { visited[v] = true; list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) fillOrder(*i, visited, Stack); Stack.push(v); } // This function mainly returns total count of // nodes in individual SCCs using Kosaraju's // algorithm. int Graph::countSCCNodes() { int res = 0; stack Stack; bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; for (int i = 0; i < V; i++) if (visited[i] == false) fillOrder(i, visited, Stack); Graph gr = getTranspose(); for (int i = 0; i < V; i++) visited[i] = false; while (Stack.empty() == false) { int v = Stack.top(); Stack.pop(); if (visited[v] == false) { int ans = gr.DFSUtil(v, visited); if (ans > 1) res += ans; } } return res; } // Returns count of cyclic elements in arr[] int countCyclic(int arr[], int n) { int res = 0; // Create a graph of array elements Graph g(n + 1); for (int i = 1; i <= n; i++) { int x = arr[i-1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering // cyclic array int v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; g.addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += g.countSCCNodes(); return res; } // Driver code int main() { int arr[] = {1, 1, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << countCyclic(arr, n); return 0; }",linear,linear "// C++ program to print connected components in // an undirected graph #include using namespace std; // Graph class represents a undirected graph // using adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing adjacency lists list* adj; // A function used by DFS void DFSUtil(int v, bool visited[]); public: Graph(int V); // Constructor ~Graph(); void addEdge(int v, int w); void connectedComponents(); }; // Method to print connected components in an // undirected graph void Graph::connectedComponents() { // Mark all the vertices as not visited bool* visited = new bool[V]; for (int v = 0; v < V; v++) visited[v] = false; for (int v = 0; v < V; v++) { if (visited[v] == false) { // print all reachable vertices // from v DFSUtil(v, visited); cout << ""\n""; } } delete[] visited; } void Graph::DFSUtil(int v, bool visited[]) { // Mark the current node as visited and print it visited[v] = true; cout << v << "" ""; // Recur for all the vertices // adjacent to this vertex list::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited); } Graph::Graph(int V) { this->V = V; adj = new list[V]; } Graph::~Graph() { delete[] adj; } // method to add an undirected edge void Graph::addEdge(int v, int w) { adj[v].push_back(w); adj[w].push_back(v); } // Driver code int main() { // Create a graph given in the above diagram Graph g(5); // 5 vertices numbered from 0 to 4 g.addEdge(1, 0); g.addEdge(2, 1); g.addEdge(3, 4); cout << ""Following are connected components \n""; g.connectedComponents(); return 0; }",linear,linear "#include using namespace std; int merge(int* parent, int x) { if (parent[x] == x) return x; return merge(parent, parent[x]); } int connectedcomponents(int n, vector >& edges) { int parent[n]; for (int i = 0; i < n; i++) { parent[i] = i; } for (auto x : edges) { parent[merge(parent, x[0])] = merge(parent, x[1]); } int ans = 0; for (int i = 0; i < n; i++) { ans += (parent[i] == i); } for (int i = 0; i < n; i++) { parent[i] = merge(parent, parent[i]); } map > m; for (int i = 0; i < n; i++) { m[parent[i]].push_back(i); } for (auto it = m.begin(); it != m.end(); it++) { list l = it->second; for (auto x : l) { cout << x << "" ""; } cout << endl; } return ans; } int main() { int n = 5; vector e1 = { 0, 1 }; vector e2 = { 2, 1 }; vector e3 = { 3, 4 }; vector > e; e.push_back(e1); e.push_back(e2); e.push_back(e3); cout << ""Following are connected components:\n""; int a = connectedcomponents(n, e); return 0; }",linear,linear "// C++ program for the above approach #include using namespace std; int maxindex(int* dist, int n) { int mi = 0; for (int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi; } void selectKcities(int n, int weights[4][4], int k) { int* dist = new int[n]; vector centers; for (int i = 0; i < n; i++) { dist[i] = INT_MAX; } // index of city having the // maximum distance to it's // closest center int max = 0; for (int i = 0; i < k; i++) { centers.push_back(max); for (int j = 0; j < n; j++) { // updating the distance // of the cities to their // closest centers dist[j] = min(dist[j], weights[max][j]); } // updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer cout << endl << dist[max] << endl; // Printing the cities that // were chosen to be made // centers for (int i = 0; i < centers.size(); i++) { cout << centers[i] << "" ""; } cout << endl; } // Driver Code int main() { int n = 4; int weights[4][4] = { { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k); } // Contributed by Balu Nagar",constant,quadratic "// C++ program to find minimum time required to make all // oranges rotten #include #define R 3 #define C 5 using namespace std; // function to check whether a cell is valid / invalid bool isvalid(int i, int j) { return (i >= 0 && j >= 0 && i < R && j < C); } // structure for storing coordinates of the cell struct ele { int x, y; }; // Function to check whether the cell is delimiter // which is (-1, -1) bool isdelim(ele temp) { return (temp.x == -1 && temp.y == -1); } // Function to check whether there is still a fresh // orange remaining bool checkall(int arr[][C]) { for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (arr[i][j] == 1) return true; return false; } // This function finds if it is possible to rot all oranges // or not. If possible, then it returns minimum time // required to rot all, otherwise returns -1 int rotOranges(int arr[][C]) { // Create a queue of cells queue Q; ele temp; int ans = 0; // Store all the cells having rotten orange in first // time frame for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (arr[i][j] == 2) { temp.x = i; temp.y = j; Q.push(temp); } } } // Separate these rotten oranges from the oranges which // will rotten due the oranges in first time frame using // delimiter which is (-1, -1) temp.x = -1; temp.y = -1; Q.push(temp); // Process the grid while there are rotten oranges in // the Queue while (!Q.empty()) { // This flag is used to determine whether even a // single fresh orange gets rotten due to rotten // oranges in current time frame so we can increase // the count of the required time. bool flag = false; // Process all the rotten oranges in current time // frame. while (!isdelim(Q.front())) { temp = Q.front(); // Check right adjacent cell that if it can be // rotten if (isvalid(temp.x + 1, temp.y) && arr[temp.x + 1][temp.y] == 1) { // if this is the first orange to get // rotten, increase count and set the flag. if (!flag) ans++, flag = true; // Make the orange rotten arr[temp.x + 1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.push(temp); temp.x--; // Move back to current cell } // Check left adjacent cell that if it can be // rotten if (isvalid(temp.x - 1, temp.y) && arr[temp.x - 1][temp.y] == 1) { if (!flag) ans++, flag = true; arr[temp.x - 1][temp.y] = 2; temp.x--; Q.push(temp); // push this cell to Queue temp.x++; } // Check top adjacent cell that if it can be // rotten if (isvalid(temp.x, temp.y + 1) && arr[temp.x][temp.y + 1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y + 1] = 2; temp.y++; Q.push(temp); // Push this cell to Queue temp.y--; } // Check bottom adjacent cell if it can be // rotten if (isvalid(temp.x, temp.y - 1) && arr[temp.x][temp.y - 1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y - 1] = 2; temp.y--; Q.push(temp); // push this cell to Queue } Q.pop(); } // Pop the delimiter Q.pop(); // If oranges were rotten in current frame then // separate the rotten oranges using delimiter for // the next frame for processing. if (!Q.empty()) { temp.x = -1; temp.y = -1; Q.push(temp); } // If Queue was empty then no rotten oranges left to // process so exit } // Return -1 if all arranges could not rot, otherwise // return ans. return (checkall(arr)) ? -1 : ans; } // Driver program int main() { int arr[][C] = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; int ans = rotOranges(arr); if (ans == -1) cout << ""All oranges cannot rotn""; else cout << ""Time required for all oranges to rot => "" << ans << endl; return 0; }",quadratic,quadratic "// CPP14 program to find common contacts. #include using namespace std; // The class DSU will implement the Union Find class DSU { vector parent, size; public: // In the constructor, we assign the each index as its // own parent and size as the number of contacts // available for that index DSU(vector >& contacts) { for (int i = 0; i < contacts.size(); i++) { parent.push_back(i); size.push_back(contacts[i].size()); } } // Finds the set in which the element belongs. Path // compression is used to optimise time complexity int findSet(int v) { if (v == parent[v]) return v; return parent[v] = findSet(parent[v]); } // Unifies the sets a and b where, the element belonging // to the smaller set is merged to the one belonging to // the smaller set void unionSet(int a, int b, vector& person1, vector& person2) { if (size[a] > size[b]) { parent[b] = a; size[a] += size[b]; for (auto contact : person2) person1.push_back(contact); } else { parent[a] = b; size[b] += size[a]; for (auto contact : person1) person2.push_back(contact); } } }; // Driver Code int main() { vector > contacts = { { ""Gaurav"", ""gaurav@gmail.com"", ""gaurav@gfgQA.com"" }, { ""Lucky"", ""lucky@gmail.com"", ""+1234567"" }, { ""gaurav123"", ""+5412312"", ""gaurav123@skype.com"" }, { ""gaurav1993"", ""+5412312"", ""gaurav@gfgQA.com"" }, { ""raja"", ""+2231210"", ""raja@gfg.com"" }, { ""bahubali"", ""+878312"", ""raja"" } }; // Initializing the object of DSU class DSU dsu(contacts); // Will contain the mapping of a contact to all the // indices it is present within unordered_map > contactToIndex; for (int index = 0; index < contacts.size(); index++) { for (auto contact : contacts[index]) contactToIndex[contact].push_back(index); } // Unifies the sets of each contact if they are not // present in the same set for (auto contact : contactToIndex) { vector indices = contact.second; for (int i = 0; i < indices.size() - 1; i++) { int set1 = dsu.findSet(indices[i]), set2 = dsu.findSet(indices[i + 1]); if (set1 != set2) dsu.unionSet(set1, set2, contacts[set1], contacts[set2]); } } // Contains a map of all the distinct sets available // after union find has been completed unordered_map > unifiedSet; // All parents are mapped to the elements in the set for (int i = 0; i < contacts.size(); i++) { unifiedSet[dsu.findSet(i)].push_back(i); } // Printing out elements from distinct sets for (auto eachSet : unifiedSet) { for (auto element : eachSet.second) cout << element << "" ""; cout << endl; } return 0; }",linear,np "#include using namespace std; void print_sieve(int& x) { int i,temp,digit; bool check; for(i=0;i<=x;i++) { if(i<10) { cout< using namespace std; // Prints all jumping numbers smaller than or equal to x starting // with 'num'. It mainly does BFS starting from 'num'. void bfs(int x, int num) { // Create a queue and enqueue 'i' to it queue q; q.push(num); // Do BFS starting from i while (!q.empty()) { num = q.front(); q.pop(); if (num <= x) { cout << num << "" ""; int last_dig = num % 10; // If last digit is 0, append next digit only if (last_dig == 0) q.push((num * 10) + (last_dig + 1)); // If last digit is 9, append previous digit only else if (last_dig == 9) q.push((num * 10) + (last_dig - 1)); // If last digit is neither 0 nor 9, append both // previous and next digits else { q.push((num * 10) + (last_dig - 1)); q.push((num * 10) + (last_dig + 1)); } } } } // Prints all jumping numbers smaller than or equal to // a positive number x void printJumping(int x) { cout << 0 << "" ""; for (int i = 1; i <= 9 && i <= x; i++) bfs(x, i); } // Driver program int main() { int x = 40; printJumping(x); return 0; }",constant,linear "// C++ program for the above approach #include using namespace std; // Function to find and print pair bool chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { return 1; } } } return 0; } // Driver code int main() { int A[] = { 0, -1, 2, -3, 1 }; int x = -2; int size = sizeof(A) / sizeof(A[0]); if (chkPair(A, size, x)) { cout << ""Yes"" << endl; } else { cout << ""No"" << x << endl; } return 0; } // This code is contributed by Samim Hossain Mondal.",constant,quadratic "// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include using namespace std; // Function to check if array has 2 elements // whose sum is equal to the given value bool hasArrayTwoCandidates(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, A + arr_size); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[l] + A[r] > sum r--; } return 0; } /* Driver program to test above function */ int main() { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (hasArrayTwoCandidates(A, arr_size, n)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,nlogn "// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include using namespace std; bool binarySearch(int A[], int low, int high, int searchKey) { while (low <= high) { int m = low + (high - low) / 2; // Check if searchKey is present at mid if (A[m] == searchKey) return true; // If searchKey greater, ignore left half if (A[m] < searchKey) low = m + 1; // If searchKey is smaller, ignore right half else high = m - 1; } // if we reach here, then element was // not present return false; } bool checkTwoSum(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, A + arr_size); // Traversing all element in an array search for // searchKey for (int i = 0; i < arr_size - 1; i++) { int searchKey = sum - A[i]; // calling binarySearch function if (binarySearch(A, i + 1, arr_size - 1, searchKey) == true) { return true; } } return false; } /* Driver program to test above function */ int main() { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 14; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (checkTwoSum(A, arr_size, n)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,nlogn "// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include using namespace std; void printPairs(int arr[], int arr_size, int sum) { unordered_set s; for (int i = 0; i < arr_size; i++) { int temp = sum - arr[i]; if (s.find(temp) != s.end()) { cout << ""Yes"" << endl; return; } s.insert(arr[i]); } cout << ""No"" << endl; } /* Driver Code */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0; }",linear,linear "// Code in cpp to tell if there exists a pair in array whose // sum results in x. #include using namespace std; // Function to print pairs void printPairs(int a[], int n, int x) { int i; int rem[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if the element // is x, as numbers greater than x can't be used to get // a sum x. Updating the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i will // result to a sum of x. Once we get two // elements which add up to x , we print x and // break. cout << ""Yes\n""; break; } } // Once we reach middle of remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 elements // with remainder x/2, then we will have two // distinct elements which add up to x. if we // dont have more than 1 element, print ""No"". if (rem[x / 2] > 1) cout << ""Yes\n""; else cout << ""No\n""; } else { // When x is odd we continue the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) cout << ""Yes\n""; else cout << ""No\n""; } } } /* Driver Code */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// CPP program to find the minimum number of // operations required to make all elements // of array equal #include using namespace std; // function for min operation int minOperation (int arr[], int n) { // Insert all elements in hash. unordered_map hash; for (int i=0; i using namespace std; // Function to find maximum distance between equal elements int maxDistance(int arr[], int n) { // Used to store element to first index mapping unordered_map mp; // Traverse elements and find maximum distance between // same occurrences with the help of map. int max_dist = 0; for (int i=0; i #include using namespace std; // method to find maximum collinear point int maxPointOnSameLine(vector< pair > points) { int N = points.size(); if (N < 2) return N; int maxPoint = 0; int curMax, overlapPoints, verticalPoints; // here since we are using unordered_map // which is based on hash function //But by default we don't have hash function for pairs //so we'll use hash function defined in Boost library unordered_map, int,boost:: hash > > slopeMap; // looping for each point for (int i = 0; i < N; i++) { curMax = overlapPoints = verticalPoints = 0; // looping from i + 1 to ignore same pair again for (int j = i + 1; j < N; j++) { // If both point are equal then just // increase overlapPoint count if (points[i] == points[j]) overlapPoints++; // If x co-ordinate is same, then both // point are vertical to each other else if (points[i].first == points[j].first) verticalPoints++; else { int yDif = points[j].second - points[i].second; int xDif = points[j].first - points[i].first; int g = __gcd(xDif, yDif); // reducing the difference by their gcd yDif /= g; xDif /= g; // increasing the frequency of current slope // in map slopeMap[make_pair(yDif, xDif)]++; curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]); } curMax = max(curMax, verticalPoints); } // updating global maximum by current point's maximum maxPoint = max(maxPoint, curMax + overlapPoints + 1); // printf(""maximum collinear point // which contains current point // are : %d\n"", curMax + overlapPoints + 1); slopeMap.clear(); } return maxPoint; } // Driver code int main() { const int N = 6; int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2}, {3, 3}, {3, 4}}; vector< pair > points; for (int i = 0; i < N; i++) points.push_back(make_pair(arr[i][0], arr[i][1])); cout << maxPointOnSameLine(points) << endl; return 0; }",linear,quadratic "// C++ implementation of the // above approach #include using namespace std; // Function to find the Duplicates, // if duplicate occurs 2 times or // more than 2 times in array so, // it will print duplicate value // only once at output void findDuplicates(int arr[], int len) { // Initialize ifPresent as false bool ifPresent = false; // ArrayList to store the output vector al; for(int i = 0; i < len - 1; i++) { for(int j = i + 1; j < len; j++) { if (arr[i] == arr[j]) { // Checking if element is // present in the ArrayList // or not if present then break auto it = std::find(al.begin(), al.end(), arr[i]); if (it != al.end()) { break; } // If element is not present in the // ArrayList then add it to ArrayList // and make ifPresent at true else { al.push_back(arr[i]); ifPresent = true; } } } } // If duplicates is present // then print ArrayList if (ifPresent == true) { cout << ""["" << al[0] << "", ""; for(int i = 1; i < al.size() - 1; i++) { cout << al[i] << "", ""; } cout << al[al.size() - 1] << ""]""; } else { cout << ""No duplicates present in arrays""; } } // Driver code int main() { int arr[] = { 12, 11, 40, 12, 5, 6, 5, 12, 11 }; int n = sizeof(arr) / sizeof(arr[0]); findDuplicates(arr, n); return 0; } // This code is contributed by divyeshrabadiya07",linear,quadratic "// C++ program to find // duplicates in the given array #include using namespace std; // function to find and print duplicates void printDuplicates(int arr[], int n) { // unordered_map to store frequencies unordered_map freq; for (int i=0; i:: iterator itr; for (itr=freq.begin(); itr!=freq.end(); itr++) { // if frequency is more than 1 // print the element if (itr->second > 1) { cout << itr->first << "" ""; dup = true; } } // no duplicates present if (dup == false) cout << ""-1""; } // Driver program to test above int main() { int arr[] = {12, 11, 40, 12, 5, 6, 5, 12, 11}; int n = sizeof(arr) / sizeof(arr[0]); printDuplicates(arr, n); return 0; }",linear,linear "// C++ program to find top k elements in a stream #include using namespace std; // Function to print top k numbers void kTop(int a[], int n, int k) { // vector of size k+1 to store elements vector top(k + 1); // array to keep track of frequency unordered_map freq; // iterate till the end of stream for (int m = 0; m < n; m++) { // increase the frequency freq[a[m]]++; // store that element in top vector top[k] = a[m]; // search in top vector for same element auto it = find(top.begin(), top.end() - 1, a[m]); // iterate from the position of element to zero for (int i = distance(top.begin(), it) - 1; i >= 0; --i) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]) swap(top[i], top[i + 1]); // if frequency is same compare the elements // and swap if next element is high else if ((freq[top[i]] == freq[top[i + 1]]) && (top[i] > top[i + 1])) swap(top[i], top[i + 1]); else break; } // print top k elements for (int i = 0; i < k && top[i] != 0; ++i) cout << top[i] << ' '; } cout << endl; } // Driver program to test above function int main() { int k = 4; int arr[] = { 5, 2, 1, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); kTop(arr, n, k); return 0; }",linear,quadratic "// CPP program to find the most frequent element // in an array. #include using namespace std; int mostFrequent(int arr[], int n) { // Sort the array sort(arr, arr + n); // Find the max frequency using linear traversal int max_count = 1, res = arr[0], curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res; } // Driver program int main() { int arr[] = { 40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,nlogn "// CPP program to find the most frequent element // in an array. #include using namespace std; int mostFrequent(int arr[], int n) { // Insert all elements in hash. unordered_map hash; for (int i = 0; i < n; i++) hash[arr[i]]++; // find the max frequency int max_count = 0, res = -1; for (auto i : hash) { if (max_count < i.second) { res = i.first; max_count = i.second; } } return res; } // driver program int main() { int arr[] = {40,50,30,40,50,30,30 }; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0; }",linear,linear "#include using namespace std; int maxFreq(int *arr, int n) { //using moore's voting algorithm int res = 0; int count = 1; for(int i = 1; i < n; i++) { if(arr[i] == arr[res]) { count++; } else { count--; } if(count == 0) { res = i; count = 1; } } return arr[res]; } int main() { int arr[] = {40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); int freq = maxFreq(arr , n); int count = 0; for(int i = 0; i < n; i++) { if(arr[i] == freq) { count++; } } cout <<""Element "" << maxFreq(arr , n) << "" occurs "" << count << "" times"" << endl;; return 0; //This code is contributed by Ashish Kumar Shakya }",constant,linear "// C++ implementation to find first // element occurring k times #include using namespace std; // Function to find the first element // occurring k number of times int firstElement(int arr[], int n, int k) { // This loop is used for selection // of elements for (int i = 0; i < n; i++) { // Count how many time selected element // occurs int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) count++; } // Check, if it occurs k times or not if (count == k) return arr[i]; } return -1; } // Driver Code int main() { int arr[] = { 1, 7, 4, 3, 4, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << firstElement(arr, n, k); return 0; }",constant,quadratic "// C++ implementation to find first // element occurring k times #include using namespace std; // function to find the first element // occurring k number of times int firstElement(int arr[], int n, int k) { // unordered_map to count // occurrences of each element unordered_map count_map; for (int i=0; i using namespace std; // function to find the first element // occurring k number of times int firstElement(int arr[], int n, int k) { // unordered_map to count // occurrences of each element map count_map; for (int i = 0; i < n; i++) { count_map[arr[i]]++; } // count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.find(arr[i]) != count_map.end()) { if (count_map[arr[i]] == k) return arr[i]; } } // no element occurs k times return -1; } // Driver code int main() { int arr[] = { 1, 7, 4, 3, 4, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << (firstElement(arr, n, k)); return 0; } // This code is contributed by Rajput-Ji",linear,nlogn "// A C++ program to find all symmetric pairs in a given // array of pairs #include using namespace std; void findSymPairs(int arr[][2], int row) { // This loop for selection of one pair for (int i = 0; i < row; i++) { // This loop for searching of symmetric pair for (int j = i + 1; j < row; j++) { // Condition of symmetric pair if (arr[i][0] == arr[j][1] and arr[i][1] == arr[j][0]) { cout << ""("" << arr[i][0] << "", "" << arr[i][1] << "")"" << endl; } } } } // Driver method int main() { int arr[5][2]; arr[0][0] = 11; arr[0][1] = 20; arr[1][0] = 30; arr[1][1] = 40; arr[2][0] = 5; arr[2][1] = 10; arr[3][0] = 40; arr[3][1] = 30; arr[4][0] = 10; arr[4][1] = 5; cout << ""Following pairs have symmetric pairs\n""; findSymPairs(arr, 5); } // This is contributed by Arpit Jain",constant,quadratic "#include using namespace std; // A C++ program to find all symmetric pairs in a given array of pairs // Print all pairs that have a symmetric counterpart void findSymPairs(int arr[][2], int row) { // Creates an empty hashMap hM unordered_map hM; // Traverse through the given array for (int i = 0; i < row; i++) { // First and second elements of current pair int first = arr[i][0]; int sec = arr[i][1]; // If found and value in hash matches with first // element of this pair, we found symmetry if (hM.find(sec) != hM.end() && hM[sec] == first) cout << ""("" << sec << "", "" << first << "")"" < using namespace std; int findRepeating(int arr[], int N) { for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (arr[i] == arr[j]) return arr[i]; } } } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; } // This code is added by Arpit Jain",constant,quadratic "// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { sort(arr, arr + N); // sort array for (int i = 0; i < N; i++) { // compare array element with its index if (arr[i] != i + 1) { return arr[i]; } } return -1; } // driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; } // this code is contributed by devendra solunke",constant,nlogn "// C++ program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { unordered_set s; for (int i = 0; i < N; i++) { if (s.find(arr[i]) != s.end()) return arr[i]; s.insert(arr[i]); } // If input is correct, we should // never reach here return -1; } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }",linear,linear "// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { // Find array sum and subtract sum // first N-1 natural numbers from it // to find the result. return accumulate(arr, arr + N, 0) - ((N - 1) * N / 2); } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }",constant,linear "// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include using namespace std; int findRepeating(int arr[], int N) { // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (N-1) ^ arr[0] ^ // arr[1] ^ .... arr[N-1] int res = 0; for (int i = 0; i < N - 1; i++) res = res ^ (i + 1) ^ arr[i]; res = res ^ arr[N - 1]; return res; } // Driver code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }",constant,linear "// CPP program to find the only // repeating element in an array // where elements are from 1 to N-1. #include using namespace std; // Function to find repeated element int findRepeating(int arr[], int N) { int missingElement = 0; // indexing based for (int i = 0; i < N; i++) { int element = arr[abs(arr[i])]; if (element < 0) { missingElement = arr[i]; break; } arr[abs(arr[i])] = -arr[abs(arr[i])]; } return abs(missingElement); } // Driver code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }",constant,linear "#include using namespace std; int findDuplicate(vector& nums) { int slow = nums[0]; int fast = nums[0]; do { slow = nums[slow]; fast = nums[nums[fast]]; } while (slow != fast); fast = nums[0]; while (slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } // Driver code int main() { vector v{ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; // Function call int ans = findDuplicate(v); cout << ans << endl; return 0; }",constant,linear "// C++ program to find one of the repeating // elements in a read only array #include using namespace std; // Function to find one of the repeating // elements int findRepeatingNumber(const int arr[], int n) { for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) count++; } if (count > 1) return arr[i]; } // If no repeating element exists return -1; } // Driver Code int main() { // Read only array const int arr[] = { 1, 1, 2, 3, 5, 4 }; int n = 5; cout << ""One of the numbers repeated in"" "" the array is: "" << findRepeatingNumber(arr, n) << endl; }",constant,quadratic "// C++ Program to Find the top three repeated numbers #include using namespace std; /* Function to print top three repeated numbers */ void top3Repeated(int arr[], int n) { // There should be atleast two elements if (n < 3) { cout << ""Invalid Input""; return; } // Count Frequency of each element unordered_map fre; for (int i = 0; i < n; i++) fre[arr[i]]++; // Initialize first value of each variable // of Pair type is INT_MIN pair x, y, z; x.first = y.first = z.first = INT_MIN; for (auto curr : fre) { // If frequency of current element // is not zero and greater than // frequency of first largest element if (curr.second > x.first) { // Update second and third largest z = y; y = x; // Modify values of x Number x.first = curr.second; x.second = curr.first; } // If frequency of current element is // not zero and frequency of current // element is less than frequency of // first largest element, but greater // than y element else if (curr.second > y.first) { // Modify values of third largest z = y; // Modify values of second largest y.first = curr.second; y.second = curr.first; } // If frequency of current element // is not zero and frequency of // current element is less than // frequency of first element and // second largest, but greater than // third largest. else if (curr.second > z.first) { // Modify values of z Number z.first = curr.second; z.second = curr.first; } } cout << ""Three largest elements are "" << x.second << "" "" << y.second << "" "" << z.second; } // Driver's Code int main() { int arr[] = { 3, 4, 2, 3, 16, 3, 15, 16, 15, 15, 16, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); top3Repeated(arr, n); return 0; }",linear,linear "// A simple C++ program to group multiple occurrences of individual // array elements #include using namespace std; // A simple method to group all occurrences of individual elements void groupElements(int arr[], int n) { // Initialize all elements as not visited bool *visited = new bool[n]; for (int i=0; i using namespace std; // C++ program to group multiple // occurrences of individual array elements // A hashing based method to group // all occurrences of individual elements void orderedGroup(vector&arr){ // Creates an empty hashmap maphM; // Traverse the array elements, and store // count for every element in HashMap for(int i=0;iarr = {10, 5, 3, 10, 10, 4, 1, 3}; orderedGroup(arr); } // This code is contributed by shinjanpatra",linear,linear "// A Simple C++ program to check if two sets are disjoint #include using namespace std; // Returns true if set1[] and set2[] are disjoint, else false bool areDisjoint(int set1[], int set2[], int m, int n) { // Take every element of set1[] and search it in set2 for (int i=0; i using namespace std; // This function prints all distinct elements bool areDisjoint(int set1[], int set2[], int n1, int n2) { // Creates an empty hashset set myset; // Traverse the first set and store its elements in hash for (int i = 0; i < n1; i++) myset.insert(set1[i]); // Traverse the second set and check if any element of it // is already in hash or not. for (int i = 0; i < n2; i++) if (myset.find(set2[i]) != myset.end()) return false; return true; } // Driver method to test above method int main() { int set1[] = {10, 5, 3, 4, 6}; int set2[] = {8, 7, 9, 3}; int n1 = sizeof(set1) / sizeof(set1[0]); int n2 = sizeof(set2) / sizeof(set2[0]); if (areDisjoint(set1, set2, n1, n2)) cout << ""Yes""; else cout << ""No""; } //This article is contributed by Chhavi",linear,linear "// CPP program to find Non-overlapping sum #include using namespace std; // function for calculating // Non-overlapping sum of two array int findSum(int A[], int B[], int n) { // Insert elements of both arrays unordered_map hash; for (int i = 0; i < n; i++) { hash[A[i]]++; hash[B[i]]++; } // calculate non-overlapped sum int sum = 0; for (auto x: hash) if (x.second == 1) sum += x.first; return sum; } // driver code int main() { int A[] = { 5, 4, 9, 2, 3 }; int B[] = { 2, 8, 7, 6, 3 }; // size of array int n = sizeof(A) / sizeof(A[0]); // function call cout << findSum(A, B, n); return 0; }",linear,linear "// C++ simple program to // find elements which are // not present in second array #include using namespace std; // Function for finding // elements which are there // in a[] but not in b[]. void findMissing(int a[], int b[], int n, int m) { for (int i = 0; i < n; i++) { int j; for (j = 0; j < m; j++) if (a[i] == b[j]) break; if (j == m) cout << a[i] << "" ""; } } // Driver code int main() { int a[] = { 1, 2, 6, 3, 4, 5 }; int b[] = { 2, 4, 3, 1, 0 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[1]); findMissing(a, b, n, m); return 0; }",constant,quadratic "// C++ efficient program to // find elements which are not // present in second array #include using namespace std; // Function for finding // elements which are there // in a[] but not in b[]. void findMissing(int a[], int b[], int n, int m) { // Store all elements of // second array in a hash table unordered_set s; for (int i = 0; i < m; i++) s.insert(b[i]); // Print all elements of // first array that are not // present in hash table for (int i = 0; i < n; i++) if (s.find(a[i]) == s.end()) cout << a[i] << "" ""; } // Driver code int main() { int a[] = { 1, 2, 6, 3, 4, 5 }; int b[] = { 2, 4, 3, 1, 0 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[1]); findMissing(a, b, n, m); return 0; }",linear,linear "// C++ program to find given two array // are equal or not #include using namespace std; // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. bool areEqual(int arr1[], int arr2[], int N, int M) { // If lengths of array are not equal means // array are not equal if (N != M) return false; // Sort both arrays sort(arr1, arr1 + N); sort(arr2, arr2 + M); // Linearly compare elements for (int i = 0; i < N; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true; } // Driver's Code int main() { int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; int N = sizeof(arr1) / sizeof(int); int M = sizeof(arr2) / sizeof(int); // Function call if (areEqual(arr1, arr2, N, M)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,nlogn "// C++ program for the above approach #include using namespace std; // Returns true if arr1[0..N-1] and arr2[0..M-1] // contain same elements. bool areEqual(int arr1[], int arr2[], int N, int M) { // If lengths of arrays are not equal if (N != M) return false; // Store arr1[] elements and their counts in // hash map unordered_map mp; for (int i = 0; i < N; i++) mp[arr1[i]]++; // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (int i = 0; i < N; i++) { // If there is an element in arr2[], but // not in arr1[] if (mp.find(arr2[i]) == mp.end()) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (mp[arr2[i]] == 0) return false; // decrease the count of arr2 elements in the // unordered map mp[arr2[i]]--; } return true; } // Driver's Code int main() { int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; int N = sizeof(arr1) / sizeof(int); int M = sizeof(arr2) / sizeof(int); // Function call if (areEqual(arr1, arr2, N, M)) cout << ""Yes""; else cout << ""No""; return 0; }",linear,linear "// C++ code to find maximum shortest distance // from endpoints #include using namespace std; // function to find maximum shortest distance int find_maximum(int a[], int n, int k) { // stores the shortest distance of every // element in original array. unordered_map b; for (int i = 0; i < n; i++) { int x = a[i]; // shortest distance from ends int d = min(1 + i, n - i); if (b.find(x) == b.end()) b[x] = d; else /* if duplicates are found, b[x] is replaced with minimum of the previous and current position's shortest distance*/ b[x] = min(d, b[x]); } int ans = INT_MAX; for (int i = 0; i < n; i++) { int x = a[i]; // similar elements ignore them // cause we need distinct elements if (x != k - x && b.find(k - x) != b.end()) ans = min(max(b[x], b[k - x]), ans); } return ans; } // driver code int main() { int a[] = { 3, 5, 8, 6, 7 }; int K = 11; int n = sizeof(a) / sizeof(a[0]); cout << find_maximum(a, n, K) << endl; return 0; }",linear,linear "// C++ program to find the k-th missing element // in a given sequence #include using namespace std; // Returns k-th missing element. It returns -1 if // no k is more than number of missing elements. int find(int a[], int b[], int k, int n1, int n2) { // Insert all elements of givens sequence b[]. unordered_set s; for (int i = 0; i < n2; i++) s.insert(b[i]); // Traverse through increasing sequence and // keep track of count of missing numbers. int missing = 0; for (int i = 0; i < n1; i++) { if (s.find(a[i]) == s.end()) missing++; if (missing == k) return a[i]; } return -1; } // driver program to test the above function int main() { int a[] = { 0, 2, 4, 6, 8, 10, 12, 14, 15 }; int b[] = { 4, 10, 6, 8, 12 }; int n1 = sizeof(a) / sizeof(a[0]); int n2 = sizeof(b) / sizeof(b[0]); int k = 3; cout << find(a, b, k, n1, n2); return 0; }",quadratic,linear "// C++ program to find a pair with product // in given array. #include using namespace std; // Function to find greatest number that us int findGreatest( int arr[] , int n) { int result = -1; for (int i = 0; i < n ; i++) for (int j = 0; j < n-1; j++) for (int k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = max(result, arr[i]); return result; } // Driver code int main() { // Your C++ Code int arr[] = {10, 3, 5, 30, 35}; int n = sizeof(arr)/sizeof(arr[0]); cout << findGreatest(arr, n); return 0; }",constant,cubic "// C++ program to find the largest product number #include using namespace std; // Function to find greatest number int findGreatest(int arr[], int n) { // Store occurrences of all elements in hash // array unordered_map m; for (int i = 0; i < n; i++) m[arr[i]]++; // Sort the array and traverse all elements from // end. sort(arr, arr + n); for (int i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (int j = 0; j < i && arr[j] <= sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && result!=arr[i] && m[result] > 0) return arr[i]; // To handle the case like arr[i] = 4 and // arr[j] = 2 else if (result == arr[j] && m[result] > 1) return arr[i]; } } } return -1; } // Drivers code int main() { int arr[] = {10, 3, 5, 30, 35}; int n = sizeof(arr) / sizeof(arr[0]); cout << findGreatest(arr, n); return 0; }",linear,nlogn "// A sorting based solution to find the // minimum number of subsets of a set // such that every subset contains distinct // elements. #include using namespace std; // Function to count subsets such that all // subsets have distinct elements. int subset(int ar[], int n) { // Take input and initialize res = 0 int res = 0; // Sort the array sort(ar, ar + n); // Traverse the input array and // find maximum frequency for (int i = 0; i < n; i++) { int count = 1; // For each number find its repetition / frequency for (; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = max(res, count); } return res; } // Driver code int main() { int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subset(arr, n); return 0; }",constant,quadratic "// A hashing based solution to find the // minimum number of subsets of a set // such that every subset contains distinct // elements. #include using namespace std; // Function to count subsets such that all // subsets have distinct elements. int subset(int arr[], int n) { // Traverse the input array and // store frequencies of elements unordered_map mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Find the maximum value in map. int res = 0; for (auto x : mp) res = max(res, x.second); return res; } // Driver code int main() { int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subset(arr, n); return 0; }",linear,linear "// CPP program to find minimum element // to remove so no common element // exist in both array #include using namespace std; // To find no elements to remove // so no common element exist int minRemove(int a[], int b[], int n, int m) { // To store count of array element unordered_map countA, countB; // Count elements of a for (int i = 0; i < n; i++) countA[a[i]]++; // Count elements of b for (int i = 0; i < m; i++) countB[b[i]]++; // Traverse through all common element, and // pick minimum occurrence from two arrays int res = 0; for (auto x : countA) if (countB.find(x.first) != countB.end()) res += min(x.second, countB[x.first]); // To return count of minimum elements return res; } // Driver program to test minRemove() int main() { int a[] = { 1, 2, 3, 4 }; int b[] = { 2, 3, 4, 5, 8 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); cout << minRemove(a, b, n, m); return 0; }",linear,linear "// C++ implementation to count items common to both // the lists but with different prices #include using namespace std; // details of an item struct item { string name; int price; }; // function to count items common to both // the lists but with different prices int countItems(item list1[], int m, item list2[], int n) { int count = 0; // for each item of 'list1' check if it is in 'list2' // but with a different price for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if ((list1[i].name.compare(list2[j].name) == 0) && (list1[i].price != list2[j].price)) count++; // required count of items return count; } // Driver program to test above int main() { item list1[] = {{""apple"", 60}, {""bread"", 20}, {""wheat"", 50}, {""oil"", 30}}; item list2[] = {{""milk"", 20}, {""bread"", 15}, {""wheat"", 40}, {""apple"", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << ""Count = "" << countItems(list1, m, list2, n); return 0; }",constant,quadratic "// C++ implementation to count // items common to both the lists // but with different prices #include using namespace std; // Details of an item struct item { string name; int price; }; // comparator function // used for sorting bool compare(struct item a, struct item b) { return (a.name.compare (b.name) <= 0); } // Function to search 'str' // in 'list2[]'. If it exists then // price associated with 'str' // in 'list2[]' is being returned // else -1 is returned. Here binary // search technique is being applied // for searching int binary_search(item list2[], int low, int high, string str) { while (low <= high) { int mid = (low + high) / 2; // if true the item 'str' // is in 'list2' if (list2[mid].name.compare(str) == 0) return list2[mid].price; else if (list2[mid].name.compare(str) < 0) low = mid + 1; else high = mid - 1; } // item 'str' is not in 'list2' return -1; } // Function to count items common to both // the lists but with different prices int countItems(item list1[], int m, item list2[], int n) { // sort 'list2' in alphabetical // order of items name sort(list2, list2 + n, compare); // initial count int count = 0; for (int i = 0; i < m; i++) { // get the price of item 'list1[i]' // from 'list2' if item in not // present in second list then // -1 is being obtained int r = binary_search(list2, 0, n - 1, list1[i].name); // if item is present in list2 // with a different price if ((r != -1) && (r != list1[i].price)) count++; } // Required count of items return count; } // Driver code int main() { item list1[] = {{""apple"", 60}, {""bread"", 20}, {""wheat"", 50}, {""oil"", 30}}; item list2[] = {{""milk"", 20}, {""bread"", 15}, {""wheat"", 40}, {""apple"", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << ""Count = "" << countItems(list1, m, list2, n); return 0; }",constant,nlogn "// C++ implementation to count items common to both // the lists but with different prices #include using namespace std; // details of an item struct item { string name; int price; }; // function to count items common to both // the lists but with different prices int countItems(item list1[], int m, item list2[], int n) { // 'um' implemented as hash table that contains // item name as the key and price as the value // associated with the key unordered_map um; int count = 0; // insert elements of 'list1' in 'um' for (int i = 0; i < m; i++) um[list1[i].name] = list1[i].price; // for each element of 'list2' check if it is // present in 'um' with a different price // value for (int i = 0; i < n; i++) if ((um.find(list2[i].name) != um.end()) && (um[list2[i].name] != list2[i].price)) count++; // required count of items return count; } // Driver program to test above int main() { item list1[] = {{""apple"", 60}, {""bread"", 20}, {""wheat"", 50}, {""oil"", 30}}; item list2[] = {{""milk"", 20}, {""bread"", 15}, {""wheat"", 40}, {""apple"", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << ""Count = "" << countItems(list1, m, list2, n); return 0; }",linear,linear "#include using namespace std; // Function to print common strings with minimum index sum void find(vector list1, vector list2) { vector res; // resultant list int max_possible_sum = list1.size() + list2.size() - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common strings in resultant list if (i < list1.size() && (sum - i) < list2.size() && list1[i] == list2[sum - i]) res.push_back(list1[i]); // if common string found then break as we are // considering index sums in increasing order. if (res.size() > 0) break; } // print the resultant list for (int i = 0; i < res.size(); i++) cout << res[i] << "" ""; } // Driver code int main() { // Creating list1 vector list1; list1.push_back(""GeeksforGeeks""); list1.push_back(""Udemy""); list1.push_back(""Coursera""); list1.push_back(""edX""); // Creating list2 vector list2; list2.push_back(""Codecademy""); list2.push_back(""Khan Academy""); list2.push_back(""GeeksforGeeks""); find(list1, list2); return 0; }",quadratic,linear "// Hashing based C++ program to find common elements // with minimum index sum. #include using namespace std; // Function to print common strings with minimum index sum void find(vector list1, vector list2) { // mapping strings to their indices unordered_map map; for (int i = 0; i < list1.size(); i++) map[list1[i]] = i; vector res; // resultant list int minsum = INT_MAX; for (int j = 0; j < list2.size(); j++) { if (map.count(list2[j])) { // If current sum is smaller than minsum int sum = j + map[list2[j]]; if (sum < minsum) { minsum = sum; res.clear(); res.push_back(list2[j]); } // if index sum is same then put this // string in resultant list as well else if (sum == minsum) res.push_back(list2[j]); } } // Print result for (int i = 0; i < res.size(); i++) cout << res[i] << "" ""; } // Driver code int main() { // Creating list1 vector list1; list1.push_back(""GeeksforGeeks""); list1.push_back(""Udemy""); list1.push_back(""Coursera""); list1.push_back(""edX""); // Creating list2 vector list2; list2.push_back(""Codecademy""); list2.push_back(""Khan Academy""); list2.push_back(""GeeksforGeeks""); find(list1, list2); return 0; }",quadratic,linear "// C++ program to find a pair with given sum such that // every element of pair is in different rows. #include using namespace std; const int MAX = 100; // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pair void pairSum(int mat[][MAX], int n, int sum) { // First sort all the rows in ascending order for (int i=0; i=0) { if ((mat[i][left] + mat[j][right]) == sum) { cout << ""("" << mat[i][left] << "", ""<< mat[j][right] << ""), ""; left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } } } // Driver program to run the case int main() { int n = 4, sum = 11; int mat[][MAX] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); return 0; }",constant,cubic "// A Program to prints common element in all // rows of matrix #include using namespace std; // Specify number of rows and columns #define M 4 #define N 5 // prints common element in all rows of matrix void printCommonElements(int mat[M][N]) { unordered_map mp; // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) mp[mat[0][j]] = 1; // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp[mat[i][j]] == i) { // we increment count of the element // in map by 1 mp[mat[i][j]] = i + 1; // If this is last row if (i==M-1 && mp[mat[i][j]]==M) cout << mat[i][j] << "" ""; } } } } // driver program to test above function int main() { int mat[M][N] = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; printCommonElements(mat); return 0; }",linear,quadratic "// C++ program to find all permutations of a given row #include #define MAX 100 using namespace std; // Function to find all permuted rows of a given row r void permutatedRows(int mat[][MAX], int m, int n, int r) { // Creating an empty set unordered_set s; // Count frequencies of elements in given row r for (int j=0; j using namespace std; void makePermutation(int a[], int n) { // Store counts of all elements. unordered_map count; for (int i = 0; i < n; i++) count[a[i]]++; int next_missing = 1; for (int i = 0; i < n; i++) { if (count[a[i]] != 1 || a[i] > n || a[i] < 1) { count[a[i]]--; // Find next missing element to put // in place of current element. while (count.find(next_missing) != count.end()) next_missing++; // Replace with next missing and insert the // missing element in hash. a[i] = next_missing; count[next_missing] = 1; } } } // Driver Code int main() { int A[] = { 2, 2, 3, 3 }; int n = sizeof(A) / sizeof(A[0]); makePermutation(A, n); for (int i = 0; i < n; i++) cout << A[i] << "" ""; return 0; }",linear,nlogn "// C++ implementation of simple method to find count of // pairs with given sum. #include using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int sum) { int count = 0; // Initialize result // Consider all possible pairs and check their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) count++; return count; } // Driver function to test the above function int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << ""Count of pairs is "" << getPairsCount(arr, n, sum); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,quadratic "// C++ code to implement the approach #include using namespace std; // Function to find the count of pairs int getPairsCount(int arr[], int n, int k) { sort(arr, arr + n); int x = 0, c = 0, y, z; for (int i = 0; i < n - 1; i++) { x = k - arr[i]; // Lower bound from i+1 int y = lower_bound(arr + i + 1, arr + n, x) - arr; // Upper bound from i+1 int z = upper_bound(arr + i + 1, arr + n, x) - arr; c = c + z - y; } return c; } // Driver code int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 6; // Function call cout << ""Count of pairs is "" << getPairsCount(arr, n, k); return 0; }",constant,nlogn "// C++ implementation of simple method to find count of // pairs with given sum. #include using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int sum) { unordered_map m; // Store counts of all elements in map m for (int i = 0; i < n; i++) m[arr[i]]++; int twice_count = 0; // iterate through each element and increment the // count (Notice that every pair is counted twice) for (int i = 0; i < n; i++) { twice_count += m[sum - arr[i]]; // if (arr[i], arr[i]) pair satisfies the condition, // then we need to ensure that the count is // decreased by one such that the (arr[i], arr[i]) // pair is not considered if (sum - arr[i] == arr[i]) twice_count--; } // return the half of twice_count return twice_count / 2; } // Driver function to test the above function int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << ""Count of pairs is "" << getPairsCount(arr, n, sum); return 0; }",linear,linear "// C++ implementation of simple method to // find count of pairs with given sum. #include using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int k) { unordered_map m; int count = 0; for (int i = 0; i < n; i++) { if (m.find(k - arr[i]) != m.end()) { count += m[k - arr[i]]; } m[arr[i]]++; } return count; } // Driver code int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; // Function Call cout << ""Count of pairs is "" << getPairsCount(arr, n, sum); return 0; }",linear,linear "// C++ implementation to count pairs from both linked // lists whose sum is equal to a given value #include using namespace std; /* A Linked list node */ struct Node { int data; struct Node* next; }; // function to insert a node at the // beginning of the linked list void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // function to count all pairs from both the linked lists // whose sum is equal to a given value int countPairs(struct Node* head1, struct Node* head2, int x) { int count = 0; struct Node *p1, *p2; // traverse the 1st linked list for (p1 = head1; p1 != NULL; p1 = p1->next) // for each node of 1st list // traverse the 2nd list for (p2 = head2; p2 != NULL; p2 = p2->next) // if sum of pair is equal to 'x' // increment count if ((p1->data + p2->data) == x) count++; // required count of pairs return count; } // Driver program to test above int main() { struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 3->1->5->7 push(&head1, 7); push(&head1, 5); push(&head1, 1); push(&head1, 3); // create linked list2 8->2->5->3 push(&head2, 3); push(&head2, 5); push(&head2, 2); push(&head2, 8); int x = 10; cout << ""Count = "" << countPairs(head1, head2, x); return 0; }",constant,quadratic "// C++ implementation to count pairs from both linked // lists whose sum is equal to a given value #include using namespace std; /* A Linked list node */ struct Node { int data; struct Node* next; }; // function to insert a node at the // beginning of the linked list void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // function to count all pairs from both the linked // lists whose sum is equal to a given value int countPairs(struct Node* head1, struct Node* head2, int x) { int count = 0; // sort head1 in ascending order and // head2 in descending order // sort (head1), sort (head2) // For simplicity both lists are considered to be // sorted in the respective orders // traverse both the lists from left to right while (head1 != NULL && head2 != NULL) { // if this sum is equal to 'x', then move both // the lists to next nodes and increment 'count' if ((head1->data + head2->data) == x) { head1 = head1->next; head2 = head2->next; count++; } // if this sum is greater than x, then // move head2 to next node else if ((head1->data + head2->data) > x) head2 = head2->next; // else move head1 to next node else head1 = head1->next; } // required count of pairs return count; } // Driver program to test above int main() { struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 1->3->5->7 // assumed to be in ascending order push(&head1, 7); push(&head1, 5); push(&head1, 3); push(&head1, 1); // create linked list2 8->5->3->2 // assumed to be in descending order push(&head2, 2); push(&head2, 3); push(&head2, 5); push(&head2, 8); int x = 10; cout << ""Count = "" << countPairs(head1, head2, x); return 0; }",constant,nlogn "// C++ implementation to count pairs from both linked // lists whose sum is equal to a given value #include using namespace std; /* A Linked list node */ struct Node { int data; struct Node* next; }; // function to insert a node at the // beginning of the linked list void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // function to count all pairs from both the linked // lists whose sum is equal to a given value int countPairs(struct Node* head1, struct Node* head2, int x) { int count = 0; unordered_set us; // insert all the elements of 1st list // in the hash table(unordered_set 'us') while (head1 != NULL) { us.insert(head1->data); // move to next node head1 = head1->next; } // for each element of 2nd list while (head2 != NULL) { // find (x - head2->data) in 'us' if (us.find(x - head2->data) != us.end()) count++; // move to next node head2 = head2->next; } // required count of pairs return count; } // Driver program to test above int main() { struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 3->1->5->7 push(&head1, 7); push(&head1, 5); push(&head1, 1); push(&head1, 3); // create linked list2 8->2->5->3 push(&head2, 3); push(&head2, 5); push(&head2, 2); push(&head2, 8); int x = 10; cout << ""Count = "" << countPairs(head1, head2, x); return 0; }",linear,linear " // C++ implementation to count quadruples from four sorted arrays // whose sum is equal to a given value x #include using namespace std; // function to count all quadruples from // four sorted arrays whose sum is equal // to a given value x int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // generate all possible quadruples from // the four sorted arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) count++; // required count of quadruples return count; } // Driver program to test above int main() { // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << ""Count = "" << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0; }",constant,np "// C++ implementation to count quadruples from // four sorted arrays whose sum is equal to a // given value x #include using namespace std; // find the 'value' in the given array 'arr[]' // binary search technique is applied bool isPresent(int arr[], int low, int high, int value) { while (low <= high) { int mid = (low + high) / 2; // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false; } // function to count all quadruples from four // sorted arrays whose sum is equal to a given value x int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // generate all triplets from the 1st three arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated int T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n, x - T)) // increment count count++; } // required count of quadruples return count; } // Driver program to test above int main() { // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << ""Count = "" << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0; }",constant,cubic "// C++ implementation to count quadruples from // four sorted arrays whose sum is equal to a // given value x #include using namespace std; // count pairs from the two sorted array whose sum // is equal to the given 'value' int countPairs(int arr1[], int arr2[], int n, int value) { int count = 0; int l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & amp; &r >= 0) { int sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++, r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count; } // function to count all quadruples from four sorted arrays // whose sum is equal to a given value x int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // generate all pairs from arr1[] and arr2[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated int p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count; } // Driver program to test above int main() { // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << ""Count = "" << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0; }",constant,cubic "// C++ implementation to count quadruples from // four sorted arrays whose sum is equal to a // given value x #include using namespace std; // function to count all quadruples from four sorted // arrays whose sum is equal to a given value x int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // unordered_map 'um' implemented as hash table // for tuples unordered_map um; // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) um[arr1[i] + arr2[j]]++; // generate pair from arr3[] and arr4[] for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated int p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (um.find(x - p_sum) != um.end()) count += um[x - p_sum]; } // required count of quadruples return count; } // Driver program to test above int main() { // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << ""Count = "" << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0; }",quadratic,quadratic "// C++ program for the above approach #include using namespace std; int main() { int arr[] = {10, 2, -2, -20, 10}; int k = -10; int n = sizeof(arr) / sizeof(arr[0]); int res = 0; // Calculate all subarrays for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // Calculate required sum sum += arr[j]; // Check if sum is equal to required sum if (sum == k) res++; } } cout << (res) << endl; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,quadratic "// C++ program to find number of subarrays with sum exactly // equal to k. #include using namespace std; // Function to find number of subarrays with sum exactly // equal to k. int findSubarraySum(int arr[], int n, int sum) { // STL map to store number of subarrays starting from // index zero having particular value of sum. unordered_map prevSum; int res = 0; // Sum of elements so far. int currSum = 0; for (int i = 0; i < n; i++) { // Add current element to sum so far. currSum += arr[i]; // If currsum is equal to desired sum, then a new // subarray is found. So increase count of // subarrays. if (currSum == sum) res++; // currsum exceeds given sum by currsum - sum. Find // number of subarrays having this sum and exclude // those subarrays from currsum by increasing count // by same amount. if (prevSum.find(currSum - sum) != prevSum.end()) res += (prevSum[currSum - sum]); // Add currsum value to count of different values of // sum. prevSum[currSum]++; } return res; } int main() { int arr[] = { 10, 2, -2, -20, 10 }; int sum = -10; int n = sizeof(arr) / sizeof(arr[0]); cout << findSubarraySum(arr, n, sum); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// C++ program to find all pairs in both arrays // whose sum is equal to given value x #include using namespace std; // Function to print all pairs in both arrays // whose sum is equal to given value x void findPairs(int arr1[], int arr2[], int n, int m, int x) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) cout << arr1[i] << "" "" << arr2[j] << endl; } // Driver code int main() { int arr1[] = { 1, 2, 3, 7, 5, 4 }; int arr2[] = { 0, 7, 4, 3, 2, 1 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); int x = 8; findPairs(arr1, arr2, n, m, x); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,quadratic "// C++ program to find all pair in both arrays // whose sum is equal to given value x #include using namespace std; // Function to find all pairs in both arrays // whose sum is equal to given value x void findPairs(int arr1[], int arr2[], int n, int m, int x) { // Insert all elements of first array in a hash unordered_set s; for (int i = 0; i < n; i++) s.insert(arr1[i]); // Subtract sum from second array elements one // by one and check it's present in array first // or not for (int j = 0; j < m; j++) if (s.find(x - arr2[j]) != s.end()) cout << x - arr2[j] << "" "" << arr2[j] << endl; } // Driver code int main() { int arr1[] = { 1, 0, -4, 7, 6, 4 }; int arr2[] = { 0, 2, 4, -3, 2, 1 }; int x = 8; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); findPairs(arr1, arr2, n, m, x); return 0; }",linear,linear "#include using namespace std; // Function to print the cumulative frequency according to // the order given void countFreq(int a[], int n) { // Declaring a map so values get inserted in a sorted // manner map m; // Inserting values into the map for (int i = 0; i < n; i++) { m[a[i]]++; } // Variable to store the count of previous number // cumulative frequency int cumul = 0; for (auto v : m) { cout << v.first << "" "" << v.second + cumul << endl; cumul += v.second; } } int main() { int arr[] = { 1, 3, 2, 4, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0; } // This code is contributed by Vinayak Pareek (Kargil)",linear,nlogn "// C++ program to print the cumulative frequency // according to the order given #include using namespace std; // Function to print the cumulative frequency // according to the order given void countFreq(int a[], int n) { // Insert elements and their // frequencies in hash map. unordered_map hm; for (int i=0; i"" << cumul << endl; } // mark the hash 0 // as the element's cumulative frequency // has been printed hm[a[i]]=0; } } // Driver Code int main() { int a[] = {1, 3, 2, 4, 2, 1}; int n = sizeof(a)/sizeof(a[0]); countFreq(a, n); return 0; }",linear,linear "// CPP program for the above approach #include using namespace std; // Used for sorting by frequency. And if frequency is same, // then by appearance bool sortByVal(const pair& a, const pair& b) { // If frequency is same then sort by index if (a.second == b.second) return a.first < b.first; return a.second > b.second; } // function to sort elements by frequency vectorsortByFreq(int a[], int n) { vectorres; unordered_map m; vector > v; for (int i = 0; i < n; ++i) { // Map m is used to keep track of count // of elements in array m[a[i]]++; } // Copy map to vector copy(m.begin(), m.end(), back_inserter(v)); // Sort the element of array by frequency sort(v.begin(), v.end(), sortByVal); for (int i = 0; i < v.size(); ++i) while(v[i].second--) { res.push_back(v[i].first); } return res; } // Driver program int main() { int a[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(a) / sizeof(a[0]); vectorres; res = sortByFreq(a, n); for(int i = 0;i < res.size(); i++) cout< using namespace std; // Function to find pair whose sum exists in arr[] void findPair(int arr[], int n) { bool found = false; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = 0; k < n; k++) { if (arr[i] + arr[j] == arr[k]) { cout << arr[i] << "" "" << arr[j] << endl; found = true; } } } } if (found == false) cout << ""Not exist"" << endl; } // Driven code int main() { int arr[] = { 10, 4, 8, 13, 5 }; int n = sizeof(arr) / sizeof(arr[0]); findPair(arr, n); return 0; }",constant,cubic "// C++ program to find pair whose sum already // exists in array #include using namespace std; // Function to find pair whose sum exists in arr[] void findPair(int arr[], int n) { // Hash to store all element of array unordered_set s; for (int i = 0; i < n; i++) s.insert(arr[i]); bool found = false; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Check sum already exists or not if (s.find(arr[i] + arr[j]) != s.end()) { cout << arr[i] << "" "" << arr[j] << endl; found = true; } } } if (found == false) cout << ""Not exist"" << endl; } // Driven code int main() { int arr[] = { 10, 4, 8, 13, 5 }; int n = sizeof(arr) / sizeof(arr[0]); findPair(arr, n); return 0; }",quadratic,quadratic "// C++ implementation to find such pairs #include using namespace std; // Function to find pair such that (a % b = k) bool printPairs(int arr[], int n, int k) { bool isPairFound = true; // Consider each and every pair for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { cout << ""("" << arr[i] << "", "" << arr[j] << "")"" << "" ""; isPairFound = true; } } } return isPairFound; } // Driver program int main() { int arr[] = { 2, 3, 5, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; if (printPairs(arr, n, k) == false) cout << ""No such pair exists""; return 0; }",constant,quadratic "// C++ program to find all pairs such that // a % b = k. #include using namespace std; // Utility function to find the divisors of // n and store in vector v[] vector findDivisors(int n) { vector v; // Vector is used to store the divisors for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // If n is a square number, push // only one occurrence if (n / i == i) v.push_back(i); else { v.push_back(i); v.push_back(n / i); } } } return v; } // Function to find pairs such that (a%b = k) bool printPairs(int arr[], int n, int k) { // Store all the elements in the map // to use map as hash for finding elements // in O(1) time. unordered_map occ; for (int i = 0; i < n; i++) occ[arr[i]] = true; bool isPairFound = false; for (int i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ[k] && k < arr[i]) { cout << ""("" << k << "", "" << arr[i] << "") ""; isPairFound = true; } // Now check for the current element as 'a' // how many b exists such that a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) vector v = findDivisors(arr[i] - k); // Check for each divisor i.e. arr[i] % b = k // or not, if yes then print that pair. for (int j = 0; j < v.size(); j++) { if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) { cout << ""("" << arr[i] << "", "" << v[j] << "") ""; isPairFound = true; } } // Clear vector v.clear(); } } return isPairFound; } // Driver program int main() { int arr[] = { 3, 1, 2, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; if (printPairs(arr, n, k) == false) cout << ""No such pair exists""; return 0; }",linear,linear "// C++ program to convert an array in reduced // form #include using namespace std; void convert(int arr[], int n) { // Create a temp array and copy contents // of arr[] to temp int temp[n]; memcpy(temp, arr, n*sizeof(int)); // Sort temp array sort(temp, temp + n); // Create a hash table. Refer // http://tinyurl.com/zp5wgef unordered_map umap; // One by one insert elements of sorted // temp[] and assign them values from 0 // to n-1 int val = 0; for (int i = 0; i < n; i++) umap[temp[i]] = val++; // Convert array by taking positions from // umap for (int i = 0; i < n; i++) arr[i] = umap[arr[i]]; } void printArr(int arr[], int n) { for (int i=0; i #define ASCII_SIZE 256 using namespace std; char getMaxOccurringChar(char* str) { // Create array to keep the count of individual // characters and initialize the array as 0 int count[ASCII_SIZE] = { 0 }; // Construct character count array from the input // string. int len = strlen(str); int max = 0; // Initialize max count char result; // Initialize result // Traversing through the string and maintaining // the count of each character for (int i = 0; i < len; i++) { count[str[i]]++; if (max < count[str[i]]) { max = count[str[i]]; result = str[i]; } } return result; } // Driver program to test the above function int main() { char str[] = ""sample string""; cout << ""Max occurring character is "" << getMaxOccurringChar(str); }",constant,linear "// C++ program to print all words that have // the same unique character set #include using namespace std; #define MAX_CHAR 26 // Generates a key from given string. The key // contains all unique characters of given string in // sorted order consisting of only distinct elements. string getKey(string &str) { bool visited[MAX_CHAR] = { false }; // store all unique characters of current // word in key for (int j = 0; j < str.length(); j++) visited[str[j] - 'a'] = true ; string key = """"; for (int j=0; j < MAX_CHAR; j++) if (visited[j]) key = key + (char)('a'+j); return key; } // Print all words together with same character sets. void wordsWithSameCharSet(string words[], int n) { // Stores indexes of all words that have same // set of unique characters. unordered_map > Hash; // Traverse all words for (int i=0; i using namespace std; // Function to find the word string secMostRepeated(vector seq) { // Store all the words with its occurrence unordered_map occ; for (int i = 0; i < seq.size(); i++) occ[seq[i]]++; // find the second largest occurrence int first_max = INT_MIN, sec_max = INT_MIN; for (auto it = occ.begin(); it != occ.end(); it++) { if (it->second > first_max) { sec_max = first_max; first_max = it->second; } else if (it->second > sec_max && it->second != first_max) sec_max = it->second; } // Return string with occurrence equals // to sec_max for (auto it = occ.begin(); it != occ.end(); it++) if (it->second == sec_max) return it->first; } // Driver program int main() { vector seq = { ""ccc"", ""aaa"", ""ccc"", ""ddd"", ""aaa"", ""aaa"" }; cout << secMostRepeated(seq); return 0; }",linear,linear "// C++ program to find the smallest element // with frequency exactly k. #include using namespace std; int smallestKFreq(int a[], int n, int k) { unordered_map m; // Map is used to store the count of // elements present in the array for (int i = 0; i < n; i++) m[a[i]]++; // Traverse the map and find minimum // element with frequency k. int res = INT_MAX; for (auto it = m.begin(); it != m.end(); ++it) if (it->second == k) res = min(res, it->first); return (res != INT_MAX)? res : -1; } // Driver code int main() { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << smallestKFreq(arr, n, k); return 0; }",linear,linear "// C++ code to find number // occurring prime number // of times with frequency >= k #include using namespace std; // Check if the number of // occurrences are primes // or not bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function to find number // with prime occurrences void primeOccurrences(int arr[], int k) { unordered_map map; // Insert values and // their frequencies for (int i = 0; i < 12; i++) map[arr[i]]++; // Traverse map and find // elements with prime // frequencies and frequency // at least k for (auto x : map) { if (isPrime(x.second) && x.second >= k) cout << x.first << endl; } } // Driver code int main() { int arr[] = {11, 11, 11, 23, 11, 37, 37, 51, 51, 51, 51, 51}; int k = 2; primeOccurrences(arr, k); return 0; } // This code is contributed by // Manish Shaw(manishshaw1)",linear,linear "// C++ implementation to find k numbers with most // occurrences in the given array #include using namespace std; // Comparison function to sort the 'freq_arr[]' bool compare(pair p1, pair p2) { // If frequencies of two elements are same // then the larger number should come first if (p1.second == p2.second) return p1.first > p2.first; // Sort on the basis of decreasing order // of frequencies return p1.second > p2.second; } // Function to print the k numbers with most occurrences void print_N_mostFrequentNumber(int arr[], int N, int K) { // unordered_map 'mp' implemented as frequency hash // table unordered_map mp; for (int i = 0; i < N; i++) mp[arr[i]]++; // store the elements of 'mp' in the vector 'freq_arr' vector > freq_arr(mp.begin(), mp.end()); // Sort the vector 'freq_arr' on the basis of the // 'compare' function sort(freq_arr.begin(), freq_arr.end(), compare); // display the top k numbers cout << K << "" numbers with most occurrences are:\n""; for (int i = 0; i < K; i++) cout << freq_arr[i].first << "" ""; } // Driver's code int main() { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; // Function call print_N_mostFrequentNumber(arr, N, K); return 0; }",logn,nlogn "// C++ program to find k numbers with most // occurrences in the given array #include using namespace std; // Function to print the k numbers with most occurrences void print_N_mostFrequentNumber(int arr[], int N, int K) { // HashMap to store count of the elements unordered_map elementCount; for (int i = 0; i < N; i++) { elementCount[arr[i]]++; } // Array to store the elements according // to their frequency vector > frequency(N + 1); // Inserting elements in the frequency array for (auto element : elementCount) { frequency[element.second].push_back(element.first); } int count = 0; cout << K << "" numbers with most occurrences are:\n""; for (int i = frequency.size() - 1; i >= 0; i--) { for (auto element : frequency[i]) { count++; cout << element << "" ""; } // if K elements have been printed if (count == K) return; } return; } // Driver's code int main() { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; // Function call print_N_mostFrequentNumber(arr, N, K); return 0; }",linear,linear "/* C++ program to find first repeating element in arr[] */ #include using namespace std; // This function prints the first repeating element in arr[] void printFirstRepeating(int arr[], int n) { // Initialize index of first repeating element int min = -1; // Creates an empty hashset set myset; // Traverse the input array from right to left for (int i = n - 1; i >= 0; i--) { // If element is already in hash set, update min if (myset.find(arr[i]) != myset.end()) min = i; else // Else add element to hash set myset.insert(arr[i]); } // Print the result if (min != -1) cout << ""The first repeating element is "" << arr[min]; else cout << ""There are no repeating elements""; } // Driver Code int main() { int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); printFirstRepeating(arr, n); } // This article is contributed by Chhavi",linear,linear "/* C++ program to find first repeating element in arr[] */ #include using namespace std; // This function prints the // first repeating element in arr[] void printFirstRepeating(int arr[], int n) { // This will set k=1, if any // repeating element found int k = 0; // max = maximum from (all elements & n) int max = n; for (int i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 int a[max + 1] = {}; // Store 1 in array b // if element is duplicate // initialized by 0 int b[max + 1] = {}; for (int i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]]) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i + 1; } if (k == 0) cout << ""No repeating element found"" << endl; else { int min = max + 1; // trace array a & find repeating element // with min index for (int i = 0; i < max + 1; i++) if (a[i] && min > a[i] && b[i]) min = a[i]; cout << arr[min - 1]; } cout << endl; } // Driver method to test above method int main() { int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); printFirstRepeating(arr, N); }",linear,linear "// Simple CPP program to find first non- // repeating element. #include using namespace std; int firstNonRepeating(int arr[], int n) { // Loop for checking each element for (int i = 0; i < n; i++) { int j; // Checking if ith element is present in array for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; // if ith element is not present in array // except at ith index then return element if (j == n) return arr[i]; } return -1; } // Driver code int main() { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << firstNonRepeating(arr, n); return 0; }",constant,quadratic "// Efficient CPP program to find first non- // repeating element. #include using namespace std; int firstNonRepeating(int arr[], int n) { // Insert all array elements in hash // table unordered_map mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse array again and return // first element with count 1. for (int i = 0; i < n; i++) if (mp[arr[i]] == 1) return arr[i]; return -1; } // Driver code int main() { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << firstNonRepeating(arr, n); return 0; }",linear,linear "// C++ program to print k-th distinct // element in a given array #include using namespace std; // Returns k-th distinct // element in arr. int printKDistinct(int arr[], int n, int k) { int dist_count = 0; for (int i = 0; i < n; i++) { // Check if current element is // present somewhere else. int j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1; } // Driver Code int main () { int ar[] = {1, 2, 1, 3, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); int k = 2; cout << printKDistinct(ar, n, k); return 0; }",constant,quadratic "// C++ program to print k-th // distinct element in a // given array #include using namespace std; // Returns k-th distinct // element in arr int printKDistinct(int arr[], int n, int k) { // Traverse input array and // store counts if individual // elements. unordered_map h; for (int i = 0; i < n; i++) h[arr[i]]++; // If size of hash is // less than k. if (h.size() < k) return -1; // Traverse array again and // find k-th element with // count as 1. int dist_count = 0; for (int i = 0; i < n; i++) { if (h[arr[i]] == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1; } // Driver Code int main () { int ar[] = {1, 2, 1, 3, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); cout << printKDistinct(ar, n, 2); return 0; }",linear,linear "// C++ program to print all distinct elements in a given array #include using namespace std; void printDistinct(int arr[], int n) { // Pick all elements one by one for (int i=0; i using namespace std; void printDistinct(int arr[], int n) { // First sort the array so that all occurrences become consecutive sort(arr, arr + n); // Traverse the sorted array for (int i=0; i using namespace std; // This function prints all distinct elements void printDistinct(int arr[],int n) { // Creates an empty hashset unordered_set s; // Traverse the input array for (int i=0; i using namespace std; int main() { int ar[] = { 10, 5, 3, 4, 3, 5, 6 }; map hm; for (int i = 0; i < sizeof(ar)/sizeof(ar[0]); i++) { // total = O(n*logn) hm.insert({ar[i], i}); // time complexity for insert() in map O(logn) } cout <<""[""; for (auto const &pair: hm) { cout << pair.first << "", ""; } cout <<""]""; } // This code is contributed by Shubham Singh",linear,nlogn "// Simple CPP program to find pairs of positive // and negative values present in an array. #include using namespace std; // Print pair with negative and positive value void printPairs(int arr[], int n) { vector v; // For each element of array. for (int i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (int j = i + 1; j < n; j++) // If absolute values are equal print pair. if (abs(arr[i]) == abs(arr[j])) v.push_back(abs(arr[i])); // If size of vector is 0, therefore there is no // element with positive negative value, print ""0"" if (v.size() == 0) return; // Print the pair with negative positive value. for (int i = 0; i < v.size(); i++) cout << -v[i] << "" "" << v[i] << "" ""; } // Driver code int main() { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call printPairs(arr, n); return 0; }",linear,quadratic "// CPP program to find pairs of // positive and negative values present in // an array. #include using namespace std; // Print pair with negative and positive value void printPairs(int arr[], int n) { vector v; unordered_map cnt; // For each element of array. for (int i = 0; i < n; i++) { // If element has not encounter early, // mark it on cnt array. if (cnt[abs(arr[i])] == 0) cnt[abs(arr[i])] = 1; // If seen before, push it in vector ( // given that elements are distinct) else { v.push_back(abs(arr[i])); cnt[abs(arr[i])] = 0; } } if (v.size() == 0) return; for (int i = 0; i < v.size(); i++) cout << ""-"" << v[i] << "" "" << v[i] << "" ""; } // Driver code int main() { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call printPairs(arr, n); return 0; }",linear,linear "// CPP program to find pairs of // positive and negative values present in // an array. #include using namespace std; // Print pair with negative and positive value void printPairs(int arr[], int n) { unordered_set hs; vector ans; for (int i = 0; i < n; i++) { if (hs.find((arr[i]) * -1) != hs.end()) { if (arr[i] < 0) { cout << arr[i] << "" ""; cout << (arr[i] * -1) << "" ""; } else { cout << (arr[i] * -1) << "" ""; cout << arr[i] << "" ""; } } hs.insert(arr[i]); } return; } // Driver code int main() { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call printPairs(arr, n); return 0; }",linear,linear "// CPP program to count divisible pairs. #include using namespace std; int countDivisibles(int arr[], int n) { int res = 0; // Iterate through all pairs for (int i=0; i using namespace std; // Function to return the total // count of pairs such that // arr[i]%arr[j]==0 int total_count(int arr[], int n) { int count = 0; // Storing the occurrence of // every element in array in // unordered_map unordered_map freq; for(int i=0;i using namespace std; bool canPairs(int nums[], int n, int k) { // Array with odd length // cannot be divided if (n % 2 == 1) return false; // Initialize count = 0 int count = 0; vector vis(n, -1); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((nums[i] + nums[j]) % k == 0 and vis[i] == -1 and vis[j] == -1) { // if pair is divisible increment // the count and mark elements // as visited count++; vis[i] = 1; vis[j] = 1; } } } if (count == n / 2) return true; else return false; } // Driver code int main() { int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call canPairs(arr, n, k) ? cout << ""True"" : cout << ""False""; return 0; } // This code is contributed by Arpit Jain",linear,quadratic "// A C++ program to check if arr[0..n-1] can be divided // in pairs such that every pair is divisible by k. #include using namespace std; // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. bool canPairs(int arr[], int n, int k) { // An odd length array cannot be divided into pairs if (n & 1) return false; // Create a frequency array to count occurrences // of all remainders when divided by k. unordered_map freq; // Count occurrences of all remainders for (int i = 0; i < n; i++) freq[((arr[i] % k) + k) % k]++; // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (int i = 0; i < n; i++) { // Remainder of current element int rem = ((arr[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (freq[rem] % 2 != 0) return false; } // If remainder is 0, then there must be even // number of elements with 0 remainder else if (rem == 0) { if (freq[rem] & 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else if (freq[rem] != freq[k - rem]) return false; } return true; } // Driver code int main() { int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call canPairs(arr, n, k) ? cout << ""True"" : cout << ""False""; return 0; }",linear,linear "// C++ implementation to find the longest subarray // with sum divisible by k #include using namespace std; // function to find the longest subarray // with sum divisible by k int longestSubarrWthSumDivByK(int arr[], int n, int k) { // unordered map 'um' implemented as // hash table unordered_map um; // 'mod_arr[i]' stores (sum[0..i] % k) int mod_arr[n], max_len = 0; int curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (int i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible by k if (mod_arr[i] == 0) // update 'max' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(mod_arr[i]) == um.end()) um[mod_arr[i]] = i; else // if true, then update 'max' if (max_len < (i - um[mod_arr[i]])) max_len = i - um[mod_arr[i]]; } // return the required length of longest subarray // with sum divisible by 'k' return max_len; } // Driver code int main() { int arr[] = { 2, 7, 6, 1, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << ""Length = "" << longestSubarrWthSumDivByK(arr, n, k); return 0; } // Code updated by Kshitij Dwivedi",linear,linear "#include using namespace std; // function to find the longest subarray // with sum divisible by k int longestSubarrWthSumDivByK(int arr[], int n, int k) { // unordered map 'um' implemented as // hash table unordered_map um; int max_len = 0; int curr_sum = 0; for (int i = 0; i < n; i++) { curr_sum += arr[i]; int mod = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod == 0) // update 'max_len' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(mod) == um.end()) um[mod] = i; else // if true, then update 'max_len' if (max_len < (i - um[mod])) max_len = i - um[mod]; } // return the required length of longest subarray with // sum divisible by 'k' return max_len; } // Driver code int main() { int arr[] = { 2, 7, 6, 1, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << ""Length = "" << longestSubarrWthSumDivByK(arr, n, k); return 0; } // Code Updated by Kshitij Dwivedi",linear,linear "// CPP code to find the subarray with // no pair sum divisible by K #include using namespace std; // function to find the subarray with // no pair sum divisible by k void subarrayDivisibleByK(int arr[], int n, int k) { // hash table to store the remainders // obtained on dividing by K map mp; // s : starting index of the // current subarray, e : ending // index of the current subarray, maxs : // starting index of the maximum // size subarray so far, maxe : ending // index of the maximum size subarray // so far int s = 0, e = 0, maxs = 0, maxe = 0; // insert the first element in the set mp[arr[0] % k]++; for (int i = 1; i < n; i++) { int mod = arr[i] % k; // Removing starting elements of current // subarray while there is an element in // set which makes a pair with mod[i] such // that the pair sum is divisible. while (mp[k - mod] != 0 || (mod == 0 && mp[mod] != 0)) { mp[arr[s] % k]--; s++; } // include the current element in // the current subarray the ending // index of the current subarray // increments by one mp[mod]++; e++; // compare the size of the current // subarray with the maximum size so // far if ((e - s) > (maxe - maxs)) { maxe = e; maxs = s; } } cout << ""The maximum size is "" << maxe - maxs + 1 << "" and "" ""the subarray is as follows\n""; for (int i=maxs; i<=maxe; i++) cout << arr[i] << "" ""; } int main() { int k = 3; int arr[] = {5, 10, 15, 20, 25}; int n = sizeof(arr)/sizeof(arr[0]); subarrayDivisibleByK(arr, n, k); return 0; }",linear,nlogn "// C++ implementation of the approach #include using namespace std; // Function to find special numbers void divisibilityCheck(int arr[], int n) { // Storing all array elements in a hash // and finding maximum element in the array unordered_set s; int max_ele = INT_MIN; for (int i = 0; i < n; i++) { s.insert(arr[i]); // Update the maximum element of the array max_ele = max(max_ele, arr[i]); } // Traversing the array elements and storing the array // multiples that are present in s in res unordered_set res; for (int i = 0; i < n; i++) { // Check for non-zero values only if (arr[i] != 0) { // Checking the factors of current element for (int j = arr[i] * 2; j <= max_ele; j += arr[i]) { // If current factor is already part // of the array then store it if (s.find(j) != s.end()) res.insert(j); } } } // For non-distinct elmments // To store the frequency of elements unordered_map mp; for (int i = 0; i < n; i++) mp[arr[i]]++; unordered_map::iterator it; vector ans; for (it = mp.begin(); it != mp.end(); it++) { // If frequency is at least 2 if (it->second >= 2) { if (res.find(it->first) == res.end()) { // If frequency is greater than 1 and // the number is not divisible by // any other number int val = it->second; // Then we push the element number of // times it is present in the vector while (val--) ans.push_back(it->first); } } // If frequency is greater than 1 and the number // is divisible by any other number if (res.find(it->first) != res.end()) { int val = it->second; // Then we push the element number of // times it is present in the vector while (val--) ans.push_back(it->first); } } // Print the elements that are divisible by // at least one other element from the array for (auto x : ans) cout << x << "" ""; } // Driver code int main() { int arr[] = { 2, 3, 8, 6, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); divisibilityCheck(arr, n); return 0; }",linear,quadratic "// C++ program to find three element // from different three arrays such // that a + b + c is equal to // given sum #include using namespace std; // Function to check if there is // an element from each array such // that sum of the three elements // is equal to given sum. bool findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum) { for (int i = 0; i < n1; i++) for (int j = 0; j < n2; j++) for (int k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false; } // Driver Code int main() { int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = sizeof(a1) / sizeof(a1[0]); int n2 = sizeof(a2) / sizeof(a2[0]); int n3 = sizeof(a3) / sizeof(a3[0]); findTriplet(a1, a2, a3, n1, n2, n3, sum)? cout << ""Yes"" : cout << ""No""; return 0; }",constant,cubic "// C++ program to find three element // from different three arrays such // that a + b + c is equal to // given sum #include using namespace std; // Function to check if there is // an element from each array such // that sum of the three elements is // equal to given sum. bool findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum) { // Store elements of // first array in hash unordered_set s; for (int i = 0; i < n1; i++) s.insert(a1[i]); // sum last two arrays // element one by one for (int i = 0; i < n2; i++) { for (int j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (s.find(sum - a2[i] - a3[j]) != s.end()) return true; } } return false; } // Driver Code int main() { int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = sizeof(a1) / sizeof(a1[0]); int n2 = sizeof(a2) / sizeof(a2[0]); int n3 = sizeof(a3) / sizeof(a3[0]); findTriplet(a1, a2, a3, n1, n2, n3, sum)? cout << ""Yes"" : cout << ""No""; return 0; }",linear,quadratic "// C++ program for the above approach #include using namespace std; // Returns length of the largest // subarray with 0 sum int maxLen(int arr[], int N) { // Initialize result int max_len = 0; // Pick a starting point for (int i = 0; i < N; i++) { // Initialize currr_sum for // every starting point int curr_sum = 0; // Try all subarrays starting with 'i' for (int j = i; j < N; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, // then update max_len // if required if (curr_sum == 0) max_len = max(max_len, j - i + 1); } } return max_len; } // Driver's Code int main() { int arr[] = {15, -2, 2, -8, 1, 7, 10, 23}; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""Length of the longest 0 sum subarray is "" << maxLen(arr, N); return 0; }",constant,quadratic "// C++ program for the above approach #include using namespace std; // Returns Length of the required subarray int maxLen(int arr[], int N) { // Map to store the previous sums unordered_map presum; int sum = 0; // Initialize the sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < N; i++) { // Add current element to sum sum += arr[i]; if (sum == 0) max_len = i + 1; // Look for this sum in Hash table if (presum.find(sum) != presum.end()) { // If this sum is seen before, then update // max_len max_len = max(max_len, i - presum[sum]); } else { // Else insert this sum with index // in hash table presum[sum] = i; } } return max_len; } // Driver's Code int main() { int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << ""Length of the longest 0 sum subarray is "" << maxLen(arr, N); return 0; }",linear,linear "// CPP program to find length of the // longest increasing subsequence // whose adjacent element differ by 1 #include using namespace std; // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 void longestSubsequence(int a[], int n) { // stores the index of elements unordered_map mp; // stores the length of the longest // subsequence that ends with a[i] int dp[n]; memset(dp, 0, sizeof(dp)); int maximum = INT_MIN; // iterate for all element int index = -1; for (int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.find(a[i] - 1) != mp.end()) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is ""maximum"". So We // print these many consecutive elements // starting from ""a[index] - maximum + 1"" // to a[index]. for (int curr = a[index] - maximum + 1; curr <= a[index]; curr++) cout << curr << "" ""; } // Driver Code int main() { int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = sizeof(a) / sizeof(a[0]); longestSubsequence(a, n); return 0; }",linear,linear "// CPP program to find length of the // longest increasing subsequence // whose adjacent element differ by 1 #include using namespace std; // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 int longestSubsequence(int a[], int n) { // stores the index of elements unordered_map mp; // stores the length of the longest // subsequence that ends with a[i] int dp[n]; memset(dp, 0, sizeof(dp)); int maximum = INT_MIN; // iterate for all element for (int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.find(a[i] - 1) != mp.end()) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length maximum = max(maximum, dp[i]); } return maximum; } // Driver Code int main() { int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = sizeof(a) / sizeof(a[0]); cout << longestSubsequence(a, n); return 0; }",linear,linear "// C++ implementation to find longest subsequence // such that difference between adjacents is one #include using namespace std; // function to find longest subsequence such // that difference between adjacents is one int longLenSub(int arr[], int n) { // hash table to map the array element with the // length of the longest subsequence of which // it is a part of and is the last element of // that subsequence unordered_map um; // to store the longest length subsequence int longLen = 0; // traverse the array elements for (int i=0; i using namespace std; // Function for LIS int findLIS(int A[], int n) { unordered_map hash; // Initialize result int LIS_size = 1; int LIS_index = 0; hash[A[0]] = 1; // iterate through array and find // end index of LIS and its Size for (int i = 1; i < n; i++) { hash[A[i]] = hash[A[i] - 1] + 1; if (LIS_size < hash[A[i]]) { LIS_size = hash[A[i]]; LIS_index = A[i]; } } // print LIS size cout << ""LIS_size = "" << LIS_size << ""\n""; // print LIS after setting start element cout << ""LIS : ""; int start = LIS_index - LIS_size + 1; while (start <= LIS_index) { cout << start << "" ""; start++; } } // driver int main() { int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; int n = sizeof(A) / sizeof(A[0]); findLIS(A, n); return 0; }",linear,linear "// C++ implementation to count subsets having // even numbers only and all are distinct #include using namespace std; // function to count the // required subsets int countSubsets(int arr[], int n) { unordered_set us; int even_count = 0; // inserting even numbers in the set 'us' // single copy of each number is retained for (int i=0; i:: iterator itr; // distinct even numbers even_count = us.size(); // total count of required subsets return (pow(2, even_count) - 1); } // Driver program to test above int main() { int arr[] = {4, 2, 1, 9, 2, 6, 5, 3}; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Number of subsets = "" << countSubsets(arr, n); return 0; } ",linear,linear "// C++ program to count distinct // elements in every window of size K #include using namespace std; // Counts distinct elements in window of size K int countWindowDistinct(int win[], int K) { int dist_count = 0; // Traverse the window for (int i = 0; i < K; i++) { // Check if element arr[i] exists in arr[0..i-1] int j; for (j = 0; j < i; j++) if (win[i] == win[j]) break; if (j == i) dist_count++; } return dist_count; } // Counts distinct elements in all windows of size k void countDistinct(int arr[], int N, int K) { // Traverse through every window for (int i = 0; i <= N - K; i++) cout << countWindowDistinct(arr + i, K) << endl; } // Driver's code int main() { int arr[] = {1, 2, 1, 3, 4, 2, 3}, K = 4; int N = sizeof(arr) / sizeof(arr[0]); // Function call countDistinct(arr, N, K); return 0; }",constant,quadratic "// C++ program for the above approach #include #include using namespace std; void countDistinct(int arr[], int K, int N) { // Creates an empty hashmap hm unordered_map hm; // initialize distinct element count for current window int dist_count = 0; // Traverse the first window and store count // of every element in hash map for (int i = 0; i < K; i++) { if (hm[arr[i]] == 0) { dist_count++; } hm[arr[i]] += 1; } // Print count of first window cout << dist_count << endl; // Traverse through the remaining array for (int i = K; i < N; i++) { // Remove first element of previous window // If there was only one occurrence, then reduce distinct count. if (hm[arr[i - K]] == 1) { dist_count--; } // reduce count of the removed element hm[arr[i - K]] -= 1; // Add new element of current window // If this element appears first time, // increment distinct element count if (hm[arr[i]] == 0) { dist_count++; } hm[arr[i]] += 1; // Print count of current window cout << dist_count << endl; } } // Driver's code int main() { int arr[] = {1, 2, 1, 3, 4, 2, 3}; int N = sizeof(arr) / sizeof(arr[0]); int K = 4; // Function call countDistinct(arr, K, N); return 0; } // This solution is contributed by Aditya Goel",linear,linear "// C++ program to find the maximum // possible sum of a window in one // array such that elements in same // window of other array are unique. #include using namespace std; // Function to return maximum sum of window // in B[] according to given constraints. int returnMaxSum(int A[], int B[], int n) { // Map is used to store elements // and their counts. unordered_set mp; int result = 0; // Initialize result // calculating the maximum possible // sum for each subarray containing // unique elements. int curr_sum = 0, curr_begin = 0; for (int i = 0; i < n; ++i) { // Remove all duplicate // instances of A[i] in // current window. while (mp.find(A[i]) != mp.end()) { mp.erase(A[curr_begin]); curr_sum -= B[curr_begin]; curr_begin++; } // Add current instance of A[i] // to map and to current sum. mp.insert(A[i]); curr_sum += B[i]; // Update result if current // sum is more. result = max(result, curr_sum); } return result; } // Driver code int main() { int A[] = { 0, 1, 2, 3, 0, 1, 4 }; int B[] = { 9, 8, 1, 2, 3, 4, 5 }; int n = sizeof(A)/sizeof(A[0]); cout << returnMaxSum(A, B, n); return 0; }",linear,linear "// C++ program to find if // there is a zero sum subarray #include using namespace std; bool subArrayExists(int arr[], int N) { unordered_set sumSet; // Traverse through array // and store prefix sums int sum = 0; for (int i = 0; i < N; i++) { sum += arr[i]; // If prefix sum is 0 or // it is already present if (sum == 0 || sumSet.find(sum) != sumSet.end()) return true; sumSet.insert(sum); } return false; } // Driver's code int main() { int arr[] = {-3, 2, 3, 1, 6}; int N = sizeof(arr) / sizeof(arr[0]); // Function call if (subArrayExists(arr, N)) cout << ""Found a subarray with 0 sum""; else cout << ""No Such Sub Array Exists!""; return 0; }",linear,linear "// C++ program to print all subarrays // in the array which has sum 0 #include using namespace std; vector > findSubArrays(int arr[], int n) { // Array to store all the start and end // indices of subarrays with 0 sum vector > out; for (int i = 0; i < n; i++) { int prefix = 0; for (int j = i; j < n; j++) { prefix += arr[j]; if (prefix == 0) out.push_back({ i, j }); } } return out; } // Function to print all subarrays with 0 sum void print(vector > out) { for (auto it = out.begin(); it != out.end(); it++) cout << ""Subarray found from Index "" << it->first << "" to "" << it->second << endl; } // Driver code int main() { // Given array int arr[] = { 6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call vector > out = findSubArrays(arr, n); // if we didn’t find any subarray with 0 sum, // then subarray doesn’t exists if (out.size() == 0) { cout << ""No subarray exists""; } else { print(out); } return 0; } // This article is contributed by Arpit Jain",constant,quadratic "// C++ program to print all subarrays // in the array which has sum 0 #include using namespace std; // Function to print all subarrays in the array which // has sum 0 vector< pair > findSubArrays(int arr[], int n) { // create an empty map unordered_map > map; // create an empty vector of pairs to store // subarray starting and ending index vector > out; // Maintains sum of elements so far int sum = 0; for (int i = 0; i < n; i++) { // add current element to sum sum += arr[i]; // if sum is 0, we found a subarray starting // from index 0 and ending at index i if (sum == 0) out.push_back(make_pair(0, i)); // If sum already exists in the map there exists // at-least one subarray ending at index i with // 0 sum if (map.find(sum) != map.end()) { // map[sum] stores starting index of all subarrays vector vc = map[sum]; for (auto it = vc.begin(); it != vc.end(); it++) out.push_back(make_pair(*it + 1, i)); } // Important - no else map[sum].push_back(i); } // return output vector return out; } // Utility function to print all subarrays with sum 0 void print(vector> out) { for (auto it = out.begin(); it != out.end(); it++) cout << ""Subarray found from Index "" << it->first << "" to "" << it->second << endl; } // Driver code int main() { int arr[] = {6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7}; int n = sizeof(arr)/sizeof(arr[0]); vector > out = findSubArrays(arr, n); // if we didn’t find any subarray with 0 sum, // then subarray doesn’t exists if (out.size() == 0) cout << ""No subarray exists""; else print(out); return 0; }",linear,linear "/* A simple program to print subarray with sum as given sum */ #include using namespace std; /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { cout << ""Sum found between indexes "" << i << "" and "" << j; return 1; } } } cout << ""No subarray found""; return 0; } // Driver Code int main() { int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; // Function call subArraySum(arr, n, sum); return 0; }",constant,quadratic "// C++ program to print subarray with sum as given sum #include using namespace std; // Function to print subarray with sum as given sum void subArraySum(int arr[], int n, int sum) { // create an empty map unordered_map map; // Maintains sum of elements so far int curr_sum = 0; for (int i = 0; i < n; i++) { // add current element to curr_sum curr_sum = curr_sum + arr[i]; // if curr_sum is equal to target sum // we found a subarray starting from index 0 // and ending at index i if (curr_sum == sum) { cout << ""Sum found between indexes "" << 0 << "" to "" << i << endl; return; } // If curr_sum - sum already exists in map // we have found a subarray with target sum if (map.find(curr_sum - sum) != map.end()) { cout << ""Sum found between indexes "" << map[curr_sum - sum] + 1 << "" to "" << i << endl; return; } map[curr_sum] = i; } // If we reach here, then no subarray exists cout << ""No subarray with given sum exists""; } // Driver code int main() { int arr[] = { 10, 2, -2, -20, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = -10; // Function call subArraySum(arr, n, sum); return 0; }",linear,linear "// CPP program to find minimum number // of insertions to make a string // palindrome #include using namespace std; // Function will return number of // characters to be added int minInsertion(string str) { // To store string length int n = str.length(); // To store number of characters // occurring odd number of times int res = 0; // To store count of each // character int count[26] = { 0 }; // To store occurrence of each // character for (int i = 0; i < n; i++) count[str[i] - 'a']++; // To count characters with odd // occurrence for (int i = 0; i < 26; i++) if (count[i] % 2 == 1) res++; // As one character can be odd return // res - 1 but if string is already // palindrome return 0 return (res == 0) ? 0 : res - 1; } // Driver program int main() { string str = ""geeksforgeeks""; cout << minInsertion(str); return 0; }",constant,linear "// C++ implementation to find maximum length // subsequence with difference between adjacent // elements as either 0 or 1 #include using namespace std; // function to find maximum length subsequence // with difference between adjacent elements as // either 0 or 1 int maxLenSub(int arr[], int n) { // hash table to map the array element with the // length of the longest subsequence of which // it is a part of and is the last element of // that subsequence unordered_map um; // to store the maximum length subsequence int maxLen = 0; // traverse the array elements for (int i=0; i using namespace std; // Return the maximum difference between // frequencies of any two elements such that // element with greater frequency is also // greater in value. int maxdiff(int arr[], int n) { unordered_map freq; // Finding the frequency of each element. for (int i = 0; i < n; i++) freq[arr[i]]++; int ans = 0; for (int i=0; i freq[arr[j]] && arr[i] > arr[j] ) ans = max(ans, freq[arr[i]]-freq[arr[j]]); else if (freq[arr[i]] < freq[arr[j]] && arr[i] < arr[j] ) ans = max(ans, freq[arr[j]]-freq[arr[i]]); } } return ans; } // Driven Program int main() { int arr[] = { 3, 1, 3, 2, 3, 2 }; int n = sizeof(arr)/sizeof(arr[0]); cout << maxdiff(arr, n) << endl; return 0; }",linear,quadratic "// Efficient C++ program to find maximum // difference between frequency of any two // elements such that element with greater // frequency is also greater in value. #include using namespace std; // Return the maximum difference between // frequencies of any two elements such that // element with greater frequency is also // greater in value. int maxdiff(int arr[], int n) { unordered_map freq; int dist[n]; // Finding the frequency of each element. int j = 0; for (int i = 0; i < n; i++) { if (freq.find(arr[i]) == freq.end()) dist[j++] = arr[i]; freq[arr[i]]++; } // Sorting the distinct element sort(dist, dist + j); int min_freq = n+1; // Iterate through all sorted distinct elements. // For each distinct element, maintaining the // element with minimum frequency than that // element and also finding the maximum // frequency difference int ans = 0; for (int i=0; i using namespace std; int findDiff(int arr[], int n) { // sort the array sort(arr, arr + n); int count = 0, max_count = 0, min_count = n; for (int i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = max(max_count, count); min_count = min(min_count, count); count = 0; } } return (max_count - min_count); } // Driver code int main() { int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findDiff(arr, n) << ""\n""; return 0; }",constant,nlogn "// CPP code to find the difference between highest // and least frequencies #include using namespace std; int findDiff(int arr[], int n) { // Put all elements in a hash map unordered_map hm; for (int i = 0; i < n; i++) hm[arr[i]]++; // Find counts of maximum and minimum // frequent elements int max_count = 0, min_count = n; for (auto x : hm) { max_count = max(max_count, x.second); min_count = min(min_count, x.second); } return (max_count - min_count); } // Driver int main() { int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findDiff(arr, n) << ""\n""; return 0; }",linear,linear "// C++ program to find minimum range that // contains exactly k distinct numbers. #include using namespace std; // Prints the minimum range that contains exactly // k distinct numbers. void minRange(int arr[], int n, int k) { // Starting and ending index of resultant subarray int start = 0, end = n; // Selecting each element as the start index for // subarray for (int i = 0; i < n; i++) { // Initialize a set to store all distinct elements unordered_set set; // Selecting the end index for subarray int j; for (j = i; j < n; j++) { set.insert(arr[j]); /* If set contains exactly k elements, then check subarray[i, j] is smaller in size than the current resultant subarray */ if (set.size() == k) { if (j - i < end - start) { start = i; end = j; } // There are already k distinct elements // now, no need to consider further elements break; } } // If there are no k distinct elements // left in the array starting from index i we will // break if (j == n) { break; } } // If no window found then print -1 if (start == 0 && end == n) cout << ""Invalid k""; else cout << start << "" "" << end; } // Driver code for above function. int main() { int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; minRange(arr, n, k); return 0; } // This code is contributed by Rajdeep",linear,quadratic "// C++ program to find minimum range that // contains exactly k distinct numbers. #include using namespace std; // prints the minimum range that contains exactly // k distinct numbers. void minRange(int arr[], int n, int k) { /* start = starting index of resultant subarray end = ending index of resultant subarray */ int start = 0, end = n; unordered_map map; /* i = starting index of the window (on left side) j = ending index of the window (on right side) */ int i = 0, j = 0; while (j < n) { // Add the current element to the map map[arr[j]]++; j++; // Nothing to do when having less element if (map.size() < k) continue; /* If map contains exactly k elements, consider subarray[i, j - 1] keep removing left most elements */ while (map.size() == k) { // as considering the (j-1)th and i-th index int windowLen = (j - 1) - i + 1; int subArrayLen = end - start + 1; if (subArrayLen > windowLen) { start = i; end = j - 1; } // Remove elements from left // If freq == 1 then totally erase if (map[arr[i]] == 1) map.erase(arr[i]); // decrease freq by 1 else map[arr[i]]--; // move the starting index of window i++; } } if (start == 0 && end == n) cout << ""Invalid k"" << endl; else cout << start << "" "" << end << endl; } // Driver code for above function. int main() { int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; minRange(arr, n, k); return 0; } // This code is contributed by Rajdeep",linear,linear "// CPP program to find longest subarray with // k or less distinct elements. #include using namespace std; // function to print the longest sub-array void longest(int a[], int n, int k) { unordered_map freq; int start = 0, end = 0, now = 0, l = 0; for (int i = 0; i < n; i++) { // mark the element visited freq[a[i]]++; // if its visited first time, then increase // the counter of distinct elements by 1 if (freq[a[i]] == 1) now++; // When the counter of distinct elements // increases from k, then reduce it to k while (now > k) { // from the left, reduce the number of // time of visit freq[a[l]]--; // if the reduced visited time element // is not present in further segment // then decrease the count of distinct // elements if (freq[a[l]] == 0) now--; // increase the subsegment mark l++; } // check length of longest sub-segment // when greater than previous best // then change it if (i - l + 1 >= end - start + 1) end = i, start = l; } // print the longest sub-segment for (int i = start; i <= end; i++) cout << a[i] << "" ""; } // driver program to test the above function int main() { int a[] = { 6, 5, 1, 2, 3, 2, 1, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); int k = 3; longest(a, n, k); return 0; }",linear,linear "// C++ program to find number of pairs in an array such that // their XOR is 0 #include using namespace std; // Function to calculate the count int calculate(int a[], int n) { // Sorting the list using built in function sort(a, a + n); int count = 1; int answer = 0; // Traversing through the elements for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) // Counting frequency of each elements count += 1; else { // Adding the contribution of the frequency to // the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer; } // Driver Code int main() { int a[] = { 1, 2, 1, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); cout << calculate(a, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,nlogn "// C++ program to find number of pairs // in an array such that their XOR is 0 #include using namespace std; // Function to calculate the answer int calculate(int a[], int n){ // Finding the maximum of the array int *maximum = max_element(a, a + n); // Creating frequency array // With initial value 0 int frequency[*maximum + 1] = {0}; // Traversing through the array for(int i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } int answer = 0; // Traversing through the frequency array for(int i = 0; i < (*maximum)+1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1) ; } return answer/2; } // Driver Code int main() { int a[] = {1, 2, 1, 2, 4}; int n = sizeof(a) / sizeof(a[0]); // Function calling cout << (calculate(a,n)); } // This code is contributed by Smitha",linear,linear "// C++ implementation to count subarrays with // equal number of 1's and 0's #include using namespace std; // function to count subarrays with // equal number of 1's and 0's int countSubarrWithEqualZeroAndOne(int arr[], int n) { // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum unordered_map um; int curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (int i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; um[curr_sum]++; } int count = 0; // traverse the hash table 'um' for (auto itr = um.begin(); itr != um.end(); itr++) { // If there are more than one prefix subarrays // with a particular sum if (itr->second > 1) count += ((itr->second * (itr->second - 1)) / 2); } // add the subarrays starting from 1st element and // have equal number of 1's and 0's if (um.find(0) != um.end()) count += um[0]; // required count of subarrays return count; } // Driver program to test above int main() { int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Count = "" << countSubarrWithEqualZeroAndOne(arr, n); return 0; }",linear,linear "#include using namespace std; int countSubarrWithEqualZeroAndOne(int arr[], int n) { unordered_map mp; int sum = 0; int count = 0; for (int i = 0; i < n; i++) { // Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; // If sum = 0, it implies number of 0's and 1's are // equal from arr[0]..arr[i] if (sum == 0) count++; // if mp[sum] exists then add ""frequency-1"" to count if (mp[sum]) count += mp[sum]; // if frequency of ""sum"" is zero then we initialize // that frequency to 1 if its not 0, we increment it if (mp[sum] == 0) mp[sum] = 1; else mp[sum]++; } return count; } int main() { int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""count="" << countSubarrWithEqualZeroAndOne(arr, n); }",linear,linear "// C++ implementation to find the length of // longest subarray having count of 1's one // more than count of 0's #include using namespace std; // function to find the length of longest // subarray having count of 1's one more // than count of 0's int lenOfLongSubarr(int arr[], int n) { // unordered_map 'um' implemented as // hash table unordered_map um; int sum = 0, maxLen = 0; // traverse the given array for (int i = 0; i < n; i++) { // consider '0' as '-1' sum += arr[i] == 0 ? -1 : 1; // when subarray starts form index '0' if (sum == 1) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'um' else if (um.find(sum) == um.end()) um[sum] = i; // check if 'sum-1' is present in 'um' // or not if (um.find(sum - 1) != um.end()) { // update maxLength if (maxLen < (i - um[sum - 1])) maxLen = i - um[sum - 1]; } } // required maximum length return maxLen; } // Driver program to test above int main() { int arr[] = { 0, 1, 1, 0, 0, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ""Length = "" << lenOfLongSubarr(arr, n); return 0; }",linear,linear "// C++ program to print all triplets in given // array that form Arithmetic Progression // C++ program to print all triplets in given // array that form Arithmetic Progression #include using namespace std; // Function to print all triplets in // given sorted array that forms AP void printAllAPTriplets(int arr[], int n) { unordered_set s; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // Use hash to find if there is // a previous element with difference // equal to arr[j] - arr[i] int diff = arr[j] - arr[i]; if (s.find(arr[i] - diff) != s.end()) cout << arr[i] - diff << "" "" << arr[i] << "" "" << arr[j] << endl; } s.insert(arr[i]); } } // Driver code int main() { int arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 }; int n = sizeof(arr) / sizeof(arr[0]); printAllAPTriplets(arr, n); return 0; }",linear,quadratic "// C++ program to print all triplets in given // array that form Arithmetic Progression #include using namespace std; // Function to print all triplets in // given sorted array that forms AP void printAllAPTriplets(int arr[], int n) { for (int i = 1; i < n - 1; i++) { // Search other two elements of // AP with arr[i] as middle. for (int j = i - 1, k = i + 1; j >= 0 && k < n;) { // if a triplet is found if (arr[j] + arr[k] == 2 * arr[i]) { cout << arr[j] << "" "" << arr[i] << "" "" << arr[k] << endl; // Since elements are distinct, // arr[k] and arr[j] cannot form // any more triplets with arr[i] k++; j--; } // If middle element is more move to // higher side, else move lower side. else if (arr[j] + arr[k] < 2 * arr[i]) k++; else j--; } } } // Driver code int main() { int arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 }; int n = sizeof(arr) / sizeof(arr[0]); printAllAPTriplets(arr, n); return 0; }",constant,quadratic "// C++ program to find unique triplets // that sum up to a given value. #include using namespace std; // Structure to define a triplet. struct triplet { int first, second, third; }; // Function to find unique triplets that // sum up to a given value. int findTriplets(int nums[], int n, int sum) { int i, j, k; // Vector to store all unique triplets. vector triplets; // Set to store already found triplets // to avoid duplication. unordered_set uniqTriplets; // Variable used to hold triplet // converted to string form. string temp; // Variable used to store current // triplet which is stored in vector // if it is unique. triplet newTriplet; // Sort the input array. sort(nums, nums + n); // Iterate over the array from the // start and consider it as the // first element. for (i = 0; i < n - 2; i++) { // index of the first element in // the remaining elements. j = i + 1; // index of the last element. k = n - 1; while (j < k) { // If sum of triplet is equal to // given value, then check if // this triplet is unique or not. // To check uniqueness, convert // triplet to string form and // then check if this string is // present in set or not. If // triplet is unique, then store // it in vector. if (nums[i] + nums[j] + nums[k] == sum) { temp = to_string(nums[i]) + "" : "" + to_string(nums[j]) + "" : "" + to_string(nums[k]); if (uniqTriplets.find(temp) == uniqTriplets.end()) { uniqTriplets.insert(temp); newTriplet.first = nums[i]; newTriplet.second = nums[j]; newTriplet.third = nums[k]; triplets.push_back(newTriplet); } // Increment the first index // and decrement the last // index of remaining elements. j++; k--; } // If sum is greater than given // value then to reduce sum // decrement the last index. else if (nums[i] + nums[j] + nums[k] > sum) k--; // If sum is less than given value // then to increase sum increment // the first index of remaining // elements. else j++; } } // If no unique triplet is found, then // return 0. if (triplets.size() == 0) return 0; // Print all unique triplets stored in // vector. for (i = 0; i < triplets.size(); i++) { cout << ""["" << triplets[i].first << "", "" << triplets[i].second << "", "" << triplets[i].third << ""], ""; } } // Driver Code int main() { int nums[] = { 12, 3, 6, 1, 6, 9 }; int n = sizeof(nums) / sizeof(nums[0]); int sum = 24; // Function call if (!findTriplets(nums, n, sum)) cout << ""No triplets can be formed.""; return 0; } // This code is contributed by NIKHIL JINDAL.",linear,quadratic "// A simple C++ program to find three elements // whose sum is equal to zero #include using namespace std; // Prints all triplets in arr[] with 0 sum void findTriplets(int arr[], int n) { bool found = false; for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == 0) { cout << arr[i] << "" "" << arr[j] << "" "" << arr[k] << endl; found = true; } } } } // If no triplet with 0 sum found in array if (found == false) cout << "" not exist "" << endl; } // Driver code int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,cubic "// C++ program to find triplets in a given // array whose sum is zero #include using namespace std; // function to print triplets with 0 sum void findTriplets(int arr[], int n) { bool found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // ""-arr[i]"" unordered_set s; for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.find(x) != s.end()) { printf(""%d %d %d\n"", x, arr[i], arr[j]); found = true; } else s.insert(arr[j]); } } if (found == false) cout << "" No Triplet Found"" << endl; } // Driver code int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; }",linear,quadratic "// C++ program to find triplets in a given // array whose sum is zero #include using namespace std; // function to print triplets with 0 sum void findTriplets(int arr[], int n) { bool found = false; // sort array elements sort(arr, arr + n); for (int i = 0; i < n - 1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero printf(""%d %d %d\n"", x, arr[l], arr[r]); l++; r--; found = true; // break; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) cout << "" No Triplet Found"" << endl; } // Driven source int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; }",constant,quadratic "// C++ program to count triplets with given // product m #include using namespace std; // Function to count such triplets int countTriplets(int arr[], int n, int m) { int count = 0; // Consider all triplets and count if // their product is equal to m for (int i = 0; i < n - 2; i++) for (int j = i + 1; j < n - 1; j++) for (int k = j + 1; k < n; k++) if (arr[i] * arr[j] * arr[k] == m) count++; return count; } // Drivers code int main() { int arr[] = { 1, 4, 6, 2, 3, 8 }; int n = sizeof(arr) / sizeof(arr[0]); int m = 24; cout << countTriplets(arr, n, m); return 0; }",constant,cubic "// C++ program to count triplets with given // product m #include using namespace std; // Function to count such triplets int countTriplets(int arr[], int n, int m) { // Store all the elements in a set unordered_map occ; for (int i = 0; i < n; i++) occ[arr[i]] = i; int count = 0; // Consider all pairs and check for a // third number so their product is equal to m for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // Check if current pair divides m or not // If yes, then search for (m / arr[i]*arr[j]) if ((arr[i] * arr[j] <= m) && (arr[i] * arr[j] != 0) && (m % (arr[i] * arr[j]) == 0)) { int check = m / (arr[i] * arr[j]); auto it = occ.find(check); // Check if the third number is present // in the map and it is not equal to any // other two elements and also check if // this triplet is not counted already // using their indexes if (check != arr[i] && check != arr[j] && it != occ.end() && it->second > i && it->second > j) count++; } } } // Return number of triplets return count; } // Drivers code int main() { int arr[] = { 1, 4, 6, 2, 3, 8 }; int n = sizeof(arr) / sizeof(arr[0]); int m = 24; cout << countTriplets(arr, n, m); return 0; }",linear,quadratic "// C++ program to count of pairs with equal // elements in an array. #include using namespace std; // Return the number of pairs with equal // values. int countPairs(int arr[], int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } // Driven Program int main() { int arr[] = { 1, 1, 2 }; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0; }",constant,quadratic "// C++ program to count of index pairs with // equal elements in an array. #include using namespace std; // Return the number of pairs with equal // values. int countPairs(int arr[], int n) { unordered_map mp; // Finding frequency of each number. for (int i = 0; i < n; i++) mp[arr[i]]++; // Calculating pairs of each value. int ans = 0; for (auto it=mp.begin(); it!=mp.end(); it++) { int count = it->second; ans += (count * (count - 1))/2; } return ans; } // Driven Program int main() { int arr[] = {1, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0; }",linear,linear "/* A C++ program to answer queries to check whether the substrings are palindrome or not efficiently */ #include using namespace std; #define p 101 #define MOD 1000000007 // Structure to represent a query. A query consists // of (L, R) and we have to answer whether the substring // from index-L to R is a palindrome or not struct Query { int L, R; }; // A function to check if a string str is palindrome // in the range L to R bool isPalindrome(string str, int L, int R) { // Keep comparing characters while they are same while (R > L) if (str[L++] != str[R--]) return (false); return (true); } // A Function to find pow (base, exponent) % MOD // in log (exponent) time unsigned long long int modPow( unsigned long long int base, unsigned long long int exponent) { if (exponent == 0) return 1; if (exponent == 1) return base; unsigned long long int temp = modPow(base, exponent / 2); if (exponent % 2 == 0) return (temp % MOD * temp % MOD) % MOD; else return (((temp % MOD * temp % MOD) % MOD) * base % MOD) % MOD; } // A Function to calculate Modulo Multiplicative Inverse of 'n' unsigned long long int findMMI(unsigned long long int n) { return modPow(n, MOD - 2); } // A Function to calculate the prefix hash void computePrefixHash( string str, int n, unsigned long long int prefix[], unsigned long long int power[]) { prefix[0] = 0; prefix[1] = str[0]; for (int i = 2; i <= n; i++) prefix[i] = (prefix[i - 1] % MOD + (str[i - 1] % MOD * power[i - 1] % MOD) % MOD) % MOD; return; } // A Function to calculate the suffix hash // Suffix hash is nothing but the prefix hash of // the reversed string void computeSuffixHash( string str, int n, unsigned long long int suffix[], unsigned long long int power[]) { suffix[0] = 0; suffix[1] = str[n - 1]; for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) suffix[j] = (suffix[j - 1] % MOD + (str[i] % MOD * power[j - 1] % MOD) % MOD) % MOD; return; } // A Function to answer the Queries void queryResults(string str, Query q[], int m, int n, unsigned long long int prefix[], unsigned long long int suffix[], unsigned long long int power[]) { for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] unsigned long long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] unsigned long long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then // the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) printf(""The Substring [%d %d] is a "" ""palindrome\n"", L, R); else printf(""The Substring [%d %d] is not a "" ""palindrome\n"", L, R); } else printf(""The Substring [%d %d] is not a "" ""palindrome\n"", L, R); } return; } // A Dynamic Programming Based Approach to compute the // powers of 101 void computePowers(unsigned long long int power[], int n) { // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) power[i] = (power[i - 1] % MOD * p % MOD) % MOD; return; } /* Driver program to test above function */ int main() { string str = ""abaaabaaaba""; int n = str.length(); // A Table to store the powers of 101 unsigned long long int power[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values unsigned long long int prefix[n + 1], suffix[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query q[] = { { 0, 10 }, { 5, 8 }, { 2, 5 }, { 5, 9 } }; int m = sizeof(q) / sizeof(q[0]); queryResults(str, q, m, n, prefix, suffix, power); return (0); }",linear,quadratic "// C++ program to finds out smallest range that includes // elements from each of the given sorted lists. #include using namespace std; // array for storing the current index of list i int ptr[501]; // This function takes an k sorted lists in the form of // 2D array as an argument. It finds out smallest range // that includes elements from each of the k lists. void findSmallestRange(vector >& arr, int N, int K) { int i, minval, maxval, minrange, minel, maxel, flag, minind; // initializing to 0 index; for (i = 0; i <= K; i++) ptr[i] = 0; minrange = INT_MAX; while (1) { // for maintaining the index of list containing the // minimum element minind = -1; minval = INT_MAX; maxval = INT_MIN; flag = 0; // iterating over all the list for (i = 0; i < K; i++) { // if every element of list[i] is traversed then // break the loop if (ptr[i] == N) { flag = 1; break; } // find minimum value among all the list // elements pointing by the ptr[] array if (ptr[i] < N && arr[i][ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i][ptr[i]]; } // find maximum value among all the list // elements pointing by the ptr[] array if (ptr[i] < N && arr[i][ptr[i]] > maxval) { maxval = arr[i][ptr[i]]; } } // if any list exhaust we will not get any better // answer, so break the while loop if (flag) break; ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } printf(""The smallest range is [%d, %d]\n"", minel, maxel); } // Driver's code int main() { vector > arr = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int K = arr.size(); int N = arr[0].size(); // Function call findSmallestRange(arr, N, K); return 0; } // This code is contributed by Aditya Krishna Namdeo",linear,linear "// C++ program to finds out smallest range that includes // elements from each of the given sorted lists. #include using namespace std; #define N 5 // A min heap node struct MinHeapNode { // The element to be stored int element; // index of the list from which the element is taken int i; // index of the next element to be picked from list int j; }; // Prototype of a utility function to swap two min heap // nodes void swap(MinHeapNode* x, MinHeapNode* y); // A class for Min Heap class MinHeap { // pointer to array of elements in heap MinHeapNode* harr; // size of min heap int heap_size; public: // Constructor: creates a min heap of given size MinHeap(MinHeapNode a[], int size); // to heapify a subtree with root at given index void MinHeapify(int); // to get index of left child of node at index i int left(int i) { return (2 * i + 1); } // to get index of right child of node at index i int right(int i) { return (2 * i + 2); } // to get the root MinHeapNode getMin() { return harr[0]; } // to replace root with new node x and heapify() new // root void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); } }; // Constructor: Builds a heap from a // given array a[] of given size MinHeap::MinHeap(MinHeapNode a[], int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; } } // A recursive method to heapify a subtree with root at // given index. This method assumes that the subtrees // are already heapified void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l].element < harr[i].element) smallest = l; if (r < heap_size && harr[r].element < harr[smallest].element) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); MinHeapify(smallest); } } // This function takes an K sorted lists in the form of // 2D array as an argument. It finds out smallest range // that includes elements from each of the k lists. void findSmallestRange(int arr[][N], int K) { // Create a min heap with k heap nodes. Every heap node // has first element of an list int range = INT_MAX; int min = INT_MAX, max = INT_MIN; int start, end; MinHeapNode* harr = new MinHeapNode[K]; for (int i = 0; i < K; i++) { // Store the first element harr[i].element = arr[i][0]; // index of list harr[i].i = i; // Index of next element to be stored // from list harr[i].j = 1; // store max element if (harr[i].element > max) max = harr[i].element; } // Create the heap MinHeap hp(harr, K); // Now one by one get the minimum element from min // heap and replace it with next element of its list while (1) { // Get the minimum element and store it in output MinHeapNode root = hp.getMin(); // update min min = hp.getMin().element; // update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will replace current // root of heap. The next element belongs to same // list as the current root. if (root.j < N) { root.element = arr[root.i][root.j]; root.j += 1; // update max element if (root.element > max) max = root.element; } // break if we have reached end of any list else break; // Replace root with next element of list hp.replaceMin(root); } cout << ""The smallest range is "" << ""["" << start << "" "" << end << ""]"" << endl; ; } // Driver's code int main() { int arr[][N] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int K = sizeof(arr) / sizeof(arr[0]); // Function call findSmallestRange(arr, K); return 0; }",linear,linear "// C++ program to find total count of an element // in a range #include using namespace std; // Returns count of element in arr[left-1..right-1] int findFrequency(int arr[], int n, int left, int right, int element) { int count = 0; for (int i=left-1; i<=right; ++i) if (arr[i] == element) ++count; return count; } // Driver Code int main() { int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Print frequency of 2 from position 1 to 6 cout << ""Frequency of 2 from 1 to 6 = "" << findFrequency(arr, n, 1, 6, 2) << endl; // Print frequency of 8 from position 4 to 9 cout << ""Frequency of 8 from 4 to 9 = "" << findFrequency(arr, n, 4, 9, 8); return 0; }",constant,linear "// C++ program for above implementation #include using namespace std; // Function to count numbers to be added int countNum(int arr[], int n) { int count = 0; // Sort the array sort(arr, arr + n); // Check if elements are consecutive // or not. If not, update count for (int i = 0; i < n - 1; i++) if (arr[i] != arr[i+1] && arr[i] != arr[i + 1] - 1) count += arr[i + 1] - arr[i] - 1; return count; } // Drivers code int main() { int arr[] = { 3, 5, 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countNum(arr, n) << endl; return 0; }",constant,nlogn "// C++ program for above implementation #include using namespace std; // Function to count numbers to be added int countNum(int arr[], int n) { unordered_set s; int count = 0, maxm = INT_MIN, minm = INT_MAX; // Make a hash of elements // and store minimum and maximum element for (int i = 0; i < n; i++) { s.insert(arr[i]); if (arr[i] < minm) minm = arr[i]; if (arr[i] > maxm) maxm = arr[i]; } // Traverse all elements from minimum // to maximum and count if it is not // in the hash for (int i = minm; i <= maxm; i++) if (s.find(arr[i]) == s.end()) count++; return count; } // Drivers code int main() { int arr[] = { 3, 5, 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countNum(arr, n) << endl; return 0; }",constant,linear "// C++ program to calculate sum of lengths of subarrays // of distinct elements. #include using namespace std; // Returns sum of lengths of all subarrays with distinct // elements. int sumoflength(int arr[], int n) { // For maintaining distinct elements. unordered_set s; // Initialize ending point and result int j = 0, ans = 0; // Fix starting point for (int i=0; i using namespace std; // Function to calculate distinct sub-array int countDistictSubarray(int arr[], int n) { // Count distinct elements in whole array unordered_map vis; for (int i = 0; i < n; ++i) vis[arr[i]] = 1; int k = vis.size(); // Reset the container by removing all elements vis.clear(); // Use sliding window concept to find // count of subarrays having k distinct // elements. int ans = 0, right = 0, window = 0; for (int left = 0; left < n; ++left) { while (right < n && window < k) { ++vis[ arr[right] ]; if (vis[ arr[right] ] == 1) ++window; ++right; } // If window size equals to array distinct // element size, then update answer if (window == k) ans += (n - right + 1); // Decrease the frequency of previous element // for next sliding window --vis[ arr[left] ]; // If frequency is zero then decrease the // window size if (vis[ arr[left] ] == 0) --window; } return ans; } // Driver code int main() { int arr[] = {2, 1, 3, 2, 3}; int n = sizeof(arr) / sizeof(arr[0]); cout << countDistictSubarray(arr, n) <<""n""; return 0; }",linear,linear "// Make a set of maximum elements from two // arrays A[] and B[] #include using namespace std; void maximizeTheFirstArray(int A[], int B[], int n) { // Create copies of A[] and B[] and sort // the copies in descending order. vector temp1(A, A+n); vector temp2(B, B+n); sort(temp1.begin(), temp1.end(), greater()); sort(temp2.begin(), temp2.end(), greater()); // Put maximum n distinct elements of // both sorted arrays in a map. unordered_map m; int i = 0, j = 0; while (m.size() < n) { if (temp1[i] >= temp2[j]) { m[temp1[i]]++; i++; } else { m[temp2[j]]++; j++; } } // Copy elements of A[] to that // are present in hash m. vector res; for (int i = 0; i < n; i++) if (m.find(A[i]) != m.end()) res.push_back(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for (int i = 0; i < n; i++) if (m.find(B[i]) != m.end() && m[B[i]] == 1) res.push_back(B[i]); // print result for (int i = 0; i < n; i++) cout << res[i] << "" ""; } // driver program int main() { int A[] = { 9, 7, 2, 3, 6 }; int B[] = { 7, 4, 8, 0, 1 }; int n = sizeof(A) / sizeof(A[0]); maximizeTheFirstArray(A, B, n); return 0; }",linear,nlogn "// C++ implementation to find the maximum number // of chocolates to be distributed equally among // k students #include using namespace std; // function to find the maximum number of chocolates // to be distributed equally among k students int maxNumOfChocolates(int arr[], int n, int k) { // unordered_map 'um' implemented as // hash table unordered_map um; // 'sum[]' to store cumulative sum, where // sum[i] = sum(arr[0]+..arr[i]) int sum[n], curr_rem; // to store sum of sub-array having maximum sum int maxSum = 0; // building up 'sum[]' sum[0] = arr[0]; for (int i = 1; i < n; i++) sum[i] = sum[i - 1] + arr[i]; // traversing 'sum[]' for (int i = 0; i < n; i++) { // finding current remainder curr_rem = sum[i] % k; // if true then sum(0..i) is divisible // by k if (curr_rem == 0) { // update 'maxSum' if (maxSum < sum[i]) maxSum = sum[i]; } // if value 'curr_rem' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(curr_rem) == um.end()) um[curr_rem] = i; else // if true, then update 'max' if (maxSum < (sum[i] - sum[um[curr_rem]])) maxSum = sum[i] - sum[um[curr_rem]]; } // required maximum number of chocolates to be // distributed equally among 'k' students return (maxSum / k); } // Driver program to test above int main() { int arr[] = { 2, 7, 6, 1, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << ""Maximum number of chocolates: "" << maxNumOfChocolates(arr, n, k); return 0; }",linear,linear "// C++ program to print n-th number in Recaman's // sequence #include using namespace std; // Prints first n terms of Recaman sequence int recaman(int n) { // Create an array to store terms int arr[n]; // First term of the sequence is always 0 arr[0] = 0; printf(""%d, "", arr[0]); // Fill remaining terms using recursive // formula. for (int i=1; i< n; i++) { int curr = arr[i-1] - i; int j; for (j = 0; j < i; j++) { // If arr[i-1] - i is negative or // already exists. if ((arr[j] == curr) || curr < 0) { curr = arr[i-1] + i; break; } } arr[i] = curr; printf(""%d, "", arr[i]); } } // Driver code int main() { int n = 17; recaman(n); return 0; }",linear,quadratic "// C++ program to print n-th number in Recaman's // sequence #include using namespace std; // Prints first n terms of Recaman sequence void recaman(int n) { if (n <= 0) return; // Print first term and store it in a hash printf(""%d, "", 0); unordered_set s; s.insert(0); // Print remaining terms using recursive // formula. int prev = 0; for (int i=1; i< n; i++) { int curr = prev - i; // If arr[i-1] - i is negative or // already exists. if (curr < 0 || s.find(curr) != s.end()) curr = prev + i; s.insert(curr); printf(""%d, "", curr); prev = curr; } } // Driver code int main() { int n = 17; recaman(n); return 0; }",linear,linear "#include using namespace std; void findFibSubset(int arr[], int n) { for (int i = 0; i < n; i++) { int fact1 = 5 * pow(arr[i], 2) + 4; int fact2 = 5 * pow(arr[i], 2) - 4; if ((int)pow((int)pow(fact1, 0.5), 2) == fact1 || (int)pow((int)pow(fact2, 0.5), 2) == fact2) cout << arr[i] << "" ""; } } int main() { int arr[] = { 4, 2, 8, 5, 20, 1, 40, 13, 23 }; int n = 9; findFibSubset(arr, n); } // This code is contributed by garg28harsh.",constant,linear "// C++ program to find largest Fibonacci subset #include using namespace std; // Prints largest subset of an array whose // all elements are fibonacci numbers void findFibSubset(int arr[], int n) { // Find maximum element in arr[] int max = *std::max_element(arr, arr+n); // Generate all Fibonacci numbers till // max and store them in hash. int a = 0, b = 1; unordered_set hash; hash.insert(a); hash.insert(b); while (b < max) { int c = a + b; a = b; b = c; hash.insert(b); } // Npw iterate through all numbers and // quickly check for Fibonacci using // hash. for (int i=0; i using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node* left, *right; }; string inorder(Node* node, unordered_map& m) { if (!node) return """"; string str = ""(""; str += inorder(node->left, m); str += to_string(node->data); str += inorder(node->right, m); str += "")""; // Subtree already present (Note that we use // unordered_map instead of unordered_set // because we want to print multiple duplicates // only once, consider example of 4 in above // subtree, it should be printed only once. if (m[str] == 1) cout << node->data << "" ""; m[str]++; return str; } // Wrapper over inorder() void printAllDups(Node* root) { unordered_map m; inorder(root, m); } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver code int main() { Node* root = NULL; root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->right->left = newNode(2); root->right->left->left = newNode(4); root->right->right = newNode(4); printAllDups(root); return 0; }",quadratic,quadratic "// A brute force approach based CPP program to // find if there is a rectangle with 1 as corners. #include using namespace std; // Returns true if there is a rectangle with // 1 as corners. bool isRectangle(const vector >& m) { // finding row and column size int rows = m.size(); if (rows == 0) return false; int columns = m[0].size(); // scanning the matrix for (int y1 = 0; y1 < rows; y1++) for (int x1 = 0; x1 < columns; x1++) // if any index found 1 then try // for all rectangles if (m[y1][x1] == 1) for (int y2 = y1 + 1; y2 < rows; y2++) for (int x2 = x1 + 1; x2 < columns; x2++) if (m[y1][x2] == 1 && m[y2][x1] == 1 && m[y2][x2] == 1) return true; return false; } // Driver code int main() { vector > mat = { { 1, 0, 0, 1, 0 }, { 0, 0, 1, 0, 1 }, { 0, 0, 0, 1, 0 }, { 1, 0, 1, 0, 1 } }; if (isRectangle(mat)) cout << ""Yes""; else cout << ""No""; }",constant,quadratic "// An efficient approach based CPP program to // find if there is a rectangle with 1 as // corners. #include using namespace std; // Returns true if there is a rectangle with // 1 as corners. bool isRectangle(const vector >& matrix) { // finding row and column size int rows = matrix.size(); if (rows == 0) return false; int columns = matrix[0].size(); // map for storing the index of combination of 2 1's unordered_map > table; // scanning from top to bottom line by line for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns - 1; ++j) { for (int k = j + 1; k < columns; ++k) { // if found two 1's in a column if (matrix[i][j] == 1 && matrix[i][k] == 1) { // check if there exists 1's in same // row previously then return true // we don't need to check (j, k) pair // and again (k, j) pair because we always // store pair in ascending order and similarly // check in ascending order, i.e. j always less // than k. if (table.find(j) != table.end() && table[j].find(k) != table[j].end()) return true; // store the indexes in hashset table[j].insert(k); } } } } return false; } // Driver code int main() { vector > mat = { { 1, 0, 0, 1, 0 }, { 0, 1, 1, 1, 1 }, { 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 0 } }; if (isRectangle(mat)) cout << ""Yes""; else cout << ""No""; } // This code is improved by Gautam Agrawal",quadratic,quadratic "// C++ implementation comes from: // https://github.com/MichaelWehar/FourCornersProblem // Written by Niteesh Kumar and Michael Wehar // References: // [1] F. Mráz, D. Prusa, and M. Wehar. // Two-dimensional Pattern Matching against // Basic Picture Languages. CIAA 2019. // [2] D. Prusa and M. Wehar. Complexity of // Searching for 2 by 2 Submatrices in Boolean // Matrices. DLT 2020. #include using namespace std; bool searchForRectangle(int rows, int cols, vector> mat) { // Make sure that matrix is non-trivial if (rows < 2 || cols < 2) { return false; } // Create map int num_of_keys; map> adjsList; if (rows >= cols) { // Row-wise num_of_keys = rows; // Convert each row into vector of col indexes for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (mat[i][j]) { adjsList[i].push_back(j); } } } } else { // Col-wise num_of_keys = cols; // Convert each col into vector of row indexes for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (mat[i][j]) { adjsList[j].push_back(i); } } } } // Search for a rectangle whose four corners are 1's map, int> pairs; for (int i = 0; i < num_of_keys; i++) { vector values = adjsList[i]; int size = values.size(); for (int j = 0; j < size - 1; j++) { for (int k = j + 1; k < size; k++) { pair temp = make_pair(values[j], values[k]); if (pairs.find(temp) != pairs.end()) { return true; } else { pairs[temp] = i; } } } } return false; } // Driver code int main() { vector > mat = { { 1, 0, 0, 1, 0 }, { 0, 1, 1, 1, 1 }, { 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 0 } }; if (searchForRectangle(4, 5, mat)) cout << ""Yes""; else cout << ""No""; }",quadratic,quadratic "// CPP program for finding maximum area possible // of a rectangle #include using namespace std; // function for finding max area int findArea(int arr[], int n) { // sort array in non-increasing order sort(arr, arr + n, greater()); // Initialize two sides of rectangle int dimension[2] = { 0, 0 }; // traverse through array for (int i = 0, j = 0; i < n - 1 && j < 2; i++) // if any element occurs twice // store that as dimension if (arr[i] == arr[i + 1]) dimension[j++] = arr[i++]; // return the product of dimensions return (dimension[0] * dimension[1]); } // driver function int main() { int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findArea(arr, n); return 0; }",constant,nlogn "// CPP program for finding maximum area possible // of a rectangle #include using namespace std; // function for finding max area int findArea(int arr[], int n) { unordered_set s; // traverse through array int first = 0, second = 0; for (int i = 0; i < n; i++) { // If this is first occurrence of arr[i], // simply insert and continue if (s.find(arr[i]) == s.end()) { s.insert(arr[i]); continue; } // If this is second (or more) occurrence, // update first and second maximum values. if (arr[i] > first) { second = first; first = arr[i]; } else if (arr[i] > second) second = arr[i]; } // return the product of dimensions return (first * second); } // driver function int main() { int arr[] = { 4, 2, 1, 4, 6, 6, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findArea(arr, n); return 0; }",linear,linear "// C++ implementation to find length of longest // strict bitonic subsequence #include using namespace std; // function to find length of longest // strict bitonic subsequence int longLenStrictBitonicSub(int arr[], int n) { // hash table to map the array element with the // length of the longest subsequence of which // it is a part of and is the last/first element of // that subsequence unordered_map inc, dcr; // arrays to store the length of increasing and // decreasing subsequences which end at them // or start from them int len_inc[n], len_dcr[n]; // to store the length of longest strict // bitonic subsequence int longLen = 0; // traverse the array elements // from left to right for (int i=0; i=0; i--) { // initialize current length // for element arr[i] as 0 int len = 0; // if 'arr[i]-1' is in 'dcr' if (dcr.find(arr[i]-1) != dcr.end()) len = dcr[arr[i]-1]; // update arr[i] subsequence length in 'dcr' // and in len_dcr[] dcr[arr[i]] = len_dcr[i] = len + 1; } // calculating the length of all the strict // bitonic subsequence for (int i=0; i using namespace std; // Returns last seen element in arr[] int lastSeenElement(int a[], int n) { // Store last occurrence index of // every element unordered_map hash; for (int i = 0; i < n; i++) hash[a[i]] = i; // Find an element in hash with minimum // index value int res_ind = INT_MAX, res; for (auto x : hash) { if (x.second < res_ind) { res_ind = x.second; res = x.first; } } return res; } // driver program int main() { int a[] = { 2, 1, 2, 2, 4, 1 }; int n = sizeof(a) / sizeof(a[0]); cout << lastSeenElement(a, n); return 0; }",linear,linear "// A complete working C++ program to // demonstrate all insertion methods // on Linked List #include using namespace std; // A linked list node class Node { public: int data; Node *next; }; // Given a reference (pointer to pointer) // to the head of a list and an int, inserts // a new node on the front of the list. void push(Node** head_ref, int new_data) { // 1. allocate node Node* new_node = new Node(); // 2. put in the data new_node->data = new_data; // 3. Make next of new node as head new_node->next = (*head_ref); // 4. move the head to point // to the new node (*head_ref) = new_node; } // Given a node prev_node, insert a new // node after the given prev_node void insertAfter(Node* prev_node, int new_data) { // 1. check if the given prev_node // is NULL if (prev_node == NULL) { cout<<""The given previous node cannot be NULL""; return; } // 2. allocate new node Node* new_node = new Node(); // 3. put in the data new_node->data = new_data; // 4. Make next of new node // as next of prev_node new_node->next = prev_node->next; // 5. move the next of prev_node // as new_node prev_node->next = new_node; } // Given a reference (pointer to pointer) // to the head of a list and an int, // appends a new node at the end void append(Node** head_ref, int new_data) { // 1. allocate node Node* new_node = new Node(); //used in step 5 Node *last = *head_ref; // 2. put in the data new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) { last = last->next; } /* 6. Change the next of last node */ last->next = new_node; return; } // This function prints contents of // linked list starting from head void printList(Node *node) { while (node != NULL) { cout<<"" ""<data; node = node->next; } } // Driver code int main() { // Start with the empty list Node* head = NULL; // Insert 6. So linked list becomes 6->NULL append(&head, 6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So // linked list becomes 1->7->6->4->NULL append(&head, 4); // Insert 8, after 7. So linked // list becomes 1->7->8->6->4->NULL insertAfter(head->next, 8); cout<<""Created Linked list is: ""; printList(head); return 0; } // This code is contributed by rathbhupendra, arkajyotibasak",constant,linear "// Alternate method to declare the class // in order to minimize the // memory allocation work #include using namespace std; class node { public: int data; node* next; // A constructor is called here node(int value) { // It automatically assigns the // value to the data data = value; // Next pointer is pointed to NULL next = NULL; } }; // Function to insert an element // at head position void insertathead(node*& head, int val) { node* n = new node(val); n->next = head; head = n; } // Function to insert a element // at a specified position void insertafter(node* head, int key, int val) { node* n = new node(val); if (key == head->data) { n->next = head->next; head->next = n; return; } node* temp = head; while (temp->data != key) { temp = temp->next; if (temp == NULL) { return; } } n->next = temp->next; temp->next = n; } // Function to insert an // element at the end void insertattail(node*& head, int val) { node* n = new node(val); if (head == NULL) { head = n; return; } node* temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = n; } // Function to print the // singly linked list void print(node*& head) { node* temp = head; while (temp != NULL) { cout << temp->data << "" -> ""; temp = temp->next; } cout << ""NULL"" << endl; } // Main function int main() { // Declaring an empty linked list node* head = NULL; insertathead(head, 1); insertathead(head, 2); cout << ""After insertion at head: ""; print(head); cout << endl; insertattail(head, 4); insertattail(head, 5); cout << ""After insertion at tail: ""; print(head); cout << endl; insertafter(head, 1, 2); insertafter(head, 5, 6); cout << ""After insertion at a given position: ""; print(head); cout << endl; return 0; } // contributed by divyanshmishra101010",constant,linear "// A complete working C++ program to delete // a node in a linked list at a given position #include using namespace std; // A linked list node class Node { public: int data; Node* next; }; // Given a reference (pointer to pointer) to // the head of a list and an int inserts a // new node on the front of the list. void push(Node** head_ref, int new_data) { Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } // Given a reference (pointer to pointer) to // the head of a list and a position, deletes // the node at the given position void deleteNode(Node** head_ref, int position) { // If linked list is empty if (*head_ref == NULL) return; // Store head node Node* temp = *head_ref; // If head needs to be removed if (position == 0) { // Change head *head_ref = temp->next; // Free old head free(temp); return; } // Find previous node of the node to be deleted for (int i = 0; temp != NULL && i < position - 1; i++) temp = temp->next; // If position is more than number of nodes if (temp == NULL || temp->next == NULL) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node* next = temp->next->next; // Unlink the node from linked list free(temp->next); // Free memory // Unlink the deleted node from list temp->next = next; } // This function prints contents of linked // list starting from the given node void printList(Node* node) { while (node != NULL) { cout << node->data << "" ""; node = node->next; } } // Driver code int main() { // Start with the empty list Node* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); push(&head, 8); cout << ""Created Linked List: ""; printList(head); deleteNode(&head, 4); cout << ""\nLinked List after Deletion at position 4: ""; printList(head); return 0; } // This code is contributed by premsai2030",constant,linear "// C++ program to delete a linked list #include using namespace std; /* Link list node */ class Node { public: int data; Node* next; }; /* Function to delete the entire linked list */ void deleteList(Node** head_ref) { /* deref head_ref to get the real head */ Node* current = *head_ref; Node* next = NULL; while (current != NULL) { next = current->next; free(current); current = next; } /* deref head_ref to affect the real head back in the caller. */ *head_ref = NULL; } /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Driver code*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->12->1->4->1 */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); cout << ""Deleting linked list""; deleteList(&head); cout << ""\nLinked list deleted""; } // This is code is contributed by rathbhupendra",constant,linear "// Iterative C++ program to find length // or count of nodes in a linked list #include using namespace std; /* Link list node */ class Node { public: int data; Node* next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Counts no. of nodes in linked list */ int getCount(Node* head) { int count = 0; // Initialize count Node* current = head; // Initialize current while (current != NULL) { count++; current = current->next; } return count; } /* Driver code*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); // Function call cout << ""count of nodes is "" << getCount(head); return 0; } // This is code is contributed by rathbhupendra",constant,linear "// Recursive C++ program to find length // or count of nodes in a linked list #include using namespace std; /* Link list node */ class Node { public: int data; Node* next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Recursively count number of nodes in linked list */ int getCount(Node* head) { // Base Case if (head == NULL) { return 0; } // Count this node plus the rest of the list else { return 1 + getCount(head->next); } } /* Driver program to test count function*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ cout << ""Count of nodes is "" << getCount(head); return 0; } // This is code is contributed by rajsanghavi9",linear,linear "// Tail Recursive C++ program to find length // or count of nodes in a linked list #include using namespace std; /* Link list node */ class Node { public: int data; Node* next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // A tail recursive function to count the nodes of a linked // list // default value of the count is used as zero int getCount(Node* head, int count = 0) { // base case if (head == NULL) return count; // move the pointer to next node and increase the count return getCount(head->next, count + 1); } /* Driver code*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); // Function call cout << ""Count of nodes is "" << getCount(head); return 0; } // This is code is contributed by Abhijeet Kumar",constant,linear "// Iterative C++ program to search // an element in linked list #include using namespace std; /* Link list node */ class Node { public: int key; Node* next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(Node** head_ref, int new_key) { /* allocate node */ Node* new_node = new Node(); /* put in the key */ new_node->key = new_key; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Checks whether the value x is present in linked list */ bool search(Node* head, int x) { Node* current = head; // Initialize current while (current != NULL) { if (current->key == x) return true; current = current->next; } return false; } /* Driver code*/ int main() { /* Start with the empty list */ Node* head = NULL; int x = 21; /* Use push() to construct below list 14->21->11->30->10 */ push(&head, 10); push(&head, 30); push(&head, 11); push(&head, 21); push(&head, 14); // Function call search(head, 21) ? cout << ""Yes"" : cout << ""No""; return 0; } // This is code is contributed by rathbhupendra",constant,linear "// Recursive C++ program to search // an element in linked list #include using namespace std; /* Link list node */ struct Node { int key; struct Node* next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(struct Node** head_ref, int new_key) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the key */ new_node->key = new_key; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Checks whether the value x is present in linked list */ bool search(struct Node* head, int x) { // Base case if (head == NULL) return false; // If key is present in current node, return true if (head->key == x) return true; // Recur for remaining list return search(head->next, x); } /* Driver code*/ int main() { /* Start with the empty list */ struct Node* head = NULL; int x = 21; /* Use push() to construct below list 14->21->11->30->10 */ push(&head, 10); push(&head, 30); push(&head, 11); push(&head, 21); push(&head, 14); // Function call search(head, 21) ? cout << ""Yes"" : cout << ""No""; return 0; } // This code is contributed by SHUBHAMSINGH10",linear,linear "// C++ program to find n'th node in linked list // using recursion #include using namespace std; /* Linked list node */ struct Node { int data; struct Node* next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Takes head pointer of the linked list and index as arguments and return data at index. (Don't use another variable)*/ int GetNth(struct Node* head, int n) { // if length of the list is less // than the given index, return -1 if (head == NULL) return -1; // if n equal to 0 return node->data if (n == 0) return head->data; // increase head to next pointer // n - 1: decrease the number of recursions until n = 0 return GetNth(head->next, n - 1); } /* Driver code*/ int main() { /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->12->1->4->1 */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); /* Check the count function */ printf(""Element at index 3 is %d"", GetNth(head, 3)); getchar(); } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// C++ program to find N'th node from end #include using namespace std; /* Link list node */ struct Node { int data; struct Node* next; }; /* Function to get the Nth node from the last of a linked list*/ void printNthFromLast(struct Node* head, int N) { int len = 0, i; struct Node* temp = head; // Count the number of nodes in Linked List while (temp != NULL) { temp = temp->next; len++; } // Check if value of N is not // more than length of the linked list if (len < N) return; temp = head; // Get the (len-N+1)th node from the beginning for (i = 1; i < len - N + 1; i++) temp = temp->next; cout << temp->data; return; } void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // Driver's Code int main() { /* Start with the empty list */ struct Node* head = NULL; // create linked 35->15->4->20 push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 35); // Function call printNthFromLast(head, 4); return 0; }",constant,linear "// C++ program to find n-th node // from the end of the linked list. #include using namespace std; struct node { int data; node* next; node(int val) { data = val; next = NULL; } }; struct llist { node* head; llist() { head = NULL; } // insert operation at the beginning of the list. void insertAtBegin(int val) { node* newNode = new node(val); newNode->next = head; head = newNode; } // finding n-th node from the end. void nthFromEnd(int n) { // create two pointers main_ptr and ref_ptr // initially pointing to head. node* main_ptr = head; node* ref_ptr = head; // if list is empty, return if (head == NULL) { cout << ""List is empty"" << endl; return; } // move ref_ptr to the n-th node from beginning. for (int i = 1; i < n; i++) { ref_ptr = ref_ptr->next; if (ref_ptr == NULL) { cout << n << "" is greater than no. of nodes in "" ""the list"" << endl; return; } } // move ref_ptr and main_ptr by one node until // ref_ptr reaches end of the list. while (ref_ptr != NULL && ref_ptr->next != NULL) { ref_ptr = ref_ptr->next; main_ptr = main_ptr->next; } cout << ""Node no. "" << n << "" from end is: "" << main_ptr->data << endl; } void displaylist() { node* temp = head; while (temp != NULL) { cout << temp->data << ""->""; temp = temp->next; } cout << ""NULL"" << endl; } }; // Driver's code int main() { llist ll; ll.insertAtBegin(20); ll.insertAtBegin(4); ll.insertAtBegin(15); ll.insertAtBegin(35); ll.displaylist(); // Function call ll.nthFromEnd(4); return 0; } // This code is contributed by sandeepkrsuman.",constant,linear "// C++ program for the above approach #include using namespace std; class Node{ public: int data; Node *next; }; class NodeOperation{ public: // Function to add a new node void pushNode(class Node** head_ref,int data_val){ // Allocate node class Node *new_node = new Node(); // Put in the data new_node->data = data_val; // Link the old list off the new node new_node->next = *head_ref; // move the head to point to the new node *head_ref = new_node; } // A utility function to print a given linked list void printNode(class Node *head){ while(head != NULL){ cout <data << ""->""; head = head->next; } cout << ""NULL"" << endl; } void printMiddle(class Node *head){ struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } cout << ""The middle element is ["" << slow_ptr->data << ""]"" << endl; } } }; // Driver Code int main(){ class Node *head = NULL; class NodeOperation *temp = new NodeOperation(); for(int i=5; i>0; i--){ temp->pushNode(&head, i); temp->printNode(head); temp->printMiddle(head); } return 0; }",constant,linear "#include using namespace std; // Link list node struct node { int data; struct node* next; }; // Function to get the middle of // the linked list void printMiddle(struct node* head) { int count = 0; struct node* mid = head; while (head != NULL) { // Update mid, when 'count' // is odd number if (count & 1) mid = mid->next; ++count; head = head->next; } // If empty list is provided if (mid != NULL) printf(""The middle element is [%d]\n\n"", mid->data); } void push(struct node** head_ref, int new_data) { // Allocate node struct node* new_node = (struct node*)malloc( sizeof(struct node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node; } // A utility function to print // a given linked list void printList(struct node* ptr) { while (ptr != NULL) { printf(""%d->"", ptr->data); ptr = ptr->next; } printf(""NULL\n""); } // Driver code int main() { // Start with the empty list struct node* head = NULL; int i; for(i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; } // This code is contributed by ac121102",constant,linear "// C++ program to count occurrences in a linked list #include using namespace std; /* Link list node */ class Node { public: int data; Node* next; }; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ int count(Node* head, int search_for) { Node* current = head; int count = 0; while (current != NULL) { if (current->data == search_for) count++; current = current->next; } return count; } /* Driver program to test count function*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ cout << ""count of 1 is "" << count(head, 1); return 0; } // This is code is contributed by rathbhupendra",constant,linear "// C++ program to count occurrences in a linked list using // recursion #include using namespace std; /* Link list node */ struct Node { int data; struct Node* next; }; // global variable for counting frequency of // given element k int frequency = 0; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Counts the no. of occurrences of a node (search_for) in a linked list (head)*/ int count(struct Node* head, int key) { if (head == NULL) return frequency; if (head->data == key) frequency++; return count(head->next, key); } /* Driver program to test count function*/ int main() { /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct below list 1->2->1->3->1 */ push(&head, 1); push(&head, 3); push(&head, 1); push(&head, 2); push(&head, 1); /* Check the count function */ cout << ""count of 1 is "" << count(head, 1); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// C++ program to count number of nodes // in loop in a linked list if loop is // present #include using namespace std; /* Link list node */ struct Node { int data; struct Node* next; }; // Returns count of nodes present in loop. int countNodes(struct Node* n) { int res = 1; struct Node* temp = n; while (temp->next != n) { res++; temp = temp->next; } return res; } /* This function detects and counts loop nodes in the list. If loop is not there then returns 0 */ int countNodesinLoop(struct Node* list) { struct Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; /* If slow_p and fast_p meet at some point then there is a loop */ if (slow_p == fast_p) return countNodes(slow_p); } /* Return 0 to indicate that there is no loop*/ return 0; } struct Node* newNode(int key) { struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp; } // Driver Code int main() { struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); /* Create a loop for testing */ head->next->next->next->next->next = head->next; cout << countNodesinLoop(head) << endl; return 0; } // This code is contributed by SHUBHAMSINGH10",constant,linear "#include using namespace std; class Node { public: int data; Node(int d) { data = d; } Node* ptr; }; // Function to check if the linked list // is palindrome or not bool isPalin(Node* head) { // Temp pointer Node* slow = head; // Declare a stack stack s; // Push all elements of the list // to the stack while (slow != NULL) { s.push(slow->data); // Move ahead slow = slow->ptr; } // Iterate in the list again and // check by popping from the stack while (head != NULL) { // Get the top most element int i = s.top(); // Pop the element s.pop(); // Check if data is not // same as popped element if (head->data != i) { return false; } // Move ahead head = head->ptr; } return true; } // Driver Code int main() { // Addition of linked list Node one = Node(1); Node two = Node(2); Node three = Node(3); Node four = Node(2); Node five = Node(1); // Initialize the next pointer // of every current pointer five.ptr = NULL; one.ptr = &two two.ptr = &three three.ptr = &four four.ptr = &five Node* temp = &one // Call function to check palindrome or not int result = isPalin(&one); if (result == 1) cout << ""isPalindrome is true\n""; else cout << ""isPalindrome is false\n""; return 0; } // This code has been contributed by Striver",linear,linear "// C++ program to check if a linked list is palindrome #include using namespace std; // Link list node struct Node { char data; struct Node* next; }; void reverse(struct Node**); bool compareLists(struct Node*, struct Node*); // Function to check if given linked list is // palindrome or not bool isPalindrome(struct Node* head) { struct Node *slow_ptr = head, *fast_ptr = head; struct Node *second_half, *prev_of_slow_ptr = head; // To handle odd size list struct Node* midnode = NULL; // initialize result bool res = true; if (head != NULL && head->next != NULL) { // Get the middle of the list. Move slow_ptr by 1 // and fast_ptr by 2, slow_ptr will have the middle // node while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; // We need previous of the slow_ptr for // linked lists with odd elements prev_of_slow_ptr = slow_ptr; slow_ptr = slow_ptr->next; } // fast_ptr would become NULL when there // are even elements in list. And not NULL // for odd elements. We need to skip the // middle node for odd case and store it // somewhere so that we can restore the // original list if (fast_ptr != NULL) { midnode = slow_ptr; slow_ptr = slow_ptr->next; } // Now reverse the second half and // compare it with first half second_half = slow_ptr; // NULL terminate first half prev_of_slow_ptr->next = NULL; // Reverse the second half reverse(&second_half); // compare res = compareLists(head, second_half); // Construct the original list back reverse( &second_half); // Reverse the second half again // If there was a mid node (odd size case) // which was not part of either first half // or second half. if (midnode != NULL) { prev_of_slow_ptr->next = midnode; midnode->next = second_half; } else prev_of_slow_ptr->next = second_half; } return res; } // Function to reverse the linked list // Note that this function may change // the head void reverse(struct Node** head_ref) { struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; } // Function to check if two input // lists have same data bool compareLists(struct Node* head1, struct Node* head2) { struct Node* temp1 = head1; struct Node* temp2 = head2; while (temp1 && temp2) { if (temp1->data == temp2->data) { temp1 = temp1->next; temp2 = temp2->next; } else return 0; } // Both are empty return 1 if (temp1 == NULL && temp2 == NULL) return 1; // Will reach here when one is NULL // and other is not return 0; } // Push a node to linked list. Note // that this function changes the head void push(struct Node** head_ref, char new_data) { // Allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list of the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node; } // A utility function to print a given linked list void printList(struct Node* ptr) { while (ptr != NULL) { cout << ptr->data << ""->""; ptr = ptr->next; } cout << ""NULL"" << ""\n""; } // Driver code int main() { // Start with the empty list struct Node* head = NULL; char str[] = ""abacaba""; int i; for (i = 0; str[i] != '\0'; i++) { push(&head, str[i]); } isPalindrome(head) ? cout << ""Is Palindrome"" << ""\n\n"" : cout << ""Not Palindrome"" << ""\n\n""; return 0; } // This code is contributed by Shivani",constant,linear "// Recursive program to check if a given linked list is // palindrome #include using namespace std; /* Link list node */ struct node { char data; struct node* next; }; // Initial parameters to this function are &head and head bool isPalindromeUtil(struct node** left, struct node* right) { /* stop recursion when right becomes NULL */ if (right == NULL) return true; /* If sub-list is not palindrome then no need to check for current left and right, return false */ bool isp = isPalindromeUtil(left, right->next); if (isp == false) return false; /* Check values at current left and right */ bool isp1 = (right->data == (*left)->data); /* Move left to next node */ *left = (*left)->next; return isp1; } // A wrapper over isPalindromeUtil() bool isPalindrome(struct node* head) { return isPalindromeUtil(&head, head); } /* Push a node to linked list. Note that this function changes the head */ void push(struct node** head_ref, char new_data) { /* allocate node */ struct node* new_node = (struct node*)malloc(sizeof(struct node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // A utility function to print a given linked list void printList(struct node* ptr) { while (ptr != NULL) { cout << ptr->data << ""->""; ptr = ptr->next; } cout << ""NULL\n""; } /* Driver program to test above function*/ int main() { /* Start with the empty list */ struct node* head = NULL; char str[] = ""abacaba""; int i; for (i = 0; str[i] != '\0'; i++) { push(&head, str[i]); } isPalindrome(head) ? cout << ""Is Palindrome\n\n"" : cout << ""Not Palindrome\n\n""; return 0; } // this code is contributed by shivanisinghss2110",linear,linear "/* C++ Program to remove duplicates in an unsorted linked list */ #include using namespace std; /* A linked list node */ struct Node { int data; struct Node* next; }; // Utility function to create a new Node struct Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->next = NULL; return temp; } /* Function to remove duplicates from a unsorted linked list */ void removeDuplicates(struct Node* start) { struct Node *ptr1, *ptr2, *dup; ptr1 = start; /* Pick elements one by one */ while (ptr1 != NULL && ptr1->next != NULL) { ptr2 = ptr1; /* Compare the picked element with rest of the elements */ while (ptr2->next != NULL) { /* If duplicate then delete it */ if (ptr1->data == ptr2->next->data) { /* sequence of steps is important here */ dup = ptr2->next; ptr2->next = ptr2->next->next; delete (dup); } else /* This is tricky */ ptr2 = ptr2->next; } ptr1 = ptr1->next; } } /* Function to print nodes in a given linked list */ void printList(struct Node* node) { while (node != NULL) { printf(""%d "", node->data); node = node->next; } } // Driver code int main() { /* The constructed linked list is: 10->12->11->11->12->11->10*/ struct Node* start = newNode(10); start->next = newNode(12); start->next->next = newNode(11); start->next->next->next = newNode(11); start->next->next->next->next = newNode(12); start->next->next->next->next->next = newNode(11); start->next->next->next->next->next->next = newNode(10); printf(""Linked list before removing duplicates ""); printList(start); removeDuplicates(start); printf(""\nLinked list after removing duplicates ""); printList(start); return 0; }",constant,quadratic "/* This program swaps the nodes of linked list rather than swapping the field from the nodes.*/ #include using namespace std; /* A linked list node */ class Node { public: int data; Node* next; }; /* Function to swap nodes x and y in linked list by changing links */ void swapNodes(Node** head_ref, int x, int y) { // Nothing to do if x and y are same if (x == y) return; // Search for x (keep track of prevX and CurrX Node *prevX = NULL, *currX = *head_ref; while (currX && currX->data != x) { prevX = currX; currX = currX->next; } // Search for y (keep track of prevY and CurrY Node *prevY = NULL, *currY = *head_ref; while (currY && currY->data != y) { prevY = currY; currY = currY->next; } // If either x or y is not present, nothing to do if (currX == NULL || currY == NULL) return; // If x is not head of linked list if (prevX != NULL) prevX->next = currY; else // Else make y as new head *head_ref = currY; // If y is not head of linked list if (prevY != NULL) prevY->next = currX; else // Else make x as new head *head_ref = currX; // Swap next pointers Node* temp = currY->next; currY->next = currX->next; currX->next = temp; } /* Function to add a node at the beginning of List */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data << "" ""; node = node->next; } } /* Driver program to test above function */ int main() { Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5->6->7 */ push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << ""Linked list before calling swapNodes() ""; printList(start); swapNodes(&start, 4, 3); cout << ""\nLinked list after calling swapNodes() ""; printList(start); return 0; } // This is code is contributed by rathbhupendra",constant,linear "// C++ program to swap two given nodes of a linked list #include using namespace std; // A linked list node class class Node { public: int data; class Node* next; // constructor Node(int val, Node* next) : data(val) , next(next) { } // print list from this to last till null void printList() { Node* node = this; while (node != NULL) { cout << node->data << "" ""; node = node->next; } cout << endl; } }; // Function to add a node at the beginning of List void push(Node** head_ref, int new_data) { // allocate node (*head_ref) = new Node(new_data, *head_ref); } void swap(Node*& a, Node*& b) { Node* temp = a; a = b; b = temp; } void swapNodes(Node** head_ref, int x, int y) { // Nothing to do if x and y are same if (x == y) return; Node **a = NULL, **b = NULL; // search for x and y in the linked list // and store their pointer in a and b while (*head_ref) { if ((*head_ref)->data == x) a = head_ref; else if ((*head_ref)->data == y) b = head_ref; head_ref = &((*head_ref)->next); } // if we have found both a and b // in the linked list swap current // pointer and next pointer of these if (a && b) { swap(*a, *b); swap(((*a)->next), ((*b)->next)); } } // Driver code int main() { Node* start = NULL; // The constructed linked list is: // 1->2->3->4->5->6->7 push(&start, 7); push(&start, 6); push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << ""Linked list before calling swapNodes() ""; start->printList(); swapNodes(&start, 6, 1); cout << ""Linked list after calling swapNodes() ""; start->printList(); } // This code is contributed by Sania Kumari Gupta // (kriSania804)",constant,linear "/* CPP Program to move last element to front in a given linked list */ #include using namespace std; /* A linked list node */ class Node { public: int data; Node* next; }; /* We are using a double pointer head_ref here because we change head of the linked list inside this function.*/ void moveToFront(Node** head_ref) { /* If linked list is empty, or it contains only one node, then nothing needs to be done, simply return */ if (*head_ref == NULL || (*head_ref)->next == NULL) return; /* Initialize second last and last pointers */ Node* secLast = NULL; Node* last = *head_ref; /*After this loop secLast contains address of second last node and last contains address of last node in Linked List */ while (last->next != NULL) { secLast = last; last = last->next; } /* Set the next of second last as NULL */ secLast->next = NULL; /* Set next of last as head node */ last->next = *head_ref; /* Change the head pointer to point to last node now */ *head_ref = last; } /* UTILITY FUNCTIONS */ /* Function to add a node at the beginning of Linked List */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data << "" ""; node = node->next; } } // Driver's code int main() { Node* start = NULL; /* The constructed linked list is: 1->2->3->4->5 */ push(&start, 5); push(&start, 4); push(&start, 3); push(&start, 2); push(&start, 1); cout << ""Linked list before moving last to front\n""; printList(start); // Function call moveToFront(&start); cout << ""\nLinked list after removing last to front\n""; printList(start); return 0; } // This code is contributed by rathbhupendra",constant,linear "#include using namespace std; /* Link list node */ struct Node { int data; Node* next; }; void push(Node** head_ref, int new_data); /*This solution uses the temporary dummy to build up the result list */ Node* sortedIntersect(Node* a, Node* b) { Node dummy; Node* tail = &dummy dummy.next = NULL; /* Once one or the other list runs out -- we're done */ while (a != NULL && b != NULL) { if (a->data == b->data) { push((&tail->next), a->data); tail = tail->next; a = a->next; b = b->next; } /* advance the smaller list */ else if (a->data < b->data) a = a->next; else b = b->next; } return (dummy.next); } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the linked list */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = (Node*)malloc( sizeof(Node)); /* put in the data */ new_node->data = new_data; /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data <<"" ""; node = node->next; } } /* Driver program to test above functions*/ int main() { /* Start with the empty lists */ Node* a = NULL; Node* b = NULL; Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); cout<<""Linked list containing common items of a & b \n""; printList(intersect); }",linear,linear "// C++ program to implement above approach #include /* Link list node */ struct Node { int data; struct Node* next; }; void push(struct Node** head_ref, int new_data); /* This solution uses the local reference */ struct Node* sortedIntersect( struct Node* a, struct Node* b) { struct Node* result = NULL; struct Node** lastPtrRef = &result /* Advance comparing the first nodes in both lists. When one or the other list runs out, we're done. */ while (a != NULL && b != NULL) { if (a->data == b->data) { /* found a node for the intersection */ push(lastPtrRef, a->data); lastPtrRef = &((*lastPtrRef)->next); a = a->next; b = b->next; } else if (a->data < b->data) a = a->next; /* advance the smaller list */ else b = b->next; } return (result); } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the linked list */ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(struct Node* node) { while (node != NULL) { printf(""%d "", node->data); node = node->next; } } /* Driver program to test above functions*/ int main() { /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); printf(""\n Linked list containing common items of a & b \n ""); printList(intersect); return 0; } //This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear "#include using namespace std; // Link list node struct Node { int data; struct Node* next; }; struct Node* sortedIntersect(struct Node* a, struct Node* b) { // base case if (a == NULL || b == NULL) return NULL; /* If both lists are non-empty */ /* Advance the smaller list and call recursively */ if (a->data < b->data) return sortedIntersect(a->next, b); if (a->data > b->data) return sortedIntersect(a, b->next); // Below lines are executed only // when a->data == b->data struct Node* temp = (struct Node*)malloc( sizeof(struct Node)); temp->data = a->data; // Advance both lists and call recursively temp->next = sortedIntersect(a->next, b->next); return temp; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the linked list */ void push(struct Node** head_ref, int new_data) { /* Allocate node */ struct Node* new_node = (struct Node*)malloc( sizeof(struct Node)); /* Put in the data */ new_node->data = new_data; /* Link the old list of the new node */ new_node->next = (*head_ref); /* Move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(struct Node* node) { while (node != NULL) { cout << "" "" << node->data; node = node->next; } } // Driver code int main() { /* Start with the empty lists */ struct Node* a = NULL; struct Node* b = NULL; struct Node* intersect = NULL; /* Let us create the first sorted linked list to test the functions Created linked list will be 1->2->3->4->5->6 */ push(&a, 6); push(&a, 5); push(&a, 4); push(&a, 3); push(&a, 2); push(&a, 1); /* Let us create the second sorted linked list Created linked list will be 2->4->6->8 */ push(&b, 8); push(&b, 6); push(&b, 4); push(&b, 2); /* Find the intersection two linked lists */ intersect = sortedIntersect(a, b); cout << ""\n Linked list containing "" << ""common items of a & b \n ""; printList(intersect); return 0; } // This code is contributed by shivanisinghss2110",linear,linear "// C++ program to implement above approach #include using namespace std; // Link list node struct Node { int data; struct Node* next; }; void printList(struct Node* node) { while (node != NULL) { cout << "" "" << node->data; node = node->next; } } void append(struct Node** head_ref, int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } vector intersection(struct Node* tmp1, struct Node* tmp2, int k) { vector res(k); unordered_set set; while (tmp1 != NULL) { set.insert(tmp1->data); tmp1 = tmp1->next; } int cnt = 0; while (tmp2 != NULL) { if (set.find(tmp2->data) != set.end()) { res[cnt] = tmp2->data; cnt++; } tmp2 = tmp2->next; } return res; } // Driver code int main() { struct Node* ll = NULL; struct Node* ll1 = NULL; append(≪,7); append(≪,6); append(≪,5); append(≪,4); append(≪,3); append(≪,2); append(≪,1); append(≪,0); append(&ll1,7); append(&ll1,6); append(&ll1,5); append(&ll1,4); append(&ll1,3); append(&ll1,12); append(&ll1,0); append(&ll1,9); vector arr= intersection(ll, ll1, 6); for (int i :arr) cout << i << ""\n""; return 0; } // This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear "// C++ program for Quick Sort on Singly Linked List #include #include using namespace std; /* a node of the singly linked list */ struct Node { int data; struct Node* next; }; /* A utility function to insert a node at the beginning of * linked list */ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* A utility function to print linked list */ void printList(struct Node* node) { while (node != NULL) { printf(""%d "", node->data); node = node->next; } printf(""\n""); } // Returns the last node of the list struct Node* getTail(struct Node* cur) { while (cur != NULL && cur->next != NULL) cur = cur->next; return cur; } // Partitions the list taking the last element as the pivot struct Node* partition(struct Node* head, struct Node* end, struct Node** newHead, struct Node** newEnd) { struct Node* pivot = end; struct Node *prev = NULL, *cur = head, *tail = pivot; // During partition, both the head and end of the list // might change which is updated in the newHead and // newEnd variables while (cur != pivot) { if (cur->data < pivot->data) { // First node that has a value less than the // pivot - becomes the new head if ((*newHead) == NULL) (*newHead) = cur; prev = cur; cur = cur->next; } else // If cur node is greater than pivot { // Move cur node to next of tail, and change // tail if (prev) prev->next = cur->next; struct Node* tmp = cur->next; cur->next = NULL; tail->next = cur; tail = cur; cur = tmp; } } // If the pivot data is the smallest element in the // current list, pivot becomes the head if ((*newHead) == NULL) (*newHead) = pivot; // Update newEnd to the current last node (*newEnd) = tail; // Return the pivot node return pivot; } // here the sorting happens exclusive of the end node struct Node* quickSortRecur(struct Node* head, struct Node* end) { // base condition if (!head || head == end) return head; Node *newHead = NULL, *newEnd = NULL; // Partition the list, newHead and newEnd will be // updated by the partition function struct Node* pivot = partition(head, end, &newHead, &newEnd); // If pivot is the smallest element - no need to recur // for the left part. if (newHead != pivot) { // Set the node before the pivot node as NULL struct Node* tmp = newHead; while (tmp->next != pivot) tmp = tmp->next; tmp->next = NULL; // Recur for the list before pivot newHead = quickSortRecur(newHead, tmp); // Change next of last node of the left half to // pivot tmp = getTail(newHead); tmp->next = pivot; } // Recur for the list after the pivot element pivot->next = quickSortRecur(pivot->next, newEnd); return newHead; } // The main function for quick sort. This is a wrapper over // recursive function quickSortRecur() void quickSort(struct Node** headRef) { (*headRef) = quickSortRecur(*headRef, getTail(*headRef)); return; } // Driver's code int main() { struct Node* a = NULL; push(&a, 5); push(&a, 20); push(&a, 4); push(&a, 3); push(&a, 30); cout << ""Linked List before sorting \n""; printList(a); // Function call quickSort(&a); cout << ""Linked List after sorting \n""; printList(a); return 0; }",linear,nlogn "// C++ program to segregate even and // odd nodes in a Linked List #include using namespace std; /* a node of the singly linked list */ class Node { public: int data; Node *next; }; void segregateEvenOdd(Node **head_ref) { Node *end = *head_ref; Node *prev = NULL; Node *curr = *head_ref; /* Get pointer to the last node */ while (end->next != NULL) end = end->next; Node *new_end = end; /* Consider all odd nodes before the first even node and move then after end */ while (curr->data % 2 != 0 && curr != end) { new_end->next = curr; curr = curr->next; new_end->next->next = NULL; new_end = new_end->next; } // 10->8->17->17->15 /* Do following steps only if there is any even node */ if (curr->data%2 == 0) { /* Change the head pointer to point to first even node */ *head_ref = curr; /* now current points to the first even node */ while (curr != end) { if ( (curr->data) % 2 == 0 ) { prev = curr; curr = curr->next; } else { /* break the link between prev and current */ prev->next = curr->next; /* Make next of curr as NULL */ curr->next = NULL; /* Move curr to end */ new_end->next = curr; /* make curr as new end of list */ new_end = curr; /* Update current pointer to next of the moved node */ curr = prev->next; } } } /* We must have prev set before executing lines following this statement */ else prev = curr; /* If there are more than 1 odd nodes and end of original list is odd then move this node to end to maintain same order of odd numbers in modified list */ if (new_end != end && (end->data) % 2 != 0) { prev->next = end->next; end->next = NULL; new_end->next = end; } return; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node *node) { while (node != NULL) { cout << node->data <<"" ""; node = node->next; } } /* Driver code*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create a sample linked list as following 0->2->4->6->8->10->11 */ push(&head, 11); push(&head, 10); push(&head, 8); push(&head, 6); push(&head, 4); push(&head, 2); push(&head, 0); cout << ""Original Linked list ""; printList(head); segregateEvenOdd(&head); cout << ""\nModified Linked list ""; printList(head); return 0; } // This code is contributed by rathbhupendra",constant,linear "// CPP program to segregate even and odd nodes in a // Linked List #include using namespace std; /* a node of the singly linked list */ struct Node { int data; struct Node* next; }; // Function to segregate even and odd nodes. void segregateEvenOdd(struct Node** head_ref) { // Starting node of list having even values. Node* evenStart = NULL; // Ending node of even values list. Node* evenEnd = NULL; // Starting node of odd values list. Node* oddStart = NULL; // Ending node of odd values list. Node* oddEnd = NULL; // Node to traverse the list. Node* currNode = *head_ref; while (currNode != NULL) { int val = currNode->data; // If current value is even, add it to even values // list. if (val % 2 == 0) { if (evenStart == NULL) { evenStart = currNode; evenEnd = evenStart; } else { evenEnd->next = currNode; evenEnd = evenEnd->next; } } // If current value is odd, add it to odd values // list. else { if (oddStart == NULL) { oddStart = currNode; oddEnd = oddStart; } else { oddEnd->next = currNode; oddEnd = oddEnd->next; } } // Move head pointer one step in forward direction currNode = currNode->next; } // If either odd list or even list is empty, no change // is required as all elements are either even or odd. if (oddStart == NULL || evenStart == NULL) return; // Add odd list after even list. evenEnd->next = oddStart; oddEnd->next = NULL; // Modify head pointer to starting of even list. *head_ref = evenStart; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data << "" ""; node = node->next; } } /* Driver program to test above functions*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create a sample linked list as following 0->1->4->6->9->10->11 */ push(&head, 11); push(&head, 10); push(&head, 9); push(&head, 6); push(&head, 4); push(&head, 1); push(&head, 0); cout << ""Original Linked list"" << endl; printList(head); segregateEvenOdd(&head); cout << endl << ""Modified Linked list "" << endl; printList(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,linear "// Iterative C++ program to reverse a linked list #include using namespace std; /* Link list node */ struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; } }; struct LinkedList { Node* head; LinkedList() { head = NULL; } /* Function to reverse the linked list */ void reverse() { // Initialize current, previous and next pointers Node* current = head; Node *prev = NULL, *next = NULL; while (current != NULL) { // Store next next = current->next; // Reverse current node's pointer current->next = prev; // Move pointers one position ahead. prev = current; current = next; } head = prev; } /* Function to print linked list */ void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << "" ""; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; } }; /* Driver code*/ int main() { /* Start with the empty list */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); cout << ""Given linked list\n""; ll.print(); ll.reverse(); cout << ""\nReversed linked list \n""; ll.print(); return 0; }",constant,linear "// Recursive C++ program to reverse // a linked list #include using namespace std; /* Link list node */ struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; } }; struct LinkedList { Node* head; LinkedList() { head = NULL; } Node* reverse(Node* head) { if (head == NULL || head->next == NULL) return head; /* reverse the rest list and put the first element at the end */ Node* rest = reverse(head->next); head->next->next = head; /* tricky step -- see the diagram */ head->next = NULL; /* fix the head pointer */ return rest; } /* Function to print linked list */ void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << "" ""; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; } }; /* Driver program to test above function*/ int main() { /* Start with the empty list */ LinkedList ll; ll.push(20); ll.push(4); ll.push(15); ll.push(85); cout << ""Given linked list\n""; ll.print(); ll.head = ll.reverse(ll.head); cout << ""\nReversed linked list \n""; ll.print(); return 0; }",linear,linear "// A simple and tail recursive C++ program to reverse // a linked list #include using namespace std; struct Node { int data; struct Node* next; }; void reverseUtil(Node* curr, Node* prev, Node** head); // This function mainly calls reverseUtil() // with prev as NULL void reverse(Node** head) { if (!head) return; reverseUtil(*head, NULL, head); } // A simple and tail-recursive function to reverse // a linked list. prev is passed as NULL initially. void reverseUtil(Node* curr, Node* prev, Node** head) { /* If last node mark it head*/ if (!curr->next) { *head = curr; /* Update next to prev node */ curr->next = prev; return; } /* Save curr->next node for recursive call */ Node* next = curr->next; /* and update next ..*/ curr->next = prev; reverseUtil(next, curr, head); } // A utility function to create a new node Node* newNode(int key) { Node* temp = new Node; temp->data = key; temp->next = NULL; return temp; } // A utility function to print a linked list void printlist(Node* head) { while (head != NULL) { cout << head->data << "" ""; head = head->next; } cout << endl; } // Driver code int main() { Node* head1 = newNode(1); head1->next = newNode(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); head1->next->next->next->next = newNode(5); head1->next->next->next->next->next = newNode(6); head1->next->next->next->next->next->next = newNode(7); head1->next->next->next->next->next->next->next = newNode(8); cout << ""Given linked list\n""; printlist(head1); reverse(&head1); cout << ""Reversed linked list\n""; printlist(head1); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// C++ program for above approach #include #include using namespace std; // Create a class Node to enter values and address in the // list class Node { public: int data; Node* next; }; // Function to reverse the linked list void reverseLL(Node** head) { // Create a stack ""s"" of Node type stack s; Node* temp = *head; while (temp->next != NULL) { // Push all the nodes in to stack s.push(temp); temp = temp->next; } *head = temp; while (!s.empty()) { // Store the top value of stack in list temp->next = s.top(); // Pop the value from stack s.pop(); // update the next pointer in the list temp = temp->next; } temp->next = NULL; } // Function to Display the elements in List void printlist(Node* temp) { while (temp != NULL) { cout << temp->data << "" ""; temp = temp->next; } } // Program to insert back of the linked list void insert_back(Node** head, int value) { // we have used insertion at back method to enter values // in the list.(eg: head->1->2->3->4->Null) Node* temp = new Node(); temp->data = value; temp->next = NULL; // If *head equals to NULL if (*head == NULL) { *head = temp; return; } else { Node* last_node = *head; while (last_node->next != NULL) last_node = last_node->next; last_node->next = temp; return; } } // Driver Code int main() { Node* head = NULL; insert_back(&head, 1); insert_back(&head, 2); insert_back(&head, 3); insert_back(&head, 4); cout << ""Given linked list\n""; printlist(head); reverseLL(&head); cout << ""\nReversed linked list\n""; printlist(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// C++ program to delete a given key from // linked list. #include using namespace std; // Structure for a node class Node { public: int data; Node* next; }; // Function to insert a node at the // beginning of a Circular linked list void push(Node** head_ref, int data) { // Create a new node and make head // as next of it. Node* ptr1 = new Node(); ptr1->data = data; ptr1->next = *head_ref; // If linked list is not NULL then // set the next of last node if (*head_ref != NULL) { // Find the node before head and // update next of it. Node* temp = *head_ref; while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else // For the first node ptr1->next = ptr1; *head_ref = ptr1; } // Function to print nodes in a given // circular linked list void printList(Node* head) { Node* temp = head; if (head != NULL) { do { cout << temp->data << "" ""; temp = temp->next; } while (temp != head); } cout << endl; } // Function to delete a given node // from the list void deleteNode(Node** head, int key) { // If linked list is empty if (*head == NULL) return; // If the list contains only a // single node if ((*head)->data == key && (*head)->next == *head) { free(*head); *head = NULL; return; } Node *last = *head, *d; // If head is to be deleted if ((*head)->data == key) { // Find the last node of the list while (last->next != *head) last = last->next; // Point last node to the next of // head i.e. the second node // of the list last->next = (*head)->next; free(*head); *head = last->next; return; } // Either the node to be deleted is // not found or the end of list // is not reached while (last->next != *head && last->next->data != key) { last = last->next; } // If node to be deleted was found if (last->next->data == key) { d = last->next; last->next = d->next; free(d); } else cout << ""no such keyfound""; } // Driver code int main() { // Initialize lists as empty Node* head = NULL; // Created linked list will be // 2->5->7->8->10 push(&head, 2); push(&head, 5); push(&head, 7); push(&head, 8); push(&head, 10); cout << ""List Before Deletion: ""; printList(head); deleteNode(&head, 7); cout << ""List After Deletion: ""; printList(head); return 0; }",constant,linear "// C++ program to check if linked list is circular #include using namespace std; /* Link list Node */ struct Node { int data; struct Node* next; }; /* This function returns true if given linked list is circular, else false. */ bool isCircular(struct Node *head) { // An empty linked list is circular if (head == NULL) return true; // Next of head struct Node *node = head->next; // This loop would stop in both cases (1) If // Circular (2) Not circular while (node != NULL && node != head) node = node->next; // If loop stopped because of circular // condition return (node == head); } // Utility function to create a new node. Node *newNode(int data) { struct Node *temp = new Node; temp->data = data; temp->next = NULL; return temp; } // Driver's code int main() { /* Start with the empty list */ struct Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); isCircular(head)? cout << ""Yes\n"" : cout << ""No\n"" ; // Making linked list circular head->next->next->next->next = head; isCircular(head)? cout << ""Yes\n"" : cout << ""No\n"" ; return 0; }",constant,linear "// C++ Program to convert a Binary Tree // to a Circular Doubly Linked List #include using namespace std; // To represents a node of a Binary Tree struct Node { struct Node *left, *right; int data; }; // A function that appends rightList at the end // of leftList. Node* concatenate(Node* leftList, Node* rightList) { // If either of the list is empty // then return the other list if (leftList == NULL) return rightList; if (rightList == NULL) return leftList; // Store the last Node of left List Node* leftLast = leftList->left; // Store the last Node of right List Node* rightLast = rightList->left; // Connect the last node of Left List // with the first Node of the right List leftLast->right = rightList; rightList->left = leftLast; // Left of first node points to // the last node in the list leftList->left = rightLast; // Right of last node refers to the first // node of the List rightLast->right = leftList; return leftList; } // Function converts a tree to a circular Linked List // and then returns the head of the Linked List Node* bTreeToCList(Node* root) { if (root == NULL) return NULL; // Recursively convert left and right subtrees Node* left = bTreeToCList(root->left); Node* right = bTreeToCList(root->right); // Make a circular linked list of single node // (or root). To do so, make the right and // left pointers of this node point to itself root->left = root->right = root; // Step 1 (concatenate the left list with the list // with single node, i.e., current node) // Step 2 (concatenate the returned list with the // right List) return concatenate(concatenate(left, root), right); } // Display Circular Link List void displayCList(Node* head) { cout << ""Circular Linked List is :\n""; Node* itr = head; do { cout << itr->data << "" ""; itr = itr->right; } while (head != itr); cout << ""\n""; } // Create a new Node and return its address Node* newNode(int data) { Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver Program to test above function int main() { Node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); Node* head = bTreeToCList(root); displayCList(head); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",logn,linear "// A C++ program for in-place conversion of Binary Tree to // CDLL #include using namespace std; /* A binary tree node has - data , left and right pointers */ struct Node { int data; Node* left; Node* right; }; // A utility function that converts given binary tree to // a doubly linked list // root --> the root of the binary tree // head --> head of the created doubly linked list Node* BTree2DoublyLinkedList(Node* root, Node** head) { // Base case if (root == NULL) return root; // Initialize previously visited node as NULL. This is // static so that the same value is accessible in all // recursive calls static Node* prev = NULL; // Recursively convert left subtree BTree2DoublyLinkedList(root->left, head); // Now convert this node if (prev == NULL) *head = root; else { root->left = prev; prev->right = root; } prev = root; // Finally convert right subtree BTree2DoublyLinkedList(root->right, head); return prev; } // A simple recursive function to convert a given Binary // tree to Circular Doubly Linked List using a utility // function root --> Root of Binary Tree tail --> Pointer to // tail node of created circular doubly linked list Node* BTree2CircularDoublyLinkedList(Node* root) { Node* head = NULL; Node* tail = BTree2DoublyLinkedList(root, &head); // make the changes to convert a DLL to CDLL tail->right = head; head->left = tail; // return the head of the created CDLL return head; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ Node* newNode(int data) { Node* new_node = new Node; new_node->data = data; new_node->left = new_node->right = NULL; return (new_node); } /* Function to print nodes in a given circular doubly linked * list */ void printList(Node* head) { if (head == NULL) return; Node* ptr = head; do { cout << ptr->data << "" ""; ptr = ptr->right; } while (ptr != head); } /* Driver program to test above functions*/ int main() { // Let us create the tree shown in above diagram Node* root = newNode(10); root->left = newNode(12); root->right = newNode(15); root->left->left = newNode(25); root->left->right = newNode(30); root->right->left = newNode(36); // Convert to DLL Node* head = BTree2CircularDoublyLinkedList(root); // Print the converted list printList(head); return 0; } // This code was contributed by Abhijeet // Kumar(abhijeet19403)",logn,linear "// C++ program to count number of nodes in a circular // linked list. #include using namespace std; /*structure for a node*/ struct Node { int data; Node* next; Node(int x) { data = x; next = NULL; } }; /* Function to insert a node at the beginning of a Circular linked list */ struct Node* push(struct Node* last, int data) { if (last == NULL) { struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Assigning the data. temp->data = data; last = temp; // Note : list was empty. We link single node // to itself. temp->next = last; return last; } // Creating a node dynamically. struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Assigning the data. temp->data = data; // Adjusting the links. temp->next = last->next; last->next = temp; return last; } /* Function to count nodes in a given Circular linked list */ int countNodes(Node* head) { Node* temp = head; int result = 0; if (head != NULL) { do { temp = temp->next; result++; } while (temp != head); } return result; } /* Driver program to test above functions */ int main() { /* Initialize lists as empty */ Node* head = NULL; head = push(head, 12); head = push(head, 56); head = push(head, 2); head = push(head, 11); cout << countNodes(head); return 0; } // This code is contributed by anushikaseth",constant,linear "// C++ program to delete a given key from // linked list. #include using namespace std; // Structure for a node class Node { public: int data; Node* next; }; // Function to insert a node at the // beginning of a Circular linked list void push(Node** head_ref, int data) { // Create a new node and make head // as next of it. Node* ptr1 = new Node(); ptr1->data = data; ptr1->next = *head_ref; // If linked list is not NULL then // set the next of last node if (*head_ref != NULL) { // Find the node before head and // update next of it. Node* temp = *head_ref; while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else // For the first node ptr1->next = ptr1; *head_ref = ptr1; } // Function to print nodes in a given // circular linked list void printList(Node* head) { Node* temp = head; if (head != NULL) { do { cout << temp->data << "" ""; temp = temp->next; } while (temp != head); } cout << endl; } // Function to delete a given node // from the list void deleteNode(Node** head, int key) { // If linked list is empty if (*head == NULL) return; // If the list contains only a // single node if ((*head)->data == key && (*head)->next == *head) { free(*head); *head = NULL; return; } Node *last = *head, *d; // If head is to be deleted if ((*head)->data == key) { // Find the last node of the list while (last->next != *head) last = last->next; // Point last node to the next of // head i.e. the second node // of the list last->next = (*head)->next; free(*head); *head = last->next; return; } // Either the node to be deleted is // not found or the end of list // is not reached while (last->next != *head && last->next->data != key) { last = last->next; } // If node to be deleted was found if (last->next->data == key) { d = last->next; last->next = d->next; free(d); } else cout << ""no such keyfound""; } // Driver code int main() { // Initialize lists as empty Node* head = NULL; // Created linked list will be // 2->5->7->8->10 push(&head, 2); push(&head, 5); push(&head, 7); push(&head, 8); push(&head, 10); cout << ""List Before Deletion: ""; printList(head); deleteNode(&head, 7); cout << ""List After Deletion: ""; printList(head); return 0; }",constant,linear "// C++ implementation of De-queue using circular // array #include using namespace std; // Maximum size of array or Dequeue #define MAX 100 // A structure to represent a Deque class Deque { int arr[MAX]; int front; int rear; int size; public: Deque(int size) { front = -1; rear = 0; this->size = size; } // Operations on Deque: void insertfront(int key); void insertrear(int key); void deletefront(); void deleterear(); bool isFull(); bool isEmpty(); int getFront(); int getRear(); }; // Checks whether Deque is full or not. bool Deque::isFull() { return ((front == 0 && rear == size - 1) || front == rear + 1); } // Checks whether Deque is empty or not. bool Deque::isEmpty() { return (front == -1); } // Inserts an element at front void Deque::insertfront(int key) { // check whether Deque if full or not if (isFull()) { cout << ""Overflow\n"" << endl; return; } // If queue is initially empty if (front == -1) { front = 0; rear = 0; } // front is at first position of queue else if (front == 0) front = size - 1; else // decrement front end by '1' front = front - 1; // insert current element into Deque arr[front] = key; } // function to inset element at rear end // of Deque. void Deque ::insertrear(int key) { if (isFull()) { cout << "" Overflow\n "" << endl; return; } // If queue is initially empty if (front == -1) { front = 0; rear = 0; } // rear is at last position of queue else if (rear == size - 1) rear = 0; // increment rear end by '1' else rear = rear + 1; // insert current element into Deque arr[rear] = key; } // Deletes element at front end of Deque void Deque ::deletefront() { // check whether Deque is empty or not if (isEmpty()) { cout << ""Queue Underflow\n"" << endl; return; } // Deque has only one element if (front == rear) { front = -1; rear = -1; } else // back to initial position if (front == size - 1) front = 0; else // increment front by '1' to remove current // front value from Deque front = front + 1; } // Delete element at rear end of Deque void Deque::deleterear() { if (isEmpty()) { cout << "" Underflow\n"" << endl; return; } // Deque has only one element if (front == rear) { front = -1; rear = -1; } else if (rear == 0) rear = size - 1; else rear = rear - 1; } // Returns front element of Deque int Deque::getFront() { // check whether Deque is empty or not if (isEmpty()) { cout << "" Underflow\n"" << endl; return -1; } return arr[front]; } // function return rear element of Deque int Deque::getRear() { // check whether Deque is empty or not if (isEmpty() || rear < 0) { cout << "" Underflow\n"" << endl; return -1; } return arr[rear]; } // Driver code int main() { Deque dq(5); // Function calls cout << ""Insert element at rear end : 5 \n""; dq.insertrear(5); cout << ""insert element at rear end : 10 \n""; dq.insertrear(10); cout << ""get rear element "" << "" "" << dq.getRear() << endl; dq.deleterear(); cout << ""After delete rear element new rear"" << "" become "" << dq.getRear() << endl; cout << ""inserting element at front end \n""; dq.insertfront(15); cout << ""get front element "" << "" "" << dq.getFront() << endl; dq.deletefront(); cout << ""After delete front element new "" << ""front become "" << dq.getFront() << endl; return 0; }",linear,linear "// CPP program to exchange first and // last node in circular linked list #include using namespace std; struct Node { int data; struct Node* next; }; struct Node* addToEmpty(struct Node* head, int data) { // This function is only for empty list if (head != NULL) return head; // Creating a node dynamically. struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Assigning the data. temp->data = data; head = temp; // Creating the link. head->next = head; return head; } struct Node* addBegin(struct Node* head, int data) { if (head == NULL) return addToEmpty(head, data); struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head->next; head->next = temp; return head; } /* function for traversing the list */ void traverse(struct Node* head) { struct Node* p; // If list is empty, return. if (head == NULL) { cout << ""List is empty."" << endl; return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { cout << p->data << "" ""; p = p->next; } while (p != head); } /* Function to exchange first and last node*/ struct Node* exchangeNodes(struct Node* head) { // If list is of length less than 2 if (head == NULL || head->next == NULL) { return head; } Node* tail = head; // Find pointer to the last node while (tail->next != head) { tail = tail->next; } /* Exchange first and last nodes using head and p */ // temporary variable to store // head data int temp = tail->data; tail->data = head->data; head->data = temp; return head; } // Driven Program int main() { int i; struct Node* head = NULL; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); cout << ""List Before: ""; traverse(head); cout << endl; cout << ""List After: ""; head = exchangeNodes(head); traverse(head); return 0; }",constant,linear "// A complete working C++ program to // demonstrate all insertion methods #include using namespace std; // A linked list node class Node { public: int data; Node* next; Node* prev; }; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */ void push(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head and previous as NULL */ new_node->next = (*head_ref); new_node->prev = NULL; /* 4. change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* 5. move the head to point to the new node */ (*head_ref) = new_node; } /* Given a node as prev_node, insert a new node after the given node */ void insertAfter(Node* prev_node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { cout << ""the given previous node cannot be NULL""; return; } /* 2. allocate new node */ Node* new_node = new Node(); /* 3. put in the data */ new_node->data = new_data; /* 4. Make next of new node as next of prev_node */ new_node->next = prev_node->next; /* 5. Make the next of prev_node as new_node */ prev_node->next = new_node; /* 6. Make prev_node as previous of new_node */ new_node->prev = prev_node; /* 7. Change previous of new_node's next node */ if (new_node->next != NULL) new_node->next->prev = new_node; } /* Given a reference (pointer to pointer) to the head of a DLL and an int, appends a new node at the end */ void append(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); Node* last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { new_node->prev = NULL; *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; /* 7. Make last node as previous of new node */ new_node->prev = last; return; } // This function prints contents of // linked list starting from the given node void printList(Node* node) { Node* last; cout << ""\nTraversal in forward direction \n""; while (node != NULL) { cout << "" "" << node->data << "" ""; last = node; node = node->next; } cout << ""\nTraversal in reverse direction \n""; while (last != NULL) { cout << "" "" << last->data << "" ""; last = last->prev; } } // Driver code int main() { /* Start with the empty list */ Node* head = NULL; // Insert 6. So linked list becomes 6->NULL append(&head, 6); // Insert 7 at the beginning. So // linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. So // linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So linked // list becomes 1->7->6->4->NULL append(&head, 4); // Insert 8, after 7. So linked // list becomes 1->7->8->6->4->NULL insertAfter(head->next, 8); cout << ""Created DLL is: ""; printList(head); return 0; } // This is code is contributed by rathbhupendra",constant,linear "// C++ program for the above approach #include using namespace std; class node { public: node* prev; int data; node* next; node(int value) { // A constructor is called here prev = NULL; // By default previous pointer is // pointed to NULL data = value; // value is assigned to the data next = NULL; // By default next pointer is pointed // to NULL } }; void insert_at_head(node*& head, int value) { node* n = new node(value); n->next = head; if (head != NULL) { head->prev = n; } head = n; } void insert_at_tail(node*& head, int value) { if (head == NULL) { insert_at_head(head, value); return; } node* n = new node(value); node* temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = n; n->prev = temp; } void display(node* head) { node* temp = head; while (temp != NULL) { cout << temp->data << "" --> ""; temp = temp->next; } cout << ""NULL"" << endl; } // Driver code int main() { node* head = NULL; // declaring an empty doubly linked list // Function call insert_at_tail(head, 1); insert_at_tail(head, 2); insert_at_tail(head, 3); insert_at_tail(head, 4); insert_at_tail(head, 5); cout << ""After insertion at tail: ""; display(head); cout << ""After insertion at head: ""; insert_at_head(head, 0); display(head); return 0; }",constant,linear "// C++ program to delete a node from // Doubly Linked List #include using namespace std; /* a node of the doubly linked list */ class Node { public: int data; Node* next; Node* prev; }; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ void deleteNode(Node** head_ref, Node* del) { /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del); return; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the Doubly Linked List */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list of the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data << "" ""; node = node->next; } } /* Driver code*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create the doubly linked list 10<->8<->4<->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << ""Original Linked list ""; printList(head); /* delete nodes from the doubly linked list */ deleteNode(&head, head); /*delete first node*/ deleteNode(&head, head->next); /*delete middle node*/ deleteNode(&head, head->next); /*delete last node*/ /* Modified linked list will be NULL<-8->NULL */ cout << ""\nModified Linked list ""; printList(head); return 0; } // This code is contributed by rathbhupendra",constant,constant "/* C++ program to reverse a doubly linked list */ #include using namespace std; /* Node of the doubly linked list */ class Node { public: int data; Node* next; Node* prev; }; /* Function to reverse a Doubly Linked List */ void reverse(Node** head_ref) { Node* temp = NULL; Node* current = *head_ref; /* swap next and prev for all nodes of doubly linked list */ while (current != NULL) { temp = current->prev; current->prev = current->next; current->next = temp; current = current->prev; } /* Before changing the head, check for the cases like empty list and list with only one node */ if (temp != NULL) *head_ref = temp->prev; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the Doubly Linked List */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list of the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data << "" ""; node = node->next; } } // Driver's code int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << ""Original Linked list"" << endl; printList(head); // Function call reverse(&head); cout << ""\nReversed Linked list"" << endl; printList(head); return 0; } // This code is contributed by rathbhupendra",constant,linear "// C++ program to reverse a doubly linked list #include using namespace std; struct LinkedList { struct Node { int data; Node *next, *prev; Node(int d) { data = d; next = prev = NULL; } }; Node* head = NULL; /* Function to reverse a Doubly Linked List using Stacks */ void reverse() { stack st; Node* temp = head; while (temp != NULL) { st.push(temp->data); temp = temp->next; } // added all the elements sequence wise in the // st temp = head; while (temp != NULL) { temp->data = st.top(); st.pop(); temp = temp->next; } // popped all the elements and the added in the // linked list, // which are in the reversed order-> } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void Push(int new_data) { /* allocate node */ Node* new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list of the new node */ new_node->next = head; /* change prev of head node to new node */ if (head != NULL) { head->prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node* node) { while (node) { cout << node->data << "" ""; node = node->next; } } }; // Driver Code int main() { LinkedList list; /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.Push(2); list.Push(4); list.Push(8); list.Push(10); cout << ""Original linked list "" << endl; list.printList(list.head); list.reverse(); cout << endl; cout << ""The reversed Linked List is "" << endl; list.printList(list.head); } // This code is contributed by Pratham76",linear,linear "// A C++ program to swap Kth node from beginning with kth // node from end #include using namespace std; // A Linked List node typedef struct Node { int data; struct Node* next; } Node; // Utility function to insert a node at the beginning void push(Node** head_ref, int new_data) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } /* Utility function for displaying linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data << "" ""; node = node->next; } cout << endl; } /* Utility function for calculating length of linked list */ int countNodes(struct Node* s) { int count = 0; while (s != NULL) { count++; s = s->next; } return count; } // Utility function for calculating length of linked list void swapKth(struct Node** head_ref, int k) { // Count nodes in linked list int n = countNodes(*head_ref); // Check if k is valid if (n < k) return; // If x (kth node from start) and y(kth node from end) // are same if (2 * k - 1 == n) return; // Find the kth node from the beginning of the linked // list. We also find previous of kth node because we // need to update next pointer of the previous. Node* x = *head_ref; Node* x_prev = NULL; for (int i = 1; i < k; i++) { x_prev = x; x = x->next; } // Similarly, find the kth node from end and its // previous. kth node from end is (n-k+1)th node from // beginning Node* y = *head_ref; Node* y_prev = NULL; for (int i = 1; i < n - k + 1; i++) { y_prev = y; y = y->next; } // If x_prev exists, then new next of it will be y. // Consider the case when y->next is x, in this case, // x_prev and y are same. So the statement ""x_prev->next // = y"" creates a self loop. This self loop will be // broken when we change y->next. if (x_prev) x_prev->next = y; // Same thing applies to y_prev if (y_prev) y_prev->next = x; // Swap next pointers of x and y. These statements also // break self loop if x->next is y or y->next is x Node* temp = x->next; x->next = y->next; y->next = temp; // Change head pointers when k is 1 or n if (k == 1) *head_ref = y; if (k == n) *head_ref = x; } // Driver code int main() { // Let us create the following linked list for testing // 1->2->3->4->5->6->7->8 struct Node* head = NULL; for (int i = 8; i >= 1; i--) push(&head, i); cout << ""Original Linked List: ""; printList(head); for (int k = 1; k < 9; k++) { // Function call swapKth(&head, k); cout << ""\nModified List for k = "" << k << endl; printList(head); } return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,linear "// C++ program for merge sort on doubly linked list #include using namespace std; class Node { public: int data; Node *next, *prev; }; Node *split(Node *head); // Function to merge two linked lists Node *merge(Node *first, Node *second) { // If first linked list is empty if (!first) return second; // If second linked list is empty if (!second) return first; // Pick the smaller value if (first->data < second->data) { first->next = merge(first->next,second); first->next->prev = first; first->prev = NULL; return first; } else { second->next = merge(first,second->next); second->next->prev = second; second->prev = NULL; return second; } } // Function to do merge sort Node *mergeSort(Node *head) { if (!head || !head->next) return head; Node *second = split(head); // Recur for left and right halves head = mergeSort(head); second = mergeSort(second); // Merge the two sorted halves return merge(head,second); } // A utility function to insert a new node at the // beginning of doubly linked list void insert(Node **head, int data) { Node *temp = new Node(); temp->data = data; temp->next = temp->prev = NULL; if (!(*head)) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; } } // A utility function to print a doubly linked list in // both forward and backward directions void print(Node *head) { Node *temp = head; cout<<""Forward Traversal using next pointer\n""; while (head) { cout << head->data << "" ""; temp = head; head = head->next; } cout << ""\nBackward Traversal using prev pointer\n""; while (temp) { cout << temp->data << "" ""; temp = temp->prev; } } // Utility function to swap two integers void swap(int *A, int *B) { int temp = *A; *A = *B; *B = temp; } // Split a doubly linked list (DLL) into 2 DLLs of // half sizes Node *split(Node *head) { Node *fast = head,*slow = head; while (fast->next && fast->next->next) { fast = fast->next->next; slow = slow->next; } Node *temp = slow->next; slow->next = NULL; return temp; } // Driver program int main(void) { Node *head = NULL; insert(&head, 5); insert(&head, 20); insert(&head, 4); insert(&head, 3); insert(&head, 30); insert(&head, 10); head = mergeSort(head); cout << ""Linked List after sorting\n""; print(head); return 0; } // This is code is contributed by rathbhupendra",constant,nlogn "// C++ program to create a doubly linked list out // of given a ternary tree. #include using namespace std; /* A ternary tree */ struct Node { int data; struct Node *left, *middle, *right; }; /* Helper function that allocates a new node with the given data and assign NULL to left, middle and right pointers.*/ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->middle = node->right = NULL; return node; } /* Utility function that constructs doubly linked list by inserting current node at the end of the doubly linked list by using a tail pointer */ void push(Node** tail_ref, Node* node) { // initialize tail pointer if (*tail_ref == NULL) { *tail_ref = node; // set left, middle and right child to point // to NULL node->left = node->middle = node->right = NULL; return; } // insert node in the end using tail pointer (*tail_ref)->right = node; // set prev of node node->left = (*tail_ref); // set middle and right child to point to NULL node->right = node->middle = NULL; // now tail pointer will point to inserted node (*tail_ref) = node; } /* Create a doubly linked list out of given a ternary tree. by traversing the tree in preorder fashion. */ void TernaryTreeToList(Node* root, Node** head_ref) { // Base case if (root == NULL) return; //create a static tail pointer static Node* tail = NULL; // store left, middle and right nodes // for future calls. Node* left = root->left; Node* middle = root->middle; Node* right = root->right; // set head of the doubly linked list // head will be root of the ternary tree if (*head_ref == NULL) *head_ref = root; // push current node in the end of DLL push(&tail, root); //recurse for left, middle and right child TernaryTreeToList(left, head_ref); TernaryTreeToList(middle, head_ref); TernaryTreeToList(right, head_ref); } // Utility function for printing double linked list. void printList(Node* head) { printf(""Created Double Linked list is:\n""); while (head) { printf(""%d "", head->data); head = head->right; } } // Driver program to test above functions int main() { // Constructing ternary tree as shown in above figure Node* root = newNode(30); root->left = newNode(5); root->middle = newNode(11); root->right = newNode(63); root->left->left = newNode(1); root->left->middle = newNode(4); root->left->right = newNode(8); root->middle->left = newNode(6); root->middle->middle = newNode(7); root->middle->right = newNode(15); root->right->left = newNode(31); root->right->middle = newNode(55); root->right->right = newNode(65); Node* head = NULL; TernaryTreeToList(root, &head); printList(head); return 0; }",linear,linear "// C++ program to find a pair with given sum x. #include using namespace std; // structure of node of doubly linked list struct Node { int data; struct Node *next, *prev; }; // Function to find pair whose sum equal to given value x. void pairSum(struct Node *head, int x) { // Set two pointers, first to the beginning of DLL // and second to the end of DLL. struct Node *first = head; struct Node *second = head; while (second->next != NULL) second = second->next; // To track if we find a pair or not bool found = false; // The loop terminates when two pointers // cross each other (second->next // == first), or they become same (first == second) while (first != second && second->next != first) { // pair found if ((first->data + second->data) == x) { found = true; cout << ""("" << first->data<< "", "" << second->data << "")"" << endl; // move first in forward direction first = first->next; // move second in backward direction second = second->prev; } else { if ((first->data + second->data) < x) first = first->next; else second = second->prev; } } // if pair is not present if (found == false) cout << ""No pair found""; } // A utility function to insert a new node at the // beginning of doubly linked list void insert(struct Node **head, int data) { struct Node *temp = new Node; temp->data = data; temp->next = temp->prev = NULL; if (!(*head)) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; } } // Driver program int main() { struct Node *head = NULL; insert(&head, 9); insert(&head, 8); insert(&head, 6); insert(&head, 5); insert(&head, 4); insert(&head, 2); insert(&head, 1); int x = 7; pairSum(head, x); return 0; }",constant,linear "// C++ implementation to insert value in sorted way // in a sorted doubly linked list #include using namespace std; // Node of a doubly linked list struct Node { int data; struct Node* prev, *next; }; // function to create and return a new node // of a doubly linked list struct Node* getNode(int data) { // allocate node struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // put in the data newNode->data = data; newNode->prev = newNode->next = NULL; return newNode; } // function to insert a new node in sorted way in // a sorted doubly linked list void sortedInsert(struct Node** head_ref, struct Node* newNode) { struct Node* current; // if list is empty if (*head_ref == NULL) *head_ref = newNode; // if the node is to be inserted at the beginning // of the doubly linked list else if ((*head_ref)->data >= newNode->data) { newNode->next = *head_ref; newNode->next->prev = newNode; *head_ref = newNode; } else { current = *head_ref; // locate the node after which the new node // is to be inserted while (current->next != NULL && current->next->data < newNode->data) current = current->next; /* Make the appropriate links */ newNode->next = current->next; // if the new node is not inserted // at the end of the list if (current->next != NULL) newNode->next->prev = newNode; current->next = newNode; newNode->prev = current; } } // function to print the doubly linked list void printList(struct Node* head) { while (head != NULL) { cout << head->data << "" ""; head = head->next; } } // Driver program to test above int main() { /* start with the empty doubly linked list */ struct Node* head = NULL; // insert the following nodes in sorted way struct Node* new_node = getNode(8); sortedInsert(&head, new_node); new_node = getNode(5); sortedInsert(&head, new_node); new_node = getNode(3); sortedInsert(&head, new_node); new_node = getNode(10); sortedInsert(&head, new_node); new_node = getNode(12); sortedInsert(&head, new_node); new_node = getNode(9); sortedInsert(&head, new_node); cout << ""Created Doubly Linked Listn""; printList(head); return 0; }",linear,linear "// C++ implementation to count triplets in a sorted doubly linked list // whose sum is equal to a given value 'x' #include using namespace std; // structure of node of doubly linked list struct Node { int data; struct Node* next, *prev; }; // function to count triplets in a sorted doubly linked list // whose sum is equal to a given value 'x' int countTriplets(struct Node* head, int x) { struct Node* ptr1, *ptr2, *ptr3; int count = 0; // generate all possible triplets for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next) for (ptr2 = ptr1->next; ptr2 != NULL; ptr2 = ptr2->next) for (ptr3 = ptr2->next; ptr3 != NULL; ptr3 = ptr3->next) // if elements in the current triplet sum up to 'x' if ((ptr1->data + ptr2->data + ptr3->data) == x) // increment count count++; // required count of triplets return count; } // A utility function to insert a new node at the // beginning of doubly linked list void insert(struct Node** head, int data) { // allocate node struct Node* temp = new Node(); // put in the data temp->data = data; temp->next = temp->prev = NULL; if ((*head) == NULL) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; } } // Driver program to test above int main() { // start with an empty doubly linked list struct Node* head = NULL; // insert values in sorted order insert(&head, 9); insert(&head, 8); insert(&head, 6); insert(&head, 5); insert(&head, 4); insert(&head, 2); insert(&head, 1); int x = 17; cout << ""Count = "" << countTriplets(head, x); return 0; }",constant,cubic "// C++ implementation to count triplets in a sorted doubly linked list // whose sum is equal to a given value 'x' #include using namespace std; // structure of node of doubly linked list struct Node { int data; struct Node* next, *prev; }; // function to count triplets in a sorted doubly linked list // whose sum is equal to a given value 'x' int countTriplets(struct Node* head, int x) { struct Node* ptr, *ptr1, *ptr2; int count = 0; // unordered_map 'um' implemented as hash table unordered_map um; // insert the tuple in 'um' for (ptr = head; ptr != NULL; ptr = ptr->next) um[ptr->data] = ptr; // generate all possible pairs for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next) for (ptr2 = ptr1->next; ptr2 != NULL; ptr2 = ptr2->next) { // p_sum - sum of elements in the current pair int p_sum = ptr1->data + ptr2->data; // if 'x-p_sum' is present in 'um' and either of the two nodes // are not equal to the 'um[x-p_sum]' node if (um.find(x - p_sum) != um.end() && um[x - p_sum] != ptr1 && um[x - p_sum] != ptr2) // increment count count++; } // required count of triplets // division by 3 as each triplet is counted 3 times return (count / 3); } // A utility function to insert a new node at the // beginning of doubly linked list void insert(struct Node** head, int data) { // allocate node struct Node* temp = new Node(); // put in the data temp->data = data; temp->next = temp->prev = NULL; if ((*head) == NULL) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; } } // Driver program to test above int main() { // start with an empty doubly linked list struct Node* head = NULL; // insert values in sorted order insert(&head, 9); insert(&head, 8); insert(&head, 6); insert(&head, 5); insert(&head, 4); insert(&head, 2); insert(&head, 1); int x = 17; cout << ""Count = "" << countTriplets(head, x); return 0; }",linear,quadratic "// C++ implementation to count triplets in a sorted doubly linked list // whose sum is equal to a given value 'x' #include using namespace std; // structure of node of doubly linked list struct Node { int data; struct Node* next, *prev; }; // function to count pairs whose sum equal to given 'value' int countPairs(struct Node* first, struct Node* second, int value) { int count = 0; // The loop terminates when either of two pointers // become NULL, or they cross each other (second->next // == first), or they become same (first == second) while (first != NULL && second != NULL && first != second && second->next != first) { // pair found if ((first->data + second->data) == value) { // increment count count++; // move first in forward direction first = first->next; // move second in backward direction second = second->prev; } // if sum is greater than 'value' // move second in backward direction else if ((first->data + second->data) > value) second = second->prev; // else move first in forward direction else first = first->next; } // required count of pairs return count; } // function to count triplets in a sorted doubly linked list // whose sum is equal to a given value 'x' int countTriplets(struct Node* head, int x) { // if list is empty if (head == NULL) return 0; struct Node* current, *first, *last; int count = 0; // get pointer to the last node of // the doubly linked list last = head; while (last->next != NULL) last = last->next; // traversing the doubly linked list for (current = head; current != NULL; current = current->next) { // for each current node first = current->next; // count pairs with sum(x - current->data) in the range // first to last and add it to the 'count' of triplets count += countPairs(first, last, x - current->data); } // required count of triplets return count; } // A utility function to insert a new node at the // beginning of doubly linked list void insert(struct Node** head, int data) { // allocate node struct Node* temp = new Node(); // put in the data temp->data = data; temp->next = temp->prev = NULL; if ((*head) == NULL) (*head) = temp; else { temp->next = *head; (*head)->prev = temp; (*head) = temp; } } // Driver program to test above int main() { // start with an empty doubly linked list struct Node* head = NULL; // insert values in sorted order insert(&head, 9); insert(&head, 8); insert(&head, 6); insert(&head, 5); insert(&head, 4); insert(&head, 2); insert(&head, 1); int x = 17; cout << ""Count = "" << countTriplets(head, x); return 0; }",constant,quadratic "/* C++ implementation to remove duplicates from a sorted doubly linked list */ #include using namespace std; /* a node of the doubly linked list */ struct Node { int data; struct Node* next; struct Node* prev; }; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ void deleteNode(struct Node** head_ref, struct Node* del) { /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del); } /* function to remove duplicates from a sorted doubly linked list */ void removeDuplicates(struct Node** head_ref) { /* if list is empty */ if ((*head_ref) == NULL) return; struct Node* current = *head_ref; struct Node* next; /* traverse the list till the last node */ while (current->next != NULL) { /* Compare current node with next node */ if (current->data == current->next->data) /* delete the node pointed to by 'current->next' */ deleteNode(head_ref, current->next); /* else simply move to the next node */ else current = current->next; } } /* Function to insert a node at the beginning of the Doubly Linked List */ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given doubly linked list */ void printList(struct Node* head) { /* if list is empty */ if (head == NULL) cout << ""Doubly Linked list empty""; while (head != NULL) { cout << head->data << "" ""; head = head->next; } } /* Driver program to test above functions*/ int main() { /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list: 4<->4<->4<->4<->6<->8<->8<->10<->12<->12 */ push(&head, 12); push(&head, 12); push(&head, 10); push(&head, 8); push(&head, 8); push(&head, 6); push(&head, 4); push(&head, 4); push(&head, 4); push(&head, 4); cout << ""Original Doubly linked list:n""; printList(head); /* remove duplicate nodes */ removeDuplicates(&head); cout << ""\nDoubly linked list after"" "" removing duplicates:n""; printList(head); return 0; }",constant,linear "/* C++ implementation to delete all occurrences of a given key in a doubly linked list */ #include using namespace std; /* a node of the doubly linked list */ struct Node { int data; struct Node* next; struct Node* prev; }; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */ void deleteNode(struct Node** head_ref, struct Node* del) { /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del); } /* function to delete all occurrences of the given key 'x' */ void deleteAllOccurOfX(struct Node** head_ref, int x) { /* if list is empty */ if ((*head_ref) == NULL) return; struct Node* current = *head_ref; struct Node* next; /* traverse the list up to the end */ while (current != NULL) { /* if node found with the value 'x' */ if (current->data == x) { /* save current's next node in the pointer 'next' */ next = current->next; /* delete the node pointed to by 'current' */ deleteNode(head_ref, current); /* update current */ current = next; } /* else simply move to the next node */ else current = current->next; } } /* Function to insert a node at the beginning of the Doubly Linked List */ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given doubly linked list */ void printList(struct Node* head) { /* if list is empty */ if (head == NULL) cout << ""Doubly Linked list empty""; while (head != NULL) { cout << head->data << "" ""; head = head->next; } } /* Driver program to test above functions*/ int main() { /* Start with the empty list */ struct Node* head = NULL; /* Create the doubly linked list: 2<->2<->10<->8<->4<->2<->5<->2 */ push(&head, 2); push(&head, 5); push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); push(&head, 2); push(&head, 2); cout << ""Original Doubly linked list:n""; printList(head); int x = 2; /* delete all occurrences of 'x' */ deleteAllOccurOfX(&head, x); cout << ""\nDoubly linked list after deletion of "" << x << "":n""; printList(head); return 0; }",constant,linear "// C++ implementation to remove duplicates from an // unsorted doubly linked list #include using namespace std; // a node of the doubly linked list struct Node { int data; struct Node* next; struct Node* prev; }; // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> pointer to node to be deleted. void deleteNode(struct Node** head_ref, struct Node* del) { // base case if (*head_ref == NULL || del == NULL) return; // If node to be deleted is head node if (*head_ref == del) *head_ref = del->next; // Change next only if node to be deleted // is NOT the last node if (del->next != NULL) del->next->prev = del->prev; // Change prev only if node to be deleted // is NOT the first node if (del->prev != NULL) del->prev->next = del->next; // Finally, free the memory occupied by del free(del); } // function to remove duplicates from // an unsorted doubly linked list void removeDuplicates(struct Node** head_ref) { // if DLL is empty or if it contains only // a single node if ((*head_ref) == NULL || (*head_ref)->next == NULL) return; struct Node* ptr1, *ptr2; // pick elements one by one for (ptr1 = *head_ref; ptr1 != NULL; ptr1 = ptr1->next) { ptr2 = ptr1->next; // Compare the picked element with the // rest of the elements while (ptr2 != NULL) { // if duplicate, then delete it if (ptr1->data == ptr2->data) { // store pointer to the node next to 'ptr2' struct Node* next = ptr2->next; // delete node pointed to by 'ptr2' deleteNode(head_ref, ptr2); // update 'ptr2' ptr2 = next; } // else simply move to the next node else ptr2 = ptr2->next; } } } // Function to insert a node at the beginning // of the Doubly Linked List void push(struct Node** head_ref, int new_data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node; } // Function to print nodes in a given doubly // linked list void printList(struct Node* head) { // if list is empty if (head == NULL) cout << ""Doubly Linked list empty""; while (head != NULL) { cout << head->data << "" ""; head = head->next; } } // Driver program to test above int main() { struct Node* head = NULL; // Create the doubly linked list: // 8<->4<->4<->6<->4<->8<->4<->10<->12<->12 push(&head, 12); push(&head, 12); push(&head, 10); push(&head, 4); push(&head, 8); push(&head, 4); push(&head, 6); push(&head, 4); push(&head, 4); push(&head, 8); cout << ""Original Doubly linked list:n""; printList(head); /* remove duplicate nodes */ removeDuplicates(&head); cout << ""\nDoubly linked list after "" ""removing duplicates:n""; printList(head); return 0; }",constant,quadratic "// C++ implementation to remove duplicates from an // unsorted doubly linked list #include using namespace std; // a node of the doubly linked list struct Node { int data; struct Node* next; struct Node* prev; }; // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> pointer to node to be deleted. void deleteNode(struct Node** head_ref, struct Node* del) { // base case if (*head_ref == NULL || del == NULL) return; // If node to be deleted is head node if (*head_ref == del) *head_ref = del->next; // Change next only if node to be deleted // is NOT the last node if (del->next != NULL) del->next->prev = del->prev; // Change prev only if node to be deleted // is NOT the first node if (del->prev != NULL) del->prev->next = del->next; // Finally, free the memory occupied by del free(del); } // function to remove duplicates from // an unsorted doubly linked list void removeDuplicates(struct Node** head_ref) { // if doubly linked list is empty if ((*head_ref) == NULL) return; // unordered_set 'us' implemented as hash table unordered_set us; struct Node* current = *head_ref, *next; // traverse up to the end of the list while (current != NULL) { // if current data is seen before if (us.find(current->data) != us.end()) { // store pointer to the node next to // 'current' node next = current->next; // delete the node pointed to by 'current' deleteNode(head_ref, current); // update 'current' current = next; } else { // insert the current data in 'us' us.insert(current->data); // move to the next node current = current->next; } } } // Function to insert a node at the beginning // of the Doubly Linked List void push(struct Node** head_ref, int new_data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node; } // Function to print nodes in a given doubly // linked list void printList(struct Node* head) { // if list is empty if (head == NULL) cout << ""Doubly Linked list empty""; while (head != NULL) { cout << head->data << "" ""; head = head->next; } } // Driver program to test above int main() { struct Node* head = NULL; // Create the doubly linked list: // 8<->4<->4<->6<->4<->8<->4<->10<->12<->12 push(&head, 12); push(&head, 12); push(&head, 10); push(&head, 4); push(&head, 8); push(&head, 4); push(&head, 6); push(&head, 4); push(&head, 4); push(&head, 8); cout << ""Original Doubly linked list:n""; printList(head); /* remove duplicate nodes */ removeDuplicates(&head); cout << ""\nDoubly linked list after "" ""removing duplicates:n""; printList(head); return 0; }",linear,linear "// C++ implementation to sort a k sorted doubly // linked list #include using namespace std; // a node of the doubly linked list struct Node { int data; struct Node* next; struct Node* prev; }; // function to sort a k sorted doubly linked list struct Node* sortAKSortedDLL(struct Node* head, int k) { if(head == NULL || head->next == NULL) return head; // perform on all the nodes in list for(Node *i = head->next; i != NULL; i = i->next) { Node *j = i; // There will be atmost k swaps for each element in the list // since each node is k steps away from its correct position while(j->prev != NULL && j->data < j->prev->data) { // swap j and j.prev node Node* temp = j->prev->prev; Node* temp2 = j->prev; Node *temp3 = j->next; j->prev->next = temp3; j->prev->prev = j; j->prev = temp; j->next = temp2; if(temp != NULL) temp->next = j; if(temp3 != NULL) temp3->prev = temp2; } // if j is now the new head // then reset head if(j->prev == NULL) head = j; } return head; } // Function to insert a node at the beginning // of the Doubly Linked List void push(struct Node** head_ref, int new_data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list of the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node; } // Function to print nodes in a given doubly linked list void printList(struct Node* head) { // if list is empty if (head == NULL) cout << ""Doubly Linked list empty""; while (head != NULL) { cout << head->data << "" ""; head = head->next; } } // Driver program to test above int main() { struct Node* head = NULL; // Create the doubly linked list: // 3<->6<->2<->12<->56<->8 push(&head, 8); push(&head, 56); push(&head, 12); push(&head, 2); push(&head, 6); push(&head, 3); int k = 2; cout << ""Original Doubly linked list:\n""; printList(head); // sort the biotonic DLL head = sortAKSortedDLL(head, k); cout << ""\nDoubly linked list after sorting:\n""; printList(head); return 0; } // This code is contributed by sachinejain74754.",constant,quadratic "// C++ implementation to sort a k sorted doubly // linked list #include using namespace std; // a node of the doubly linked list struct Node { int data; struct Node* next; struct Node* prev; }; // 'compare' function used to build up the // priority queue struct compare { bool operator()(struct Node* p1, struct Node* p2) { return p1->data > p2->data; } }; // function to sort a k sorted doubly linked list struct Node* sortAKSortedDLL(struct Node* head, int k) { // if list is empty if (head == NULL) return head; // priority_queue 'pq' implemented as min heap with the // help of 'compare' function priority_queue, compare> pq; struct Node* newHead = NULL, *last; // Create a Min Heap of first (k+1) elements from // input doubly linked list for (int i = 0; head != NULL && i <= k; i++) { // push the node on to 'pq' pq.push(head); // move to the next node head = head->next; } // loop till there are elements in 'pq' while (!pq.empty()) { // place root or top of 'pq' at the end of the // result sorted list so far having the first node // pointed to by 'newHead' // and adjust the required links if (newHead == NULL) { newHead = pq.top(); newHead->prev = NULL; // 'last' points to the last node // of the result sorted list so far last = newHead; } else { last->next = pq.top(); pq.top()->prev = last; last = pq.top(); } // remove element from 'pq' pq.pop(); // if there are more nodes left in the input list if (head != NULL) { // push the node on to 'pq' pq.push(head); // move to the next node head = head->next; } } // making 'next' of last node point to NULL last->next = NULL; // new head of the required sorted DLL return newHead; } // Function to insert a node at the beginning // of the Doubly Linked List void push(struct Node** head_ref, int new_data) { // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node; } // Function to print nodes in a given doubly linked list void printList(struct Node* head) { // if list is empty if (head == NULL) cout << ""Doubly Linked list empty""; while (head != NULL) { cout << head->data << "" ""; head = head->next; } } // Driver program to test above int main() { struct Node* head = NULL; // Create the doubly linked list: // 3<->6<->2<->12<->56<->8 push(&head, 8); push(&head, 56); push(&head, 12); push(&head, 2); push(&head, 6); push(&head, 3); int k = 2; cout << ""Original Doubly linked list:\n""; printList(head); // sort the biotonic DLL head = sortAKSortedDLL(head, k); cout << ""\nDoubly linked list after sorting:\n""; printList(head); return 0; }",constant,nlogn "// C++ program to convert a given Binary Tree to Doubly Linked List #include // Structure for tree and linked list struct Node { int data; Node *left, *right; }; // Utility function for allocating node for Binary // Tree. Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // A simple recursive function to convert a given // Binary tree to Doubly Linked List // root --> Root of Binary Tree // head --> Pointer to head node of created doubly linked list void BToDLL(Node* root, Node*& head) { // Base cases if (root == NULL) return; // Recursively convert right subtree BToDLL(root->right, head); // insert root into DLL root->right = head; // Change left pointer of previous head if (head != NULL) head->left = root; // Change head of Doubly linked list head = root; // Recursively convert left subtree BToDLL(root->left, head); } // Utility function for printing double linked list. void printList(Node* head) { printf(""Extracted Double Linked list is:\n""); while (head) { printf(""%d "", head->data); head = head->right; } } // Driver program to test above function int main() { /* Constructing below tree 5 / \ 3 6 / \ \ 1 4 8 / \ / \ 0 2 7 9 */ Node* root = newNode(5); root->left = newNode(3); root->right = newNode(6); root->left->left = newNode(1); root->left->right = newNode(4); root->right->right = newNode(8); root->left->left->left = newNode(0); root->left->left->right = newNode(2); root->right->right->left = newNode(7); root->right->right->right = newNode(9); Node* head = NULL; BToDLL(root, head); printList(head); return 0; }",linear,linear "/* C++ program to insetail nodes in doubly linked list such that list remains in ascending order on printing from left to right */ #include using namespace std; // A linked list node class Node { public: Node *prev; int info; Node *next; }; // Function to insetail new node void nodeInsetail(Node **head, Node **tail, int key) { Node *p = new Node(); p->info = key; p->next = NULL; // If first node to be insetailed in doubly // linked list if ((*head) == NULL) { (*head) = p; (*tail) = p; (*head)->prev = NULL; return; } // If node to be insetailed has value less // than first node if ((p->info) < ((*head)->info)) { p->prev = NULL; (*head)->prev = p; p->next = (*head); (*head) = p; return; } // If node to be insetailed has value more // than last node if ((p->info) > ((*tail)->info)) { p->prev = (*tail); (*tail)->next = p; (*tail) = p; return; } // Find the node before which we need to // insert p. Node *temp = (*head)->next; while ((temp->info) < (p->info)) temp = temp->next; // Insert new node before temp (temp->prev)->next = p; p->prev = temp->prev; temp->prev = p; p->next = temp; } // Function to print nodes in from left to right void printList(Node *temp) { while (temp != NULL) { cout << temp->info << "" ""; temp = temp->next; } } // Driver program to test above functions int main() { Node *left = NULL, *right = NULL; nodeInsetail(&left, &right, 30); nodeInsetail(&left, &right, 50); nodeInsetail(&left, &right, 90); nodeInsetail(&left, &right, 10); nodeInsetail(&left, &right, 40); nodeInsetail(&left, &right, 110); nodeInsetail(&left, &right, 60); nodeInsetail(&left, &right, 95); nodeInsetail(&left, &right, 23); cout<<""Doubly linked list on printing"" "" from left to right\n""; printList(left); return 0; } // This is code is contributed by rathbhupendra",constant,linear "#include using namespace std; class Node { public: char data; Node* next; Node* pre; Node(int data) { this->data=data; pre=NULL; next=NULL; } }; void insertAtHead(Node* &head, int data) { Node* n = new Node(data); if(head==NULL) { head=n; return; } n->next=head; head->pre=n; head=n; return; } void insertAtTail(Node* &head, int data) { if(head==NULL) { insertAtHead(head,data); return; } Node* temp=head; while(temp->next!=NULL) { temp=temp->next; } Node* n=new Node(data); temp->next=n; n->pre=temp; return; } void display(Node* head) { while(head!=NULL) { cout << head->data << ""-->""; head=head->next; } cout << ""NULL\n""; } void rotateByN(Node *&head, int pos) { if (pos == 0) return; Node *curr = head; while (pos) { curr = curr->next; pos--; } Node *tail = curr->pre; Node *NewHead = curr; tail->next = NULL; curr->pre = NULL; while (curr->next != NULL) { curr = curr->next; } curr->next = head; head->pre = curr; head = NewHead; } int main() { Node* head=NULL; insertAtTail(head,'a'); insertAtTail(head,'b'); insertAtTail(head,'c'); insertAtTail(head,'d'); insertAtTail(head,'e'); int n=2; cout << ""\nBefore Rotation : \n""; display(head); rotateByN(head,n); cout << ""\nAfter Rotation : \n""; display(head); cout << ""\n\n""; return 0; }",constant,linear "// C++ implementation to reverse a doubly linked list // in groups of given size without recursion // Iterative Method #include using namespace std; // Represents a node of doubly linked list struct Node { int data; Node *next, *prev; }; // function to get a new node Node* getNode(int data) { // allocating node Node* new_node = new Node(); new_node->data = data; new_node->next = new_node->prev = NULL; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List Node* push(Node* head, Node* new_node) { // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = head; // change prev of head node to new node if (head != NULL) head->prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size Node* revListInGroupOfGivenSize(Node* head, int k) { if (!head) return head; Node* st = head; Node* globprev = NULL; Node* ans = NULL; while (st) { int count = 1; // to count k nodes Node* curr = st; Node* prev = NULL; Node* next = NULL; while (curr && count <= k) { // reversing k nodes next = curr->next; curr->prev = next; curr->next = prev; prev = curr; curr = next; count++; } if (!ans) { ans = prev; // to store ans i.e the new head ans->prev = NULL; } if (!globprev) globprev = st; // assigning the last node of the // reversed k nodes else { globprev->next = prev; prev->prev = globprev; // connecting last node of last // k group to the first node of // present k group globprev = st; } st = curr; // advancing the pointer for the next k // group } return ans; } // Function to print nodes in a // given doubly linked list void printList(Node* head) { while (head) { cout << head->data << "" ""; head = head->next; } } // Driver code int main() { // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; cout << ""Original list: ""; printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); cout << ""\nModified list: ""; printList(head); return 0; } // This code is contributed by Tapesh (tapeshdua420)",constant,linear "// C++ program to illustrate inserting a Node in // a Circular Doubly Linked list in begging, end // and middle #include using namespace std; // Structure of a Node struct Node { int data; struct Node* next; struct Node* prev; }; // Function to insert at the end void insertEnd(struct Node** start, int value) { // If the list is empty, create a single node // circular and doubly list if (*start == NULL) { struct Node* new_node = new Node; new_node->data = value; new_node->next = new_node->prev = new_node; *start = new_node; return; } // If list is not empty /* Find last node */ Node* last = (*start)->prev; // Create Node dynamically struct Node* new_node = new Node; new_node->data = value; // Start is going to be next of new_node new_node->next = *start; // Make new node previous of start (*start)->prev = new_node; // Make last previous of new node new_node->prev = last; // Make new node next of old last last->next = new_node; } // Function to insert Node at the beginning // of the List, void insertBegin(struct Node** start, int value) { // Pointer points to last Node struct Node* last = (*start)->prev; struct Node* new_node = new Node; new_node->data = value; // Inserting the data // setting up previous and next of new node new_node->next = *start; new_node->prev = last; // Update next and previous pointers of start // and last. last->next = (*start)->prev = new_node; // Update start pointer *start = new_node; } // Function to insert node with value as value1. // The new node is inserted after the node with // with value2 void insertAfter(struct Node** start, int value1, int value2) { struct Node* new_node = new Node; new_node->data = value1; // Inserting the data // Find node having value2 and next node of it struct Node* temp = *start; while (temp->data != value2) temp = temp->next; struct Node* next = temp->next; // insert new_node between temp and next. temp->next = new_node; new_node->prev = temp; new_node->next = next; next->prev = new_node; } void display(struct Node* start) { struct Node* temp = start; printf(""\nTraversal in forward direction \n""); while (temp->next != start) { printf(""%d "", temp->data); temp = temp->next; } printf(""%d "", temp->data); printf(""\nTraversal in reverse direction \n""); Node* last = start->prev; temp = last; while (temp->prev != last) { printf(""%d "", temp->data); temp = temp->prev; } printf(""%d "", temp->data); } /* Driver program to test above functions*/ int main() { /* Start with the empty list */ struct Node* start = NULL; // Insert 5. So linked list becomes 5->NULL insertEnd(&start, 5); // Insert 4 at the beginning. So linked // list becomes 4->5 insertBegin(&start, 4); // Insert 7 at the end. So linked list // becomes 4->5->7 insertEnd(&start, 7); // Insert 8 at the end. So linked list // becomes 4->5->7->8 insertEnd(&start, 8); // Insert 6, after 5. So linked list // becomes 4->5->6->7->8 insertAfter(&start, 6, 5); printf(""Created circular doubly linked list is: ""); display(start); return 0; }",constant,linear "// C++ program to implement Stack // using linked list so that reverse // can be done with O(1) extra space. #include using namespace std; class StackNode { public: int data; StackNode *next; StackNode(int data) { this->data = data; this->next = NULL; } }; class Stack { StackNode *top; public: // Push and pop operations void push(int data) { if (top == NULL) { top = new StackNode(data); return; } StackNode *s = new StackNode(data); s->next = top; top = s; } StackNode* pop() { StackNode *s = top; top = top->next; return s; } // prints contents of stack void display() { StackNode *s = top; while (s != NULL) { cout << s->data << "" ""; s = s->next; } cout << endl; } // Reverses the stack using simple // linked list reversal logic. void reverse() { StackNode *prev, *cur, *succ; cur = prev = top; cur = cur->next; prev->next = NULL; while (cur != NULL) { succ = cur->next; cur->next = prev; prev = cur; cur = succ; } top = prev; } }; // driver code int main() { Stack *s = new Stack(); s->push(1); s->push(2); s->push(3); s->push(4); cout << ""Original Stack"" << endl;; s->display(); cout << endl; // reverse s->reverse(); cout << ""Reversed Stack"" << endl; s->display(); return 0; } // This code is contributed by Chhavi.",constant,linear "// C++ program to implement unrolled linked list // and traversing it. #include using namespace std; #define maxElements 4 // Unrolled Linked List Node class Node { public: int numElements; int array[maxElements]; Node *next; }; /* Function to traverse an unrolled linked list and print all the elements*/ void printUnrolledList(Node *n) { while (n != NULL) { // Print elements in current node for (int i=0; inumElements; i++) cout<array[i]<<"" ""; // Move to next node n = n->next; } } // Program to create an unrolled linked list // with 3 Nodes int main() { Node* head = NULL; Node* second = NULL; Node* third = NULL; // allocate 3 Nodes head = new Node(); second = new Node(); third = new Node(); // Let us put some values in second node (Number // of values must be less than or equal to // maxElement) head->numElements = 3; head->array[0] = 1; head->array[1] = 2; head->array[2] = 3; // Link first Node with the second Node head->next = second; // Let us put some values in second node (Number // of values must be less than or equal to // maxElement) second->numElements = 3; second->array[0] = 4; second->array[1] = 5; second->array[2] = 6; // Link second Node with the third Node second->next = third; // Let us put some values in third node (Number // of values must be less than or equal to // maxElement) third->numElements = 3; third->array[0] = 7; third->array[1] = 8; third->array[2] = 9; third->next = NULL; printUnrolledList(head); return 0; } // This is code is contributed by rathbhupendra",linear,linear "// C++ program to construct the maximum sum linked // list out of two given sorted lists #include using namespace std; //A linked list node struct Node { int data; //data belong to that node Node *next; //next pointer }; // Push the data to the head of the linked list void push(Node **head, int data) { //Allocation memory to the new node Node *newnode = new Node; //Assigning data to the new node newnode->data = data; //Adjusting next pointer of the new node newnode->next = *head; //New node becomes the head of the list *head = newnode; } // Method that adjusts the pointers and prints the final list void finalMaxSumList(Node *a, Node *b) { Node *result = NULL; // Assigning pre and cur to the head of the // linked list. Node *pre1 = a, *curr1 = a; Node *pre2 = b, *curr2 = b; // Till either of the current pointers is not // NULL execute the loop while (curr1 != NULL || curr2 != NULL) { // Keeping 2 local variables at the start of every // loop run to keep track of the sum between pre // and cur pointer elements. int sum1 = 0, sum2 = 0; // Calculating sum by traversing the nodes of linked // list as the merging of two linked list. The loop // stops at a common node while (curr1!=NULL && curr2!=NULL && curr1->data!=curr2->data) { if (curr1->data < curr2->data) { sum1 += curr1->data; curr1 = curr1->next; } else // (curr2->data < curr1->data) { sum2 += curr2->data; curr2 = curr2->next; } } // If either of current pointers becomes NULL // carry on the sum calculation for other one. if (curr1 == NULL) { while (curr2 != NULL) { sum2 += curr2->data; curr2 = curr2->next; } } if (curr2 == NULL) { while (curr1 != NULL) { sum1 += curr1->data; curr1 = curr1->next; } } // First time adjustment of resultant head based on // the maximum sum. if (pre1 == a && pre2 == b) result = (sum1 > sum2)? pre1 : pre2; // If pre1 and pre2 don't contain the head pointers of // lists adjust the next pointers of previous pointers. else { if (sum1 > sum2) pre2->next = pre1->next; else pre1->next = pre2->next; } // Adjusting previous pointers pre1 = curr1, pre2 = curr2; // If curr1 is not NULL move to the next. if (curr1) curr1 = curr1->next; // If curr2 is not NULL move to the next. if (curr2) curr2 = curr2->next; } // Print the resultant list. while (result != NULL) { cout << result->data << "" ""; result = result->next; } } //Main driver program int main() { //Linked List 1 : 1->3->30->90->110->120->NULL //Linked List 2 : 0->3->12->32->90->100->120->130->NULL Node *head1 = NULL, *head2 = NULL; push(&head1, 120); push(&head1, 110); push(&head1, 90); push(&head1, 30); push(&head1, 3); push(&head1, 1); push(&head2, 130); push(&head2, 120); push(&head2, 100); push(&head2, 90); push(&head2, 32); push(&head2, 12); push(&head2, 3); push(&head2, 0); finalMaxSumList(head1, head2); return 0; }",constant,linear "// C++ program to find fractional node in a linked list #include /* Linked list node */ struct Node { int data; Node* next; }; /* Function to create a new node with given data */ Node* newNode(int data) { Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node; } /* Function to find fractional node in the linked list */ Node* fractionalNodes(Node* head, int k) { // Corner cases if (k <= 0 || head == NULL) return NULL; Node* fractionalNode = NULL; // Traverse the given list int i = 0; for (Node* temp = head; temp != NULL; temp = temp->next) { // For every k nodes, we move fractionalNode one // step ahead. if (i % k == 0) { // First time we see a multiple of k if (fractionalNode == NULL) fractionalNode = head; else fractionalNode = fractionalNode->next; } i++; } return fractionalNode; } // A utility function to print a linked list void printList(Node* node) { while (node != NULL) { printf(""%d "", node->data); node = node->next; } printf(""\n""); } /* Driver program to test above function */ int main(void) { Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); int k = 2; printf(""List is ""); printList(head); Node* answer = fractionalNodes(head, k); printf(""\nFractional node is ""); printf(""%d\n"", answer->data); return 0; }",constant,linear "// C++ program to find modular node in a linked list #include /* Linked list node */ struct Node { int data; Node* next; }; /* Function to create a new node with given data */ Node* newNode(int data) { Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node; } /* Function to find modular node in the linked list */ Node* modularNode(Node* head, int k) { // Corner cases if (k <= 0 || head == NULL) return NULL; // Traverse the given list int i = 1; Node* modularNode = NULL; for (Node* temp = head; temp != NULL; temp = temp->next) { if (i % k == 0) modularNode = temp; i++; } return modularNode; } /* Driver program to test above function */ int main(void) { Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); int k = 2; Node* answer = modularNode(head, k); printf(""\nModular node is ""); if (answer != NULL) printf(""%d\n"", answer->data); else printf(""null\n""); return 0; }",constant,linear "// C++ Program to find smallest and largest // elements in singly linked list. #include using namespace std; /* Linked list node */ struct Node { int data; struct Node* next; }; // Function that returns the largest element // from the linked list. int largestElement(struct Node* head) { // Declare a max variable and initialize // it with INT_MIN value. // INT_MIN is integer type and its value // is -32767 or less. int max = INT_MIN; // Check loop while head not equal to NULL while (head != NULL) { // If max is less than head->data then // assign value of head->data to max // otherwise node point to next node. if (max < head->data) max = head->data; head = head->next; } return max; } // Function that returns smallest element // from the linked list. int smallestElement(struct Node* head) { // Declare a min variable and initialize // it with INT_MAX value. // INT_MAX is integer type and its value // is 32767 or greater. int min = INT_MAX; // Check loop while head not equal to NULL while (head != NULL) { // If min is greater than head->data then // assign value of head->data to min // otherwise node point to next node. if (min > head->data) min = head->data; head = head->next; } return min; } // Function that push the element in linked list. void push(struct Node** head, int data) { // Allocate dynamic memory for newNode. struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Assign the data into newNode. newNode->data = data; // newNode->next assign the address of // head node. newNode->next = (*head); // newNode become the headNode. (*head) = newNode; } // Display linked list. void printList(struct Node* head) { while (head != NULL) { printf(""%d -> "", head->data); head = head->next; } cout << ""NULL"" << endl; } // Driver program to test the functions int main() { // Start with empty list struct Node* head = NULL; // Using push() function to construct // singly linked list // 17->22->13->14->15 push(&head, 15); push(&head, 14); push(&head, 13); push(&head, 22); push(&head, 17); cout << ""Linked list is : "" << endl; // Call printList() function to display // the linked list. printList(head); cout << ""Maximum element in linked list:""; // Call largestElement() function to get largest // element in linked list. cout << largestElement(head) << endl; cout << ""Minimum element in linked list:""; // Call smallestElement() function to get smallest // element in linked list. cout << smallestElement(head) << endl; return 0; }",constant,linear "/* C++ program to arrange consonants and vowels nodes in a linked list */ #include using namespace std; /* A linked list node */ struct Node { char data; struct Node *next; }; /* Function to add new node to the List */ Node *newNode(char key) { Node *temp = new Node; temp->data = key; temp->next = NULL; return temp; } // utility function to print linked list void printlist(Node *head) { if (! head) { cout << ""Empty List\n""; return; } while (head != NULL) { cout << head->data << "" ""; if (head->next) cout << ""-> ""; head = head->next; } cout << endl; } // utility function for checking vowel bool isVowel(char x) { return (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'); } /* function to arrange consonants and vowels nodes */ Node *arrange(Node *head) { Node *newHead = head; // for keep track of vowel Node *latestVowel; Node *curr = head; // list is empty if (head == NULL) return NULL; // We need to discover the first vowel // in the list. It is going to be the // returned head, and also the initial // latestVowel. if (isVowel(head->data)) // first element is a vowel. It will // also be the new head and the initial // latestVowel; latestVowel = head; else { // First element is not a vowel. Iterate // through the list until we find a vowel. // Note that curr points to the element // *before* the element with the vowel. while (curr->next != NULL && !isVowel(curr->next->data)) curr = curr->next; // This is an edge case where there are // only consonants in the list. if (curr->next == NULL) return head; // Set the initial latestVowel and the // new head to the vowel item that we found. // Relink the chain of consonants after // that vowel item: // old_head_consonant->consonant1->consonant2-> // vowel->rest_of_list becomes // vowel->old_head_consonant->consonant1-> // consonant2->rest_of_list latestVowel = newHead = curr->next; curr->next = curr->next->next; latestVowel->next = head; } // Now traverse the list. Curr is always the item // *before* the one we are checking, so that we // can use it to re-link. while (curr != NULL && curr->next != NULL) { if (isVowel(curr->next->data)) { // The next discovered item is a vowel if (curr == latestVowel) { // If it comes directly after the // previous vowel, we don't need to // move items around, just mark the // new latestVowel and advance curr. latestVowel = curr = curr->next; } else { // But if it comes after an intervening // chain of consonants, we need to chain // the newly discovered vowel right after // the old vowel. Curr is not changed as // after the re-linking it will have a // new next, that has not been checked yet, // and we always keep curr at one before // the next to check. Node *temp = latestVowel->next; // Chain in new vowel latestVowel->next = curr->next; // Advance latestVowel latestVowel = latestVowel->next; // Remove found vowel from previous place curr->next = curr->next->next; // Re-link chain of consonants after latestVowel latestVowel->next = temp; } } else { // No vowel in the next element, advance curr. curr = curr->next; } } return newHead; } // Driver code int main() { Node *head = newNode('a'); head->next = newNode('b'); head->next->next = newNode('c'); head->next->next->next = newNode('e'); head->next->next->next->next = newNode('d'); head->next->next->next->next->next = newNode('o'); head->next->next->next->next->next->next = newNode('x'); head->next->next->next->next->next->next->next = newNode('i'); printf(""Linked list before :\n""); printlist(head); head = arrange(head); printf(""Linked list after :\n""); printlist(head); return 0; }",constant,linear "/* C++ program to arrange consonants and vowels nodes in a linked list */ #include using namespace std; /* A linked list node */ struct Node { char data; struct Node* next; Node(int x) { data = x; next = NULL; } }; /* Function to add new node to the List */ void append(struct Node** headRef, char data) { struct Node* new_node = new Node(data); struct Node* last = *headRef; if (*headRef == NULL) { *headRef = new_node; return; } while (last->next != NULL) last = last->next; last->next = new_node; return; } // utility function to print linked list void printlist(Node* head) { if (!head) { cout << ""Empty List\n""; return; } while (head != NULL) { cout << head->data << "" ""; if (head->next) cout << ""-> ""; head = head->next; } cout << endl; } /* function to arrange consonants and vowels nodes */ struct Node* arrange(Node* head) { Node *vowel = NULL, *consonant = NULL, *start = NULL, *end = NULL; while (head != NULL) { char x = head->data; // Checking the current node data is vowel or // not if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') { if (!vowel) { vowel = new Node(x); start = vowel; } else { vowel->next = new Node(x); vowel = vowel->next; } } else { if (!consonant) { consonant = new Node(x); end = consonant; } else { consonant->next = new Node(x); consonant = consonant->next; } } head = head->next; } // In case when there is no vowel in the incoming LL // then we have to return the head of the consonant LL if (start == NULL) return end; // Connecting the vowel and consonant LL vowel->next = end; return start; } // Driver code int main() { struct Node* head = NULL; append(&head, 'a'); append(&head, 'b'); append(&head, 'c'); append(&head, 'e'); append(&head, 'd'); append(&head, 'o'); append(&head, 'x'); append(&head, 'i'); printf(""Linked list before :\n""); printlist(head); head = arrange(head); printf(""Linked list after :\n""); printlist(head); return 0; } // This code is contributed by Aditya Kumar",linear,linear "// C++ program to partition a linked list around a // given value. #include using namespace std; /* Link list Node */ struct Node { int data; struct Node* next; }; // A utility function to create a new node Node *newNode(int data) { struct Node* new_node = new Node; new_node->data = data; new_node->next = NULL; return new_node; } // Function to make a new list(using the existing // nodes) and return head of new list. struct Node *partition(struct Node *head, int x) { /* Let us initialize start and tail nodes of new list */ struct Node *tail = head; // Now iterate original list and connect nodes Node *curr = head; while (curr != NULL) { struct Node *next = curr->next; if (curr->data < x) { /* Insert node at head. */ curr->next = head; head = curr; } else // Append to the list of greater values { /* Insert node at tail. */ tail->next = curr; tail = curr; } curr = next; } tail->next = NULL; // The head has changed, so we need // to return it to the user. return head; } /* Function to print linked list */ void printList(struct Node *head) { struct Node *temp = head; while (temp != NULL) { printf(""%d "", temp->data); temp = temp->next; } } // Driver program to run the case int main() { /* Start with the empty list */ struct Node* head = newNode(3); head->next = newNode(5); head->next->next = newNode(8); head->next->next->next = newNode(2); head->next->next->next->next = newNode(10); head->next->next->next->next->next = newNode(2); head->next->next->next->next->next->next = newNode(1); int x = 5; head = partition(head, x); printList(head); return 0; }",constant,linear "// C++ implementation to modify the contents of // the linked list #include using namespace std; /* Linked list node */ struct Node { int data; struct Node* next; }; /* function prototype for printing the list */ void printList(struct Node*); /* Function to insert a node at the beginning of the linked list */ void push(struct Node **head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list at the end of the new node */ new_node->next = *head_ref; /* move the head to point to the new node */ *head_ref = new_node; } /* Split the nodes of the given list into front and back halves, and return the two lists using the reference parameters. Uses the fast/slow pointer strategy. */ void frontAndBackSplit(struct Node *head, struct Node **front_ref, struct Node **back_ref) { Node *slow, *fast; slow = head; fast = head->next; /* Advance 'fast' two nodes, and advance 'slow' one node */ while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } } /* 'slow' is before the midpoint in the list, so split it in two at that point. */ *front_ref = head; *back_ref = slow->next; slow->next = NULL; } /* Function to reverse the linked list */ void reverseList(struct Node **head_ref) { struct Node *current, *prev, *next; current = *head_ref; prev = NULL; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; } // perform the required subtraction operation on // the 1st half of the linked list void modifyTheContentsOf1stHalf(struct Node *front, struct Node *back) { // traversing both the lists simultaneously while (back != NULL) { // subtraction operation and node data // modification front->data = front->data - back->data; front = front->next; back = back->next; } } // function to concatenate the 2nd(back) list at the end of // the 1st(front) list and returns the head of the new list struct Node* concatFrontAndBackList(struct Node *front, struct Node *back) { struct Node *head = front; while (front->next != NULL) front = front->next; front->next = back; return head; } // function to modify the contents of the linked list struct Node* modifyTheList(struct Node *head) { // if list is empty or contains only single node if (!head || head->next == NULL) return head; struct Node *front, *back; // split the list into two halves // front and back lists frontAndBackSplit(head, &front, &back); // reverse the 2nd(back) list reverseList(&back); // modify the contents of 1st half modifyTheContentsOf1stHalf(front, back); // agains reverse the 2nd(back) list reverseList(&back); // concatenating the 2nd list back to the // end of the 1st list head = concatFrontAndBackList(front, back); // pointer to the modified list return head; } // function to print the linked list void printList(struct Node *head) { if (!head) return; while (head->next != NULL) { cout << head->data << "" -> ""; head = head->next; } cout << head->data << endl; } // Driver program to test above int main() { struct Node *head = NULL; // creating the linked list push(&head, 10); push(&head, 7); push(&head, 12); push(&head, 8); push(&head, 9); push(&head, 2); // modify the linked list head = modifyTheList(head); // print the modified linked list cout << ""Modified List:"" << endl; printList(head); return 0; }",constant,linear "// C++ implementation to modify the // contents of the linked list #include using namespace std; // Linked list node struct Node { int data; struct Node* next; }; // function prototype for printing the list void printList(struct Node*); // Function to insert a node at the // beginning of the linked list void push(struct Node **head_ref, int new_data) { // allocate node struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // link the old list at the end of the new node new_node->next = *head_ref; // move the head to point to the new node *head_ref = new_node; } // function to print the linked list void printList(struct Node *head) { if (!head) return; while (head->next != NULL) { cout << head->data << "" -> ""; head = head->next; } cout << head->data << endl; } // Function to middle node of list. Node* find_mid(Node *head) { Node *temp = head, *slow = head, *fast = head ; while(fast && fast->next) { // Advance 'fast' two nodes, and // advance 'slow' one node slow = slow->next ; fast = fast->next->next ; } // If number of nodes are odd then update slow // by slow->next; if(fast) slow = slow->next ; return slow ; } // function to modify the contents of the linked list. void modifyTheList(struct Node *head, struct Node *slow) { // Create Stack. stack s; Node *temp = head ; while(slow) { s.push( slow->data ) ; slow = slow->next ; } // Traverse the list by using temp until stack is empty. while( !s.empty() ) { temp->data = temp->data - s.top() ; temp = temp->next ; s.pop() ; } } // Driver program to test above int main() { struct Node *head = NULL, *mid ; // creating the linked list push(&head, 10); push(&head, 7); push(&head, 12); push(&head, 8); push(&head, 9); push(&head, 2); // Call Function to Find the starting point of second half of list. mid = find_mid(head) ; // Call function to modify the contents of the linked list. modifyTheList( head, mid); // print the modified linked list cout << ""Modified List:"" << endl; printList(head); return 0; } // This is contributed by Mr. Gera",linear,linear "// C++ program to rotate a matrix // by 90 degrees #include #define N 4 using namespace std; // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction void rotateMatrix(int mat[][N]) { // Consider all squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (int y = x; y < N - x - 1; y++) { // Store current cell in // temp variable int temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } } } // Function to print the matrix void displayMatrix(int mat[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << mat[i][j] << "" ""; } cout << endl; } cout << endl; } /* Driver code */ int main() { // Test Case 1 int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0; }",constant,quadratic "// C++ program to rotate a matrix // by 90 degrees #include using namespace std; #define N 4 // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction void rotateMatrix(int mat[][N]) { // REVERSE every row for (int i = 0; i < N; i++) reverse(mat[i], mat[i] + N); // Performing Transpose for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) swap(mat[i][j], mat[j][i]); } } // Function to print the matrix void displayMatrix(int mat[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << mat[i][j] << "" ""; } cout << endl; } cout << endl; } /* Driver code */ int main() { int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0; }",constant,quadratic "#include using namespace std; //Function to rotate matrix anticlockwise by 90 degrees. void rotateby90(vector >& matrix) { int n=matrix.size(); int mid; if(n%2==0) mid=n/2-1; else mid=n/2; for(int i=0,j=n-1;i<=mid;i++,j--) { for(int k=0;k>& arr) { int n=arr.size(); for(int i=0;i> arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); return 0; }",constant,quadratic "// C++ program to rotate a matrix by 180 degrees #include #define N 3 using namespace std; // Function to Rotate the matrix by 180 degree void rotateMatrix(int mat[][N]) { // Simply print from last cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) printf(""%d "", mat[i][j]); printf(""\n""); } } // Driven code int main() { int mat[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); return 0; }",constant,quadratic "// C++ program for left rotation of matrix by 180 #include using namespace std; #define R 4 #define C 4 // Function to rotate the matrix by 180 degree void reverseColumns(int arr[R][C]) { for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) swap(arr[j][i], arr[k][i]); } // Function for transpose of matrix void transpose(int arr[R][C]) { for (int i = 0; i < R; i++) for (int j = i; j < C; j++) swap(arr[i][j], arr[j][i]); } // Function for display the matrix void printMatrix(int arr[R][C]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << "" ""; cout << '\n'; } } // Function to anticlockwise rotate matrix // by 180 degree void rotate180(int arr[R][C]) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driven code int main() { int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); return 0; }",constant,quadratic "#include using namespace std; /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ void reverseRow(vector>& data, int index) { int cols = data[index].size(); for(int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ void printMatrix(vector>& data) { for(int i = 0; i < data.size(); i++) { for(int j = 0; j < data[i].size(); j++) { cout << data[i][j] << "" ""; } cout << endl; } } /** * Rotate Matrix by 180 degrees * @param data matrix */ void rotateMatrix180(vector>& data) { int rows = data.size(); int cols = data[0].size(); if (rows % 2 != 0) { // If N is odd reverse the middle // row in the matrix reverseRow(data, data.size() / 2); } // Swap the value of matrix [i][j] with // [rows - i - 1][cols - j - 1] for half // the rows size. for(int i = 0; i <= (rows/2) - 1; i++) { for(int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } } } // Driver code int main() { vector> data{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; // Rotate Matrix rotateMatrix180(data); // Print Matrix printMatrix(data); return 0; } // This code is contributed by divyeshrabadiya07",constant,quadratic "// C++ program to rotate individual rings by k in // spiral order traversal. #include #define MAX 100 using namespace std; // Fills temp array into mat[][] using spiral order // traversal. void fillSpiral(int mat[][MAX], int m, int n, int temp[]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int tIdx = 0; // Index in temp array while (k < m && l < n) { /* first row from the remaining rows */ for (int i = l; i < n; ++i) mat[k][i] = temp[tIdx++]; k++; /* last column from the remaining columns */ for (int i = k; i < m; ++i) mat[i][n-1] = temp[tIdx++]; n--; /* last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) mat[m-1][i] = temp[tIdx++]; m--; } /* first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) mat[i][l] = temp[tIdx++]; l++; } } } // Function to spirally traverse matrix and // rotate each ring of matrix by K elements // mat[][] --> matrix of elements // M --> number of rows // N --> number of columns void spiralRotate(int mat[][MAX], int M, int N, int k) { // Create a temporary array to store the result int temp[M*N]; /* s - starting row index m - ending row index l - starting column index n - ending column index; */ int m = M, n = N, s = 0, l = 0; int *start = temp; // Start position of current ring int tIdx = 0; // Index in temp while (s < m && l < n) { // Initialize end position of current ring int *end = start; // copy the first row from the remaining rows for (int i = l; i < n; ++i) { temp[tIdx++] = mat[s][i]; end++; } s++; // copy the last column from the remaining columns for (int i = s; i < m; ++i) { temp[tIdx++] = mat[i][n-1]; end++; } n--; // copy the last row from the remaining rows if (s < m) { for (int i = n-1; i >= l; --i) { temp[tIdx++] = mat[m-1][i]; end++; } m--; } /* copy the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= s; --i) { temp[tIdx++] = mat[i][l]; end++; } l++; } // if elements in current ring greater than // k then rotate elements of current ring if (end-start > k) { // Rotate current ring using reversal // algorithm for rotation reverse(start, start+k); reverse(start+k, end); reverse(start, end); // Reset start for next ring start = end; } } // Fill temp array in original matrix. fillSpiral(mat, M, N, temp); } // Driver program to run the case int main() { // Your C++ Code int M = 4, N = 4, k = 3; int mat[][MAX]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; spiralRotate(mat, M, N, k); // print modified matrix for (int i=0; i using namespace std; const int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1] // are rotations of each other. bool isPermutedMatrix( int mat[MAX][MAX], int n) { // Creating a string that contains elements of first // row. string str_cat = """"; for (int i = 0 ; i < n ; i++) str_cat = str_cat + ""-"" + to_string(mat[0][i]); // Concatenating the string with itself so that // substring search operations can be performed on // this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i=1; i using namespace std; #define SIZE 10 // function to sort the given matrix void sortMat(int mat[SIZE][SIZE], int n) { // temporary matrix of size n^2 int temp[n * n]; int k = 0; // copy the elements of matrix one by one // into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] sort(temp, temp + k); // copy the elements of temp[] one by one // in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++]; } // function to print the given matrix void printMat(int mat[SIZE][SIZE], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << "" ""; cout << endl; } } // Driver program to test above int main() { int mat[SIZE][SIZE] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; cout << ""Original Matrix:\n""; printMat(mat, n); sortMat(mat, n); cout << ""\nMatrix After Sorting:\n""; printMat(mat, n); return 0; }",quadratic,quadratic "// C++ program to find median of a matrix // sorted row wise #include using namespace std; const int MAX = 100; // function to find median in the matrix int binaryMedian(int m[][MAX], int r ,int c) { int min = INT_MAX, max = INT_MIN; for (int i=0; i max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while (min < max) { int mid = min + (max - min) / 2; int place = 0; // Find count of elements smaller than or equal to mid for (int i = 0; i < r; ++i) place += upper_bound(m[i], m[i]+c, mid) - m[i]; if (place < desired) min = mid + 1; else max = mid; } return min; } // driver program to check above functions int main() { int r = 3, c = 3; int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; cout << ""Median is "" << binaryMedian(m, r, c) << endl; return 0; }",constant,nlogn "// C++ program to print Lower // triangular and Upper triangular // matrix of an array #include using namespace std; // Function to form // lower triangular matrix void lower(int matrix[3][3], int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i < j) { cout << ""0"" << "" ""; } else cout << matrix[i][j] << "" ""; } cout << endl; } } // Function to form upper triangular matrix void upper(int matrix[3][3], int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i > j) { cout << ""0"" << "" ""; } else cout << matrix[i][j] << "" ""; } cout << endl; } } // Driver Code int main() { int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int row = 3, col = 3; cout << ""Lower triangular matrix: \n""; lower(matrix, row, col); cout << ""Upper triangular matrix: \n""; upper(matrix, row, col); return 0; }",constant,quadratic "// C++ program for the above approach #include using namespace std; vector spiralOrder(vector >& matrix) { int m = matrix.size(), n = matrix[0].size(); vector ans; if (m == 0) return ans; vector > seen(m, vector(n, false)); int dr[] = { 0, 1, 0, -1 }; int dc[] = { 1, 0, -1, 0 }; int x = 0, y = 0, di = 0; // Iterate from 0 to m * n - 1 for (int i = 0; i < m * n; i++) { ans.push_back(matrix[x][y]); // on normal geeksforgeeks ui page it is showing // 'ans.push_back(matrix[x])' which gets copied as // this only and gives error on compilation, seen[x][y] = true; int newX = x + dr[di]; int newY = y + dc[di]; if (0 <= newX && newX < m && 0 <= newY && newY < n && !seen[newX][newY]) { x = newX; y = newY; } else { di = (di + 1) % 4; x += dr[di]; y += dc[di]; } } return ans; } // Driver code int main() { vector > a{ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call for (int x : spiralOrder(a)) { cout << x << "" ""; } return 0; } // This code is contributed by Yashvendra Singh",linear,linear "// C++ Program to print a matrix spirally #include using namespace std; #define R 4 #define C 4 void spiralPrint(int m, int n, int a[R][C]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { cout << a[k][i] << "" ""; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { cout << a[i][n - 1] << "" ""; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { cout << a[m - 1][i] << "" ""; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m - 1; i >= k; --i) { cout << a[i][l] << "" ""; } l++; } } } /* Driver Code */ int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call spiralPrint(R, C, a); return 0; } // This is code is contributed by rathbhupendra",constant,quadratic "// C++. program for the above approach #include using namespace std; #define R 4 #define C 4 // Function for printing matrix in spiral // form i, j: Start index of matrix, row // and column respectively m, n: End index // of matrix row and column respectively void print(int arr[R][C], int i, int j, int m, int n) { // If i or j lies outside the matrix if (i >= m or j >= n) return; // Print First Row for (int p = j; p < n; p++) cout << arr[i][p] << "" ""; // Print Last Column for (int p = i + 1; p < m; p++) cout << arr[p][n - 1] << "" ""; // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) for (int p = n - 2; p >= j; p--) cout << arr[m - 1][p] << "" ""; // Print First Column, if Last and // First Column are not same if ((n - 1) != j) for (int p = m - 2; p > i; p--) cout << arr[p][j] << "" ""; print(arr, i + 1, j + 1, m - 1, n - 1); } // Driver Code int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); return 0; } // This Code is contributed by Ankur Goel",constant,quadratic "// C++ program for the above approach #include using namespace std; #define R 4 #define C 4 bool isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } // check if the position is blocked bool isBlocked(int matrix[R][C], int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false; } // DFS code to traverse spirally void spirallyDFSTravserse(int matrix[R][C], int i, int j, int dir, vector& res) { if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push_back(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } // To traverse spirally vector spirallyTraverse(int matrix[R][C]) { vector res; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } // Driver Code int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call vector res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) cout << res[i] << "" ""; cout << endl; return 0; } // code contributed by Ephi F",constant,quadratic "// C++ program to find unique element in matrix #include using namespace std; #define R 4 #define C 4 // function that calculate unique element int unique(int mat[R][C], int n, int m) { // declare map for hashing unordered_map mp; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) // increase freq of mat[i][j] in map mp[mat[i][j]]++; int flag = false; // print unique element for (auto p : mp) { if (p.second == 1) { cout << p.first << "" ""; flag = 1; } } if (!flag) { cout << ""No unique element in the matrix""; } } // Driver program int main() { int mat[R][C] = { { 1, 2, 3, 20 }, { 5, 6, 20, 25 }, { 1, 3, 5, 6 }, { 6, 7, 8, 15 } }; // function that calculate unique element unique(mat, R, C); return 0; }",quadratic,quadratic "// C++ program to shift k elements in a matrix. #include using namespace std; #define N 4 // Function to shift first k elements of // each row of matrix. void shiftMatrixByK(int mat[N][N], int k) { if (k > N) { cout << ""shifting is not possible"" << endl; return; } int j = 0; while (j < N) { // Print elements from index k for (int i = k; i < N; i++) cout << mat[j][i] << "" ""; // Print elements before index k for (int i = 0; i < k; i++) cout << mat[j][i] << "" ""; cout << endl; j++; } } // Driver code int main() { int mat[N][N] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int k = 2; // Function call shiftMatrixByK(mat, k); return 0; }",constant,quadratic "// CPP Program to swap diagonal of a matrix #include using namespace std; // size of square matrix #define N 3 // Function to swap diagonal of matrix void swapDiagonal(int matrix[][N]) { for (int i = 0; i < N; i++) swap(matrix[i][i], matrix[i][N - i - 1]); } // Driver Code int main() { int matrix[N][N] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; swapDiagonal(matrix); // Displaying modified matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << matrix[i][j] << "" ""; cout << endl; } return 0; }",constant,quadratic "// CPP program for finding max path in matrix #include #define N 4 #define M 6 using namespace std; // To calculate max path in matrix int findMaxPath(int mat[][M]) { for (int i = 1; i < N; i++) { for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum } } int res = 0; for (int j = 0; j < M; j++) res = max(mat[N-1][j], res); return res; } // Driver program to check findMaxPath int main() { int mat1[N][M] = { { 10, 10, 2, 0, 20, 4 }, { 1, 0, 0, 30, 2, 5 }, { 0, 10, 4, 0, 2, 0 }, { 1, 0, 2, 20, 0, 4 } }; cout << findMaxPath(mat1) << endl; return 0; }",constant,quadratic "// C++ code to move matrix elements // in given direction with add // element with same value #include using namespace std; #define MAX 50 // Function to shift the matrix // in the given direction void moveMatrix(char d[], int n, int a[MAX][MAX]) { // For right shift move. if (d[0] == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { vector v, w; int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (auto it = w.begin(); it != w.end(); it++) a[i][j--] = *it; } } // for left shift move else if (d[0] == 'l') { // for each row for (int i = 0; i < n; i++) { vector v, w; int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (auto it = w.begin(); it != w.end(); it++) a[i][j++] = *it; } } // for down shift move. else if (d[0] == 'd') { // for each column for (int i = 0; i < n; i++) { vector v, w; int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j--][i] = *it; } } // for up shift move else if (d[0] == 'u') { // for each column for (int i = 0; i < n; i++) { vector v, w; int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j++][i] = *it; } } } // Driven Program int main() { char d[2] = ""l""; int n = 5; int a[MAX][MAX] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << a[i][j] << "" ""; cout << endl; } return 0; }",linear,quadratic "// C++ implementation to sort the rows // of matrix in ascending order followed by // sorting the columns in descending order #include using namespace std; #define MAX_SIZE 10 // function to sort each row of the matrix // according to the order specified by // ascending. void sortByRow(int mat[][MAX_SIZE], int n, bool ascending) { for (int i = 0; i < n; i++) { if (ascending) sort(mat[i], mat[i] + n); else sort(mat[i], mat[i] + n, greater()); } } // function to find transpose of the matrix void transpose(int mat[][MAX_SIZE], int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // swapping element at index (i, j) // by element at index (j, i) swap(mat[i][j], mat[j][i]); } // function to sort the matrix row-wise // and column-wise void sortMatRowAndColWise(int mat[][MAX_SIZE], int n) { // sort rows of mat[][] sortByRow(mat, n, true); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] in descending // order. sortByRow(mat, n, false); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix void printMat(int mat[][MAX_SIZE], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << "" ""; cout << endl; } } // Driver program to test above int main() { int n = 3; int mat[n][MAX_SIZE] = {{3, 2, 1}, {9, 8, 7}, {6, 5, 4}}; cout << ""Original Matrix:\n""; printMat(mat, n); sortMatRowAndColWise(mat, n); cout << ""\nMatrix After Sorting:\n""; printMat(mat, n); return 0; }",constant,quadratic "// C++ program to find sum of // middle row and column in matrix #include using namespace std; const int MAX = 100; void middlesum(int mat[][MAX], int n) { int row_sum = 0, col_sum = 0; //loop for sum of row for (int i = 0; i < n; i++) row_sum += mat[n / 2][i]; cout << ""Sum of middle row = "" << row_sum< #include // taking MAX 10000 so that time difference // can be shown #define MAX 10000 int arr[MAX][MAX] = { 0 }; void rowMajor() { int i, j; // accessing element row wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[i][j]++; } } } void colMajor() { int i, j; // accessing element column wise for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { arr[j][i]++; } } } // driver code int main() { int i, j; // Time taken by row major order clock_t t = clock(); rowMajor(); t = clock() - t; printf(""Row major access time :%f s\n"", t / (float)CLOCKS_PER_SEC); // Time taken by column major order t = clock(); colMajor(); t = clock() - t; printf(""Column major access time :%f s\n"", t / (float)CLOCKS_PER_SEC); return 0; }",quadratic,quadratic "// CPP program to rotate a matrix right by k times #include // size of matrix #define M 3 #define N 3 using namespace std; // function to rotate matrix by k times void rotateMatrix(int matrix[][M], int k) { // temporary array of size M int temp[M]; // within the size of matrix k = k % M; for (int i = 0; i < N; i++) { // copy first M-k elements to temporary array for (int t = 0; t < M - k; t++) temp[t] = matrix[i][t]; // copy the elements from k to end to starting for (int j = M - k; j < M; j++) matrix[i][j - M + k] = matrix[i][j]; // copy elements from temporary array to end for (int j = k; j < M; j++) matrix[i][j] = temp[j - k]; } } // function to display the matrix void displayMatrix(int matrix[][M]) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << matrix[i][j] << "" ""; cout << endl; } } // Driver's code int main() { int matrix[N][M] = {{12, 23, 34}, {45, 56, 67}, {78, 89, 91}}; int k = 2; // rotate matrix by k rotateMatrix(matrix, k); // display rotated matrix displayMatrix(matrix); return 0; }",linear,quadratic "// Program to check given matrix // is idempotent matrix or not. #include #define N 3 using namespace std; // Function for matrix multiplication. void multiply(int mat[][N], int res[][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { res[i][j] = 0; for (int k = 0; k < N; k++) res[i][j] += mat[i][k] * mat[k][j]; } } } // Function to check idempotent // property of matrix. bool checkIdempotent(int mat[][N]) { // Calculate multiplication of matrix // with itself and store it into res. int res[N][N]; multiply(mat, res); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != res[i][j]) return false; return true; } // Driver function. int main() { int mat[N][N] = {{2, -2, -4}, {-1, 3, 4}, {1, -2, -3}}; // checkIdempotent function call. if (checkIdempotent(mat)) cout << ""Idempotent Matrix""; else cout << ""Not Idempotent Matrix.""; return 0; }",quadratic,cubic "// Program to implement involutory matrix. #include #define N 3 using namespace std; // Function for matrix multiplication. void multiply(int mat[][N], int res[][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { res[i][j] = 0; for (int k = 0; k < N; k++) res[i][j] += mat[i][k] * mat[k][j]; } } } // Function to check involutory matrix. bool InvolutoryMatrix(int mat[N][N]) { int res[N][N]; // multiply function call. multiply(mat, res); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (i == j && res[i][j] != 1) return false; if (i != j && res[i][j] != 0) return false; } } return true; } // Driver function. int main() { int mat[N][N] = { { 1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } }; // Function call. If function return // true then if part will execute otherwise // else part will execute. if (InvolutoryMatrix(mat)) cout << ""Involutory Matrix""; else cout << ""Not Involutory Matrix""; return 0; }",quadratic,cubic "// C++ code to swap the element of first // and last row and display the result #include using namespace std; #define n 4 void interchangeFirstLast(int m[][n]) { int rows = n; // swapping of element between first // and last rows for (int i = 0; i < n; i++) { int t = m[0][i]; m[0][i] = m[rows - 1][i]; m[rows - 1][i] = t; } } // Driver code int main() { // input in the array int m[n][n] = { { 8, 9, 7, 6 }, { 4, 7, 6, 5 }, { 3, 2, 1, 8 }, { 9, 9, 7, 7 } }; // Function call interchangeFirstLast(m); // printing the interchanged matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << m[i][j] << "" ""; cout << endl; } } // This code is contributed by Anant Agarwal.",constant,linear "/* C++ Program to print matrix in Zig-zag pattern*/ #include using namespace std; #define C 3 // Utility function to print matrix // in zig-zag form void zigZagMatrix(int arr[][C], int n, int m) { int row = 0, col = 0; // Boolean variable that will true if we // need to increment 'row' value otherwise // false- if increment 'col' value bool row_inc = 0; // Print matrix of lower half zig-zag pattern int mn = min(m, n); for (int len = 1; len <= mn; ++len) { for (int i = 0; i < len; ++i) { cout << arr[row][col] << "" ""; if (i + 1 == len) break; // If row_increment value is true // increment row and decrement col // else decrement row and increment // col if (row_inc) ++row, --col; else --row, ++col; } if (len == mn) break; // Update row or col value according // to the last increment if (row_inc) ++row, row_inc = false; else ++col, row_inc = true; } // Update the indexes of row and col variable if (row == 0) { if (col == m - 1) ++row; else ++col; row_inc = 1; } else { if (row == n - 1) ++col; else ++row; row_inc = 0; } // Print the next half zig-zag pattern int MAX = max(m, n) - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > mn) len = mn; else len = diag; for (int i = 0; i < len; ++i) { cout << arr[row][col] << "" ""; if (i + 1 == len) break; // Update row or col value according // to the last increment if (row_inc) ++row, --col; else ++col, --row; } // Update the indexes of row and col variable if (row == 0 || col == m - 1) { if (col == m - 1) ++row; else ++col; row_inc = true; } else if (col == 0 || row == n - 1) { if (row == n - 1) ++col; else ++row; row_inc = false; } } } // Driver code int main() { int matrix[][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; zigZagMatrix(matrix, 3, 3); return 0; }",constant,quadratic "// C++ code to // sort 2D matrix row-wise #include using namespace std; void sortRowWise(int m[][4], int r, int c) { // loop for rows of matrix for (int i = 0; i < r; i++) { // loop for column of matrix for (int j = 0; j < c; j++) { // loop for comparison and swapping for (int k = 0; k < c - j - 1; k++) { if (m[i][k] > m[i][k + 1]) { // swapping of elements swap(m[i][k], m[i][k + 1]); } } } } // printing the sorted matrix for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout << m[i][j] << "" ""; cout << endl; } } // Driver code int main() { int m[][4] = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; int c = sizeof(m[0]) / sizeof(m[0][0]); int r = sizeof(m) / sizeof(m[0]); sortRowWise(m, r, c); return 0; } // This code is contributed by Rutvik_56",constant,quadratic "// C++ code to sort 2D // matrix row-wise #include using namespace std; #define M 4 #define N 4 int sortRowWise(int m[M][N]) { // One by one sort // individual rows. for (int i = 0; i < M; i++) sort(m[i], m[i] + N); // Printing the sorted matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) cout << (m[i][j]) << "" ""; cout << endl; } } // Driver code int main() { int m[M][N] = {{9, 8, 7, 1}, {7, 3, 0, 2}, {9, 5, 3, 2}, {6, 3, 1, 2}}; sortRowWise(m); } // This code is contributed by gauravrajput1",constant,quadratic "// C++ code to check Markov Matrix #include using namespace std; #define n 3 bool checkMarkov(double m[][n]) { // outer loop to access rows // and inner to access columns for (int i = 0; i #define N 4 using namespace std; // Function to check matrix // is diagonal matrix or not. bool isDiagonalMatrix(int mat[N][N]) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) // condition to check other elements // except main diagonal are zero or not. if ((i != j) && (mat[i][j] != 0)) return false; return true; } // Driver function int main() { int mat[N][N] = { { 4, 0, 0, 0 }, { 0, 7, 0, 0 }, { 0, 0, 5, 0 }, { 0, 0, 0, 1 } }; if (isDiagonalMatrix(mat)) cout << ""Yes"" << endl; else cout << ""No"" << endl; return 0; }",constant,quadratic "// Program to check matrix is scalar matrix or not. #include #define N 4 using namespace std; // Function to check matrix is scalar matrix or not. bool isScalarMatrix(int mat[N][N]) { // Check all elements except main diagonal are // zero or not. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if ((i != j) && (mat[i][j] != 0)) return false; // Check all diagonal elements are same or not. for (int i = 0; i < N - 1; i++) if (mat[i][i] != mat[i + 1][i + 1]) return false; return true; } // Driver function int main() { int mat[N][N] = { { 2, 0, 0, 0 }, { 0, 2, 0, 0 }, { 0, 0, 2, 0 }, { 0, 0, 0, 2 } }; // Function call if (isScalarMatrix(mat)) cout << ""Yes"" << endl; else cout << ""No"" << endl; return 0; }",constant,quadratic "// C++ implementation to sort the matrix row-wise // and column-wise #include using namespace std; #define MAX_SIZE 10 // function to sort each row of the matrix void sortByRow(int mat[MAX_SIZE][MAX_SIZE], int n) { for (int i = 0; i < n; i++) // sorting row number 'i' sort(mat[i], mat[i] + n); } // function to find transpose of the matrix void transpose(int mat[MAX_SIZE][MAX_SIZE], int n) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) // swapping element at index (i, j) // by element at index (j, i) swap(mat[i][j], mat[j][i]); } // function to sort the matrix row-wise // and column-wise void sortMatRowAndColWise(int mat[MAX_SIZE][MAX_SIZE], int n) { // sort rows of mat[][] sortByRow(mat, n); // get transpose of mat[][] transpose(mat, n); // again sort rows of mat[][] sortByRow(mat, n); // again get transpose of mat[][] transpose(mat, n); } // function to print the matrix void printMat(int mat[MAX_SIZE][MAX_SIZE], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << "" ""; cout << endl; } } // Driver program to test above int main() { int mat[MAX_SIZE][MAX_SIZE] = { { 4, 1, 3 }, { 9, 6, 8 }, { 5, 2, 7 } }; int n = 3; cout << ""Original Matrix:\n""; printMat(mat, n); sortMatRowAndColWise(mat, n); cout << ""\nMatrix After Sorting:\n""; printMat(mat, n); return 0; }",constant,quadratic "// C++ Program to count islands in boolean 2D matrix #include using namespace std; #define ROW 5 #define COL 5 // A function to check if a given // cell (row, col) can be included in DFS int isSafe(int M[][COL], int row, int col, bool visited[][COL]) { // row number is in range, column // number is in range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]); } // A utility function to do DFS for a // 2D boolean matrix. It only considers // the 8 neighbours as adjacent vertices void DFS(int M[][COL], int row, int col, bool visited[][COL]) { // These arrays are used to get // row and column numbers of 8 // neighbours of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited); } // The main function that returns // count of islands in a given boolean // 2D matrix int countIslands(int M[][COL]) { // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize count as 0 and // traverse through the all cells of // given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new island found // Visit all cells in this island. DFS(M, i, j, visited); // and increment island count ++count; } return count; } // Driver code int main() { int M[][COL] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << ""Number of islands is: "" << countIslands(M); return 0; } // This is code is contributed by rathbhupendra",quadratic,quadratic "// C++Program to count islands in boolean 2D matrix #include using namespace std; // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices void DFS(vector >& M, int i, int j, int ROW, int COL) { // Base condition // if i less than 0 or j less than 0 or i greater than // ROW-1 or j greater than COL- or if M[i][j] != 1 then // we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); // right side traversal DFS(M, i - 1, j, ROW, COL); // left side traversal DFS(M, i, j + 1, ROW, COL); // upward side traversal DFS(M, i, j - 1, ROW, COL); // downward side traversal DFS(M, i + 1, j + 1, ROW, COL); // upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); // downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); // downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); // upward-left side traversal } } int countIslands(vector >& M) { int ROW = M.size(); int COL = M[0].size(); int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i][j] == 1) { count++; DFS(M, i, j, ROW, COL); // traversal starts // from current cell } } } return count; } // Driver Code int main() { vector > M = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << ""Number of islands is: "" << countIslands(M); return 0; } // This code is contributed by ajaymakvana. // Code improved by Animesh Singh",quadratic,quadratic "// C++ Program to print Magic square // of Doubly even order #include using namespace std; // Function for calculating Magic square void doublyEven( int n ) { int arr[n][n], i, j; // filling matrix with its count value // starting from 1; for ( i = 0; i < n; i++) for ( j = 0; j < n; j++) arr[i][j] = (n*i) + j + 1; // change value of Array elements // at fix location as per rule // (n*n+1)-arr[i][j] // Top Left corner of Matrix // (order (n/4)*(n/4)) for ( i = 0; i < n/4; i++) for ( j = 0; j < n/4; j++) arr[i][j] = (n*n + 1) - arr[i][j]; // Top Right corner of Matrix // (order (n/4)*(n/4)) for ( i = 0; i < n/4; i++) for ( j = 3 * (n/4); j < n; j++) arr[i][j] = (n*n + 1) - arr[i][j]; // Bottom Left corner of Matrix // (order (n/4)*(n/4)) for ( i = 3 * n/4; i < n; i++) for ( j = 0; j < n/4; j++) arr[i][j] = (n*n+1) - arr[i][j]; // Bottom Right corner of Matrix // (order (n/4)*(n/4)) for ( i = 3 * n/4; i < n; i++) for ( j = 3 * n/4; j < n; j++) arr[i][j] = (n*n + 1) - arr[i][j]; // Centre of Matrix (order (n/2)*(n/2)) for ( i = n/4; i < 3 * n/4; i++) for ( j = n/4; j < 3 * n/4; j++) arr[i][j] = (n*n + 1) - arr[i][j]; // Printing the magic-square for (i = 0; i < n; i++) { for ( j = 0; j < n; j++) cout << arr[i][j] << "" ""; cout << ""\n""; } } // driver program int main() { int n=8; doublyEven(n); //Function call return 0; }",quadratic,quadratic "// C++ program to generate odd sized magic squares #include using namespace std; // A function to generate odd sized magic squares void generateSquare(int n) { int magicSquare[n][n]; // set all slots as 0 memset(magicSquare, 0, sizeof(magicSquare)); // Initialize position for 1 int i = n / 2; int j = n - 1; // One by one put all values in magic square for (int num = 1; num <= n * n;) { if (i == -1 && j == n) // 3rd condition { j = n - 2; i = 0; } else { // 1st condition helper if next number // goes to out of square's right side if (j == n) j = 0; // 1st condition helper if next number // is goes to out of square's upper side if (i < 0) i = n - 1; } if (magicSquare[i][j]) // 2nd condition { j -= 2; i++; continue; } else magicSquare[i][j] = num++; // set number j++; i--; // 1st condition } // Print magic square cout << ""The Magic Square for n="" << n << "":\nSum of "" ""each row or column "" << n * (n * n + 1) / 2 << "":\n\n""; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) // setw(7) is used so that the matrix gets // printed in a proper square fashion. cout << setw(4) << magicSquare[i][j] << "" ""; cout << endl; } } // Driver code int main() { // Works only when n is odd int n = 7; generateSquare(n); return 0; } // This code is contributed by rathbhupendra",quadratic,quadratic "// C++ program to check whether a given // matrix is magic matrix or not #include # define my_sizeof(type) ((char *)(&type+1)-(char*)(&type)) using namespace std; // Returns true if mat[][] is magic // square, else returns false. bool isMagicSquare(int mat[][3]) { int n = my_sizeof(mat)/my_sizeof(mat[0]); // calculate the sum of // the prime diagonal int i=0,j=0; // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0, sumd2=0; for (i = 0; i < n; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1 += mat[i][i]; sumd2 += mat[i][n-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // For sums of Rows for (i = 0; i < n; i++) { int rowSum = 0, colSum = 0; for (j = 0; j < n; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true; } // driver program to // test above function int main() { int mat[3][3] = {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) cout << ""Magic Square""; else cout << ""Not a magic Square""; return 0; }",constant,quadratic "// C++ program to check whether a given // matrix is magic matrix or not #include # define my_sizeof(type) ((char *)(&type+1)-(char*)(&type)) using namespace std; // Returns true if mat[][] is magic // square, else returns false. bool isMagicSquare(int mat[][3]) { int n = my_sizeof(mat)/my_sizeof(mat[0]); // calculate the sum of // the prime diagonal int i=0,j=0; // sumd1 and sumd2 are the sum of the two diagonals int sumd1 = 0, sumd2=0; for (i = 0; i < n; i++) { // (i, i) is the diagonal from top-left -> bottom-right // (i, n - i - 1) is the diagonal from top-right -> bottom-left sumd1 += mat[i][i]; sumd2 += mat[i][n-1-i]; } // if the two diagonal sums are unequal then it is not a magic square if(sumd1!=sumd2) return false; // For sums of Rows for (i = 0; i < n; i++) { int rowSum = 0, colSum = 0; for (j = 0; j < n; j++) { rowSum += mat[i][j]; colSum += mat[j][i]; } if (rowSum != colSum || colSum != sumd1) return false; } return true; } // driver program to // test above function int main() { int mat[3][3] = {{ 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 }}; if (isMagicSquare(mat)) cout << ""Magic Square""; else cout << ""Not a magic Square""; return 0; }",constant,quadratic "// C++ code to find the Kronecker Product of two // matrices and stores it as matrix C #include using namespace std; // rowa and cola are no of rows and columns // of matrix A // rowb and colb are no of rows and columns // of matrix B const int cola = 2, rowa = 3, colb = 3, rowb = 2; // Function to computes the Kronecker Product // of two matrices void Kroneckerproduct(int A[][cola], int B[][colb]) { int C[rowa * rowb][cola * colb]; // i loops till rowa for (int i = 0; i < rowa; i++) { // k loops till rowb for (int k = 0; k < cola; k++) { // j loops till cola for (int j = 0; j < rowb; j++) { // l loops till colb for (int l = 0; l < colb; l++) { // Each element of matrix A is // multiplied by whole Matrix B // resp and stored as Matrix C C[i * rowb + k][j * colb + l] = A[i][j] * B[k][l]; } } } } for (int i = 0; i < rowa * rowb; i++) { for (int j = 0; j < cola * colb; j++) { cout << C[i][j] << "" ""; } cout << endl; } } // Driver Code int main() { int A[3][2] = { { 1, 2 }, { 3, 4 }, { 1, 0 } }, B[2][3] = { { 0, 5, 2 }, { 6, 7, 3 } }; Kroneckerproduct(A, B); return 0; } // This code is contributed by shubhamsingh10",np,np "// C++ implementation to count sub-matrices having sum // divisible by the value 'k' #include using namespace std; #define SIZE 10 // function to count all sub-arrays divisible by k int subCount(int arr[], int n, int k) { // create auxiliary hash array to count frequency // of remainders int mod[k]; memset(mod, 0, sizeof(mod)); // Traverse original array and compute cumulative // sum take remainder of this current cumulative // sum and increase count by 1 for this remainder // in mod[] array int cumSum = 0; for (int i = 0; i < n; i++) { cumSum += arr[i]; // as the sum can be negative, taking modulo // twice mod[((cumSum % k) + k) % k]++; } int result = 0; // Initialize result // Traverse mod[] for (int i = 0; i < k; i++) // If there are more than one prefix subarrays // with a particular mod value. if (mod[i] > 1) result += (mod[i] * (mod[i] - 1)) / 2; // add the subarrays starting from the arr[i] // which are divisible by k itself result += mod[0]; return result; } // function to count all sub-matrices having sum // divisible by the value 'k' int countSubmatrix(int mat[SIZE][SIZE], int n, int k) { // Variable to store the final output int tot_count = 0; int left, right, i; int temp[n]; // Set the left column for (left = 0; left < n; left++) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left column // set by outer loop for (right = left; right < n; right++) { // Calculate sum between current left // and right for every row 'i' for (i = 0; i < n; ++i) temp[i] += mat[i][right]; // Count number of subarrays in temp[] // having sum divisible by 'k' and then // add it to 'tot_count' tot_count += subCount(temp, n, k); } } // required count of sub-matrices having sum // divisible by 'k' return tot_count; } // Driver program to test above int main() { int mat[][SIZE] = { { 5, -1, 6 }, { -2, 3, 8 }, { 7, 4, -9 } }; int n = 3, k = 4; cout << ""Count = "" << countSubmatrix(mat, n, k); return 0; }",linear,cubic "// CPP Program to check whether given matrix // is Diagonally Dominant Matrix. #include #define N 3 using namespace std; // check the given matrix is Diagonally // Dominant Matrix or not. bool isDDM(int m[N][N], int n) { // for each row for (int i = 0; i < n; i++) { // for each column, finding sum of each row. int sum = 0; for (int j = 0; j < n; j++) sum += abs(m[i][j]); // removing the diagonal element. sum -= abs(m[i][i]); // checking if diagonal element is less // than sum of non-diagonal element. if (abs(m[i][i]) < sum) return false; } return true; } // Driven Program int main() { int n = 3; int m[N][N] = { { 3, -2, 1 }, { 1, -3, 2 }, { -1, 2, 4 } }; (isDDM(m, n)) ? (cout << ""YES"") : (cout << ""NO""); return 0; }",constant,quadratic "// C++ Program to Find minimum number of operation required // such that sum of elements on each row and column becomes // same*/ #include using namespace std; // Function to find minimum operation required to make sum // of each row and column equals int findMinOpeartion(int matrix[][2], int n) { // Initialize the sumRow[] and sumCol[] array to 0 int sumRow[n], sumCol[n]; memset(sumRow, 0, sizeof(sumRow)); memset(sumCol, 0, sizeof(sumCol)); // Calculate sumRow[] and sumCol[] array for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { sumRow[i] += matrix[i][j]; sumCol[j] += matrix[i][j]; } // Find maximum sum value in either row or in column int maxSum = 0; for (int i = 0; i < n; ++i) { maxSum = max(maxSum, sumRow[i]); maxSum = max(maxSum, sumCol[i]); } int count = 0; for (int i = 0, j = 0; i < n && j < n;) { // Find minimum increment required in either row or // column int diff = min(maxSum - sumRow[i], maxSum - sumCol[j]); // Add difference in corresponding cell, sumRow[] // and sumCol[] array matrix[i][j] += diff; sumRow[i] += diff; sumCol[j] += diff; // Update the count variable count += diff; // If ith row satisfied, increment ith value for // next iteration if (sumRow[i] == maxSum) ++i; // If jth column satisfied, increment jth value for // next iteration if (sumCol[j] == maxSum) ++j; } return count; } // Utility function to print matrix void printMatrix(int matrix[][2], int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) cout << matrix[i][j] << "" ""; cout << ""\n""; } } // Driver code int main() { int matrix[][2] = { { 1, 2 }, { 3, 4 } }; cout << findMinOpeartion(matrix, 2) << ""\n""; printMatrix(matrix, 2); return 0; } // This code is contributed by Sania Kumari Gupta",linear,quadratic "// CPP program to find the frequency of k // in matrix where m(i, j)=i+j #include using namespace std; int find(int n, int k) { if (n + 1 >= k) return (k - 1); else return (2 * n + 1 - k); } // Driver Code int main() { int n = 4, k = 7; int freq = find(n, k); if (freq < 0) cout << "" element not exist \n ""; else cout << "" Frequency of "" << k << "" is "" << freq << ""\n""; return 0; }",constant,constant "// CPP program to print given number of 1's, // 2's, 3's ....k's in zig-zag way. #include using namespace std; // function that prints given number of 1's, // 2's, 3's ....k's in zig-zag way. void ZigZag(int rows, int columns, int numbers[]) { int k = 0; // two-dimensional array to store numbers. int arr[rows][columns]; for (int i=0; i0; j++) { // storing element. arr[i][j] = k+1; // decrement element at // kth index. numbers[k]--; // if array contains zero // then increment index to // make this next index if (numbers[k] == 0) k++; } } // for odd row. else { // for each column. for (int j=columns-1; j>=0 and numbers[k]>0; j--) { // storing element. arr[i][j] = k+1; // decrement element // at kth index. numbers[k]--; // if array contains zero then // increment index to make this // next index. if (numbers[k]==0) k++; } } } // printing the stored elements. for (int i=0;i using namespace std; const int n = 5; // function to find max product int FindMaxProduct(int arr[][n], int n) { int max = 0, result; // iterate the rows. for (int i = 0; i < n; i++) { // iterate the columns. for (int j = 0; j < n; j++) { // check the maximum product // in horizontal row. if ((j - 3) >= 0) { result = arr[i][j] * arr[i][j - 1] * arr[i][j - 2] * arr[i][j - 3]; if (max < result) max = result; } // check the maximum product // in vertical row. if ((i - 3) >= 0) { result = arr[i][j] * arr[i - 1][j] * arr[i - 2][j] * arr[i - 3][j]; if (max < result) max = result; } // check the maximum product in // diagonal (going through down - right) if ((i - 3) >= 0 && (j - 3) >= 0) { result = arr[i][j] * arr[i - 1][j - 1] * arr[i - 2][j - 2] * arr[i - 3][j - 3]; if (max < result) max = result; } // check the maximum product in // diagonal (going through up - right) if ((i - 3) >= 0 && (j - 3) <= 0) { result = arr[i][j] * arr[i - 1][j + 1] * arr[i - 2][j + 2] * arr[i - 3][j + 3]; if (max < result) max = result; } } } return max; } // Driver code int main() { /* int arr[][4] = {{6, 2, 3, 4}, {5, 4, 3, 1}, {7, 4, 5, 6}, {8, 3, 1, 0}};*/ /* int arr[][5] = {{1, 2, 1, 3, 4}, {5, 6, 3, 9, 2}, {7, 8, 8, 1, 2}, {1, 0, 7, 9, 3}, {3, 0, 8, 4, 9}};*/ int arr[][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 1}, {2, 3, 4, 5, 6}, {7, 8, 9, 1, 0}, {9, 6, 4, 2, 3}}; cout << FindMaxProduct(arr, n); return 0; }",constant,quadratic "// C++ implementation of the above approach #include using namespace std; int maxPro(int a[6][5], int n, int m, int k) { int maxi(1), mp(1); for (int i = 0; i < n; ++i) { // Window Product for each row. int wp(1); for (int l = 0; l < k; ++l) { wp *= a[i][l]; } // Maximum window product for each row mp = wp; for (int j = k; j < m; ++j) { wp = wp * a[i][j] / a[i][j - k]; // Global maximum window product maxi = max(maxi,max(mp,wp)); } } return maxi; } // Driver Code int main() { int n = 6, m = 5, k = 4; int a[6][5] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 1 }, { 2, 3, 4, 5, 6 }, { 7, 8, 9, 1, 0 }, { 9, 6, 4, 2, 3 }, { 1, 1, 2, 1, 1 } }; cout << maxPro(a, n, m, k); return 0; }",constant,quadratic "// Program to check lower // triangular matrix. #include #define N 4 using namespace std; // Function to check matrix is in // lower triangular form or not. bool isLowerTriangularMatrix(int mat[N][N]) { for (int i = 0; i < N-1; i++) for (int j = i + 1; j < N; j++) if (mat[i][j] != 0) return false; return true; } // Driver function. int main() { int mat[N][N] = { { 1, 0, 0, 0 }, { 1, 4, 0, 0 }, { 4, 6, 2, 0 }, { 0, 4, 7, 6 } }; // Function call if (isLowerTriangularMatrix(mat)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,quadratic "// Program to check upper triangular matrix. #include #define N 4 using namespace std; // Function to check matrix is in upper triangular // form or not. bool isUpperTriangularMatrix(int mat[N][N]) { for (int i = 1; i < N; i++) for (int j = 0; j < i; j++) if (mat[i][j] != 0) return false; return true; } // Driver function. int main() { int mat[N][N] = { { 1, 3, 5, 3 }, { 0, 4, 6, 2 }, { 0, 0, 2, 5 }, { 0, 0, 0, 6 } }; if (isUpperTriangularMatrix(mat)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,quadratic "// C++ Program to Find the frequency // of even and odd numbers in a matrix #include using namespace std; #define MAX 100 // function for calculating frequency void freq(int ar[][MAX], int m, int n) { int even = 0, odd = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { // modulo by 2 to check // even and odd if ((ar[i][j] % 2) == 0) ++even; else ++odd; } } // print Frequency of numbers printf("" Frequency of odd number = %d \n"", odd); printf("" Frequency of even number = %d \n"", even); } // Driver code int main() { int m = 3, n = 3; int array[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; freq(array, m, n); return 0; } ",constant,quadratic "// C++ Program to check if the center // element is equal to the individual // sum of all the half diagonals #include #include using namespace std; const int MAX = 100; // Function to Check center element // is equal to the individual // sum of all the half diagonals bool HalfDiagonalSums(int mat[][MAX], int n) { // Find sums of half diagonals int diag1_left = 0, diag1_right = 0; int diag2_left = 0, diag2_right = 0; for (int i = 0, j = n - 1; i < n; i++, j--) { if (i < n/2) { diag1_left += mat[i][i]; diag2_left += mat[j][i]; } else if (i > n/2) { diag1_right += mat[i][i]; diag2_right += mat[j][i]; } } return (diag1_left == diag2_right && diag2_right == diag2_left && diag1_right == diag2_left && diag2_right == mat[n/2][n/2]); } // Driver code int main() { int a[][MAX] = { { 2, 9, 1, 4, -2}, { 6, 7, 2, 11, 4}, { 4, 2, 9, 2, 4}, { 1, 9, 2, 4, 4}, { 0, 2, 4, 2, 5} }; cout << ( HalfDiagonalSums(a, 5) ? ""Yes"" : ""No"" ); return 0; }",constant,linear "// C++ program to print Identity Matrix #include using namespace std; int Identity(int num) { int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) cout << 1 << "" ""; else cout << 0 << "" ""; } cout << endl; } return 0; } // Driver Code int main() { int size = 5; Identity(size); return 0; } // This code is contributed by shubhamsingh10",constant,quadratic "// CPP program to check if a given matrix is identity #include using namespace std; const int MAX = 100; bool isIdentity(int mat[][MAX], int N) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true; } // Driver Code int main() { int N = 4; int mat[][MAX] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) cout << ""Yes ""; else cout << ""No ""; return 0; }",constant,quadratic "// CPP Program to implement matrix // for swapping the upper diagonal // elements with lower diagonal // elements of matrix. #include #define n 4 using namespace std; // Function to swap the diagonal // elements in a matrix. void swapUpperToLower(int arr[n][n]) { // Loop for swap the elements of matrix. for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } // Loop for print the matrix elements. for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << arr[i][j] << "" ""; cout << endl; } } // Driver function to run the program int main() { int arr[n][n] = { { 2, 3, 5, 6 }, { 4, 5, 7, 9 }, { 8, 6, 4, 9 }, { 1, 3, 5, 6 } }; // Function call swapUpperToLower(arr); return 0; }",constant,quadratic "// CPP program to find sparse matrix rep- // resentation using CSR #include #include #include using namespace std; typedef std::vector vi; typedef vector > matrix; // Utility Function to print a Matrix void printMatrix(const matrix& M) { int m = M.size(); int n = M[0].size(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << M[i][j] << "" ""; cout << endl; } } // Utility Function to print A, IA, JA vectors // with some decoration. void printVector(const vi& V, char* msg) { cout << msg << ""[ ""; for_each(V.begin(), V.end(), [](int a) { cout << a << "" ""; }); cout << ""]"" << endl; } // Generate the three vectors A, IA, JA void sparesify(const matrix& M) { int m = M.size(); int n = M[0].size(), i, j; vi A; vi IA = { 0 }; // IA matrix has N+1 rows vi JA; int NNZ = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (M[i][j] != 0) { A.push_back(M[i][j]); JA.push_back(j); // Count Number of Non Zero // Elements in row i NNZ++; } } IA.push_back(NNZ); } printMatrix(M); printVector(A, (char*)""A = ""); printVector(IA, (char*)""IA = ""); printVector(JA, (char*)""JA = ""); } // Driver code int main() { matrix M = { { 0, 0, 0, 0, 1 }, { 5, 8, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 0, 6, 0, 0, 1 }, }; sparesify(M); return 0; }",linear,quadratic "// Simple CPP program to find mirror of // matrix across diagonal. #include using namespace std; const int MAX = 100; void imageSwap(int mat[][MAX], int n) { // for diagonal which start from at // first row of matrix int row = 0; // traverse all top right diagonal for (int j = 0; j < n; j++) { // here we use stack for reversing // the element of diagonal stack s; int i = row, k = j; while (i < n && k >= 0) s.push(mat[i++][k--]); // push all element back to matrix // in reverse order i = row, k = j; while (i < n && k >= 0) { mat[i++][k--] = s.top(); s.pop(); } } // do the same process for all the // diagonal which start from last // column int column = n - 1; for (int j = 1; j < n; j++) { // here we use stack for reversing // the elements of diagonal stack s; int i = j, k = column; while (i < n && k >= 0) s.push(mat[i++][k--]); // push all element back to matrix // in reverse order i = j; k = column; while (i < n && k >= 0) { mat[i++][k--] = s.top(); s.pop(); } } } // Utility function to print a matrix void printMatrix(int mat[][MAX], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << "" ""; cout << endl; } } // driver program to test above function int main() { int mat[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int n = 4; imageSwap(mat, n); printMatrix(mat, n); return 0; }",linear,quadratic "// Efficient CPP program to find mirror of // matrix across diagonal. #include using namespace std; const int MAX = 100; void imageSwap(int mat[][MAX], int n) { // traverse a matrix and swap // mat[i][j] with mat[j][i] for (int i = 0; i < n; i++) for (int j = 0; j <= i; j++) mat[i][j] = mat[i][j] + mat[j][i] - (mat[j][i] = mat[i][j]); } // Utility function to print a matrix void printMatrix(int mat[][MAX], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << "" ""; cout << endl; } } // driver program to test above function int main() { int mat[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; int n = 4; imageSwap(mat, n); printMatrix(mat, n); return 0; }",constant,quadratic "// A brute force approach based CPP program to // find if there is a rectangle with 1 as corners. #include using namespace std; // Returns true if there is a rectangle with // 1 as corners. bool isRectangle(const vector >& m) { // finding row and column size int rows = m.size(); if (rows == 0) return false; int columns = m[0].size(); // scanning the matrix for (int y1 = 0; y1 < rows; y1++) for (int x1 = 0; x1 < columns; x1++) // if any index found 1 then try // for all rectangles if (m[y1][x1] == 1) for (int y2 = y1 + 1; y2 < rows; y2++) for (int x2 = x1 + 1; x2 < columns; x2++) if (m[y1][x2] == 1 && m[y2][x1] == 1 && m[y2][x2] == 1) return true; return false; } // Driver code int main() { vector > mat = { { 1, 0, 0, 1, 0 }, { 0, 0, 1, 0, 1 }, { 0, 0, 0, 1, 0 }, { 1, 0, 1, 0, 1 } }; if (isRectangle(mat)) cout << ""Yes""; else cout << ""No""; }",constant,quadratic "// An efficient approach based CPP program to // find if there is a rectangle with 1 as // corners. #include using namespace std; // Returns true if there is a rectangle with // 1 as corners. bool isRectangle(const vector >& matrix) { // finding row and column size int rows = matrix.size(); if (rows == 0) return false; int columns = matrix[0].size(); // map for storing the index of combination of 2 1's unordered_map > table; // scanning from top to bottom line by line for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns - 1; ++j) { for (int k = j + 1; k < columns; ++k) { // if found two 1's in a column if (matrix[i][j] == 1 && matrix[i][k] == 1) { // check if there exists 1's in same // row previously then return true // we don't need to check (j, k) pair // and again (k, j) pair because we always // store pair in ascending order and similarly // check in ascending order, i.e. j always less // than k. if (table.find(j) != table.end() && table[j].find(k) != table[j].end()) return true; // store the indexes in hashset table[j].insert(k); } } } } return false; } // Driver code int main() { vector > mat = { { 1, 0, 0, 1, 0 }, { 0, 1, 1, 1, 1 }, { 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 0 } }; if (isRectangle(mat)) cout << ""Yes""; else cout << ""No""; } // This code is improved by Gautam Agrawal",quadratic,quadratic "// C++ implementation comes from: // https://github.com/MichaelWehar/FourCornersProblem // Written by Niteesh Kumar and Michael Wehar // References: // [1] F. Mráz, D. Prusa, and M. Wehar. // Two-dimensional Pattern Matching against // Basic Picture Languages. CIAA 2019. // [2] D. Prusa and M. Wehar. Complexity of // Searching for 2 by 2 Submatrices in Boolean // Matrices. DLT 2020. #include using namespace std; bool searchForRectangle(int rows, int cols, vector> mat) { // Make sure that matrix is non-trivial if (rows < 2 || cols < 2) { return false; } // Create map int num_of_keys; map> adjsList; if (rows >= cols) { // Row-wise num_of_keys = rows; // Convert each row into vector of col indexes for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (mat[i][j]) { adjsList[i].push_back(j); } } } } else { // Col-wise num_of_keys = cols; // Convert each col into vector of row indexes for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (mat[i][j]) { adjsList[j].push_back(i); } } } } // Search for a rectangle whose four corners are 1's map, int> pairs; for (int i = 0; i < num_of_keys; i++) { vector values = adjsList[i]; int size = values.size(); for (int j = 0; j < size - 1; j++) { for (int k = j + 1; k < size; k++) { pair temp = make_pair(values[j], values[k]); if (pairs.find(temp) != pairs.end()) { return true; } else { pairs[temp] = i; } } } } return false; } // Driver code int main() { vector > mat = { { 1, 0, 0, 1, 0 }, { 0, 1, 1, 1, 1 }, { 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 0 } }; if (searchForRectangle(4, 5, mat)) cout << ""Yes""; else cout << ""No""; }",quadratic,quadratic "// C++ program for the above approach #include using namespace std; void findend(int i,int j, vector> &a, vector> &output,int index) { int x = a.size(); int y = a[0].size(); // flag to check column edge case, // initializing with 0 int flagc = 0; // flag to check row edge case, // initializing with 0 int flagr = 0; int n, m; for (m = i; m < x; m++) { // loop breaks where first 1 encounters if (a[m][j] == 1) { flagr = 1; // set the flag break; } // pass because already processed if (a[m][j] == 5) continue; for (n = j; n < y; n++) { // loop breaks where first 1 encounters if (a[m][n] == 1) { flagc = 1; // set the flag break; } // fill rectangle elements with any // number so that we can exclude // next time a[m][n] = 5; } } if (flagr == 1) output[index].push_back(m-1); else // when end point touch the boundary output[index].push_back(m); if (flagc == 1) output[index].push_back(n-1); else // when end point touch the boundary output[index].push_back(n); } void get_rectangle_coordinates(vector> a) { // retrieving the column size of array int size_of_array = a.size(); // output array where we are going // to store our output vector> output; // It will be used for storing start // and end location in the same index int index = -1; for (int i = 0; i < size_of_array; i++) { for (int j = 0; j < a[0].size(); j++) { if (a[i][j] == 0) { // storing initial position // of rectangle output.push_back({i, j}); // will be used for the // last position index = index + 1; findend(i, j, a, output, index); } } } cout << ""[""; int aa = 2, bb = 0; for(auto i:output) { bb = 3; cout << ""[""; for(int j:i) { if(bb) cout << j << "", ""; else cout << j; bb--; } cout << ""]""; if(aa) cout << "", ""; aa--; } cout << ""]""; } // Driver code int main() { vector> tests = { {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 0, 0, 0, 1}, {1, 0, 1, 0, 0, 0, 1}, {1, 0, 1, 1, 1, 1, 1}, {1, 0, 1, 0, 0, 0, 0}, {1, 1, 1, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1} }; get_rectangle_coordinates(tests); return 0; } // This code is contributed by mohit kumar 29.",quadratic,quadratic "// C++ Code implementation for above problem #include using namespace std; #define N 4 #define M 4 // QItem for current location and distance // from source location class QItem { public: int row; int col; int dist; QItem(int x, int y, int w) : row(x), col(y), dist(w) { } }; int minDistance(char grid[N][M]) { QItem source(0, 0, 0); // To keep track of visited QItems. Marking // blocked cells as visited. bool visited[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (grid[i][j] == '0') visited[i][j] = true; else visited[i][j] = false; // Finding source if (grid[i][j] == 's') { source.row = i; source.col = j; } } } // applying BFS on matrix cells starting from source queue q; q.push(source); visited[source.row][source.col] = true; while (!q.empty()) { QItem p = q.front(); q.pop(); // Destination found; if (grid[p.row][p.col] == 'd') return p.dist; // moving up if (p.row - 1 >= 0 && visited[p.row - 1][p.col] == false) { q.push(QItem(p.row - 1, p.col, p.dist + 1)); visited[p.row - 1][p.col] = true; } // moving down if (p.row + 1 < N && visited[p.row + 1][p.col] == false) { q.push(QItem(p.row + 1, p.col, p.dist + 1)); visited[p.row + 1][p.col] = true; } // moving left if (p.col - 1 >= 0 && visited[p.row][p.col - 1] == false) { q.push(QItem(p.row, p.col - 1, p.dist + 1)); visited[p.row][p.col - 1] = true; } // moving right if (p.col + 1 < M && visited[p.row][p.col + 1] == false) { q.push(QItem(p.row, p.col + 1, p.dist + 1)); visited[p.row][p.col + 1] = true; } } return -1; } // Driver code int main() { char grid[N][M] = { { '0', '*', '0', 's' }, { '*', '0', '*', '*' }, { '0', '*', '*', '*' }, { 'd', '*', '*', '*' } }; cout << minDistance(grid); return 0; }",quadratic,quadratic "// CPP program to compute number of sets // in a binary matrix. #include using namespace std; const int m = 3; // no of columns const int n = 2; // no of rows // function to calculate the number of // non empty sets of cell long long countSets(int a[n][m]) { // stores the final answer long long res = 0; // traverses row-wise for (int i = 0; i < n; i++) { int u = 0, v = 0; for (int j = 0; j < m; j++) a[i][j] ? u++ : v++; res += pow(2,u)-1 + pow(2,v)-1; } // traverses column wise for (int i = 0; i < m; i++) { int u = 0, v = 0; for (int j = 0; j < n; j++) a[j][i] ? u++ : v++; res += pow(2,u)-1 + pow(2,v)-1; } // at the end subtract n*m as no of // single sets have been added twice. return res-(n*m); } // driver program to test the above function. int main() { int a[][3] = {(1, 0, 1), (0, 1, 0)}; cout << countSets(a); return 0; }",constant,quadratic "// C++ program to search an element in row-wise // and column-wise sorted matrix #include using namespace std; /* Searches the element x in mat[][]. If the element is found, then prints its position and returns true, otherwise prints ""not found"" and returns false */ int search(int mat[4][4], int n, int x) { if (n == 0) return -1; // traverse through the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) // if the element is found if (mat[i][j] == x) { cout << ""Element found at ("" << i << "", "" << j << "")\n""; return 1; } } cout << ""n Element not found""; return 0; } // Driver code int main() { int mat[4][4] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 } }; // Function call search(mat, 4, 29); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,quadratic "// C++ program to search an element in row-wise // and column-wise sorted matrix #include using namespace std; /* Searches the element x in mat[][]. If the element is found, then prints its position and returns true, otherwise prints ""not found"" and returns false */ int search(int mat[4][4], int n, int x) { if (n == 0) return -1; int smallest = mat[0][0], largest = mat[n - 1][n - 1]; if (x < smallest || x > largest) return -1; // set indexes for top right element int i = 0, j = n - 1; while (i < n && j >= 0) { if (mat[i][j] == x) { cout << ""Element found at "" << i << "", "" << j; return 1; } if (mat[i][j] > x) j--; // Check if mat[i][j] < x else i++; } cout << ""n Element not found""; return 0; } // Driver code int main() { int mat[4][4] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 } }; // Function call search(mat, 4, 29); return 0; } // This code is contributed // by Akanksha Rai(Abby_akku)",constant,linear "#include using namespace std; // Function to print alternating rectangles of 0 and X void fill0X(int m, int n) { /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ int i, k = 0, l = 0; // Store given number of rows and columns for later use int r = m, c = n; // A 2D array to store the output to be printed char a[m][n]; char x = 'X'; // Initialize the character to be stored in a[][] // Fill characters in a[][] in spiral form. Every iteration fills // one rectangle of either Xs or Os while (k < m && l < n) { /* Fill the first row from the remaining rows */ for (i = l; i < n; ++i) a[k][i] = x; k++; /* Fill the last column from the remaining columns */ for (i = k; i < m; ++i) a[i][n-1] = x; n--; /* Fill the last row from the remaining rows */ if (k < m) { for (i = n-1; i >= l; --i) a[m-1][i] = x; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) a[i][l] = x; l++; } // Flip character for next iteration x = (x == '0')? 'X': '0'; } // Print the filled matrix for (i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout <<"" ""<< a[i][j]; cout <<""\n""; } } /* Driver program to test above functions */ int main() { puts(""Output for m = 5, n = 6""); fill0X(5, 6); puts(""\nOutput for m = 4, n = 4""); fill0X(4, 4); puts(""\nOutput for m = 3, n = 4""); fill0X(3, 4); return 0; } // This code is contributed by shivanisinghss2110",quadratic,quadratic "// C++ program to print all elements // of given matrix in diagonal order #include using namespace std; #define ROW 5 #define COL 4 // A utility function to find min // of two integers int minu(int a, int b) { return (a < b) ? a : b; } // A utility function to find min // of three integers int min(int a, int b, int c) { return minu(minu(a, b), c); } // A utility function to find // max of two integers int max(int a, int b) { return (a > b) ? a : b; } // The main function that prints given // matrix in diagonal order void diagonalOrder(int matrix[][COL]) { // There will be ROW+COL-1 lines // in the output for(int line = 1; line <= (ROW + COL - 1); line++) { /* Get column index of the first element in this line of output. The index is 0 for first ROW lines and line - ROW for remaining lines */ int start_col = max(0, line - ROW); /* Get count of elements in this line. The count of elements is equal to minimum of line number, COL-start_col and ROW */ int count = min(line, (COL - start_col), ROW); /* Print elements of this line */ for(int j = 0; j < count; j++) cout << setw(5) << matrix[minu(ROW, line) - j - 1][start_col + j]; /* Print elements of next diagonal on next line */ cout << ""\n""; } } // Utility function to print a matrix void printMatrix(int matrix[ROW][COL]) { for(int i = 0; i < ROW; i++) { for(int j = 0; j < COL; j++) cout << setw(5) << matrix[i][j]; cout << ""\n""; } } // Driver code int main() { int M[ROW][COL] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 },}; cout << ""Given matrix is "" << endl; printMatrix(M); cout << ""\nDiagonal printing of matrix is "" << endl; diagonalOrder(M); return 0; } // This code is contributed by shubhamsingh10",constant,quadratic "#include #define R 5 #define C 4 using namespace std; bool isValid(int i, int j) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } void diagonalOrder(int arr[][C]) { /* through this for loop we choose each element of first column as starting point and print diagonal starting at it. arr[0][0], arr[1][0]....arr[R-1][0] are all starting points */ for (int k = 0; k < R; k++) { cout << arr[k][0] << "" ""; // set row index for next point in // diagonal int i = k - 1; // set column index for next point in // diagonal int j = 1; /* Print Diagonally upward */ while (isValid(i, j)) { cout << arr[i][j] << "" ""; i--; // move in upright direction j++; } cout << endl; } /* through this for loop we choose each element of last row as starting point (except the [0][c-1] it has already been processed in previous for loop) and print diagonal starting at it. arr[R-1][0], arr[R-1][1]....arr[R-1][c-1] are all starting points */ // Note : we start from k = 1 to C-1; for (int k = 1; k < C; k++) { cout << arr[R - 1][k] << "" ""; // set row index for next point in // diagonal int i = R - 2; // set column index for next point in // diagonal int j = k + 1; /* Print Diagonally upward */ while (isValid(i, j)) { cout << arr[i][j] << "" ""; i--; // move in upright direction j++; } cout << endl; } } // Driver Code int main() { int arr[][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; diagonalOrder(arr); return 0; }",constant,quadratic "#include #define R 5 #define C 4 using namespace std; void diagonalOrder(int arr[][C], int n, int m) { // we will use a 2D vector to // store the diagonals of our array // the 2D vector will have (n+m-1) // rows that is equal to the number of // diagonals vector > ans(n + m - 1); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { ans[i + j].push_back(arr[j][i]); } } for (int i = 0; i < ans.size(); i++) { for (int j = 0; j < ans[i].size(); j++) cout << ans[i][j] << "" ""; cout << endl; } } // Driver Code int main() { // we have a matrix of n rows // and m columns int n = 5, m = 4; int arr[][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, }; // Function call diagonalOrder(arr, n, m); return 0; }",linear,quadratic "// C++ implementation to find the total energy // required to rearrange the numbers #include using namespace std; #define SIZE 100 // function to find the total energy // required to rearrange the numbers int calculateEnergy(int mat[SIZE][SIZE], int n) { int i_des, j_des, q; int tot_energy = 0; // nested loops to access the elements // of the given matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // store quotient q = mat[i][j] / n; // final destination location (i_des, j_des) of // the element mat[i][j] is being calculated i_des = q; j_des = mat[i][j] - (n * q); // energy required for the movement of the // element mat[i][j] is calculated and then // accumulated in the 'tot_energy' tot_energy += abs(i_des - i) + abs(j_des - j); } } // required total energy return tot_energy; } // Driver program to test above int main() { int mat[SIZE][SIZE] = { { 4, 7, 0, 3 }, { 8, 5, 6, 1 }, { 9, 11, 10, 2 }, { 15, 13, 14, 12 } }; int n = 4; cout << ""Total energy required = "" << calculateEnergy(mat, n) << "" units""; return 0; }",constant,quadratic "// C++ program to count unique cells in // a matrix #include using namespace std; const int MAX = 100; // Returns true if mat[i][j] is unique bool isUnique(int mat[][MAX], int i, int j, int n, int m) { // checking in row calculating sumrow // will be moving column wise int sumrow = 0; for (int k = 0; k < m; k++) { sumrow += mat[i][k]; if (sumrow > 1) return false; } // checking in column calculating sumcol // will be moving row wise int sumcol = 0; for (int k = 0; k < n; k++) { sumcol += mat[k][j]; if (sumcol > 1) return false; } return true; } int countUnique(int mat[][MAX], int n, int m) { int uniquecount = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (mat[i][j] && isUnique(mat, i, j, n, m)) uniquecount++; return uniquecount; } // Driver code int main() { int mat[][MAX] = {{0, 1, 0, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}}; cout << countUnique(mat, 3, 4); return 0; }",constant,quadratic "// Efficient C++ program to count unique // cells in a binary matrix #include using namespace std; const int MAX = 100; int countUnique(int mat[][MAX], int n, int m) { int rowsum[n], colsum[m]; memset(colsum, 0, sizeof(colsum)); memset(rowsum, 0, sizeof(rowsum)); // Count number of 1s in each row // and in each column for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (mat[i][j]) { rowsum[i]++; colsum[j]++; } // Using above count arrays, find // cells int uniquecount = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (mat[i][j] && rowsum[i] == 1 && colsum[j] == 1) uniquecount++; return uniquecount; } // Driver code int main() { int mat[][MAX] = {{0, 1, 0, 0}, {0, 0, 1, 0}, {1, 0, 0, 1}}; cout << countUnique(mat, 3, 4); return 0; }",linear,quadratic "// CPP program for counting number of cell // equals to given x #include using namespace std; // function to count factors as number of cell int count (int n, int x) { int count=0; // traverse and find the factors for (int i=1; i<=n && i<=x ; i++) { // x%i == 0 means i is factor of x // x/i <= n means i and j are <= n (for i*j=x) if ( x/i <= n && x%i ==0) count++; } // return count return count; } // driver program int main() { int n = 8; // we can manually assume matrix of order 8*8 // where mat[i][j] = i*j , 0 using namespace std; const int MAX = 100; bool isSparse(int array[][MAX], int m, int n) { int counter = 0; // Count number of zeros in the matrix for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (array[i][j] == 0) ++counter; return (counter > ((m * n) / 2)); } // Driver Function int main() { int array[][MAX] = { { 1, 0, 3 }, { 0, 0, 4 }, { 6, 0, 0 } }; int m = 3, n = 3; if (isSparse(array, m, n)) cout << ""Yes""; else cout << ""No""; }",constant,quadratic "// CPP program to find common elements in // two diagonals. #include #define MAX 100 using namespace std; // Returns count of row wise same // elements in two diagonals of // mat[n][n] int countCommon(int mat[][MAX], int n) { int res = 0; for (int i=0;i using namespace std; const int MAX = 100; // Function to check the if sum of a row // is same as corresponding column bool areSumSame(int a[][MAX], int n, int m) { int sum1 = 0, sum2 = 0; for (int i = 0; i < min(n, m); i++) { sum1 = 0, sum2 = 0; for (int j = 0; j < min(n, m); j++) { sum1 += a[i][j]; sum2 += a[j][i]; } if (sum1 == sum2) return true; } return false; } // Driver Code int main() { int n = 4; // number of rows int m = 4; // number of columns int M[n][MAX] = { { 1, 2, 3, 4 }, { 9, 5, 3, 1 }, { 0, 3, 5, 6 }, { 0, 4, 5, 6 } }; cout << areSumSame(M, n, m) << ""\n""; return 0; }",constant,linear "// CPP program to find row with maximum 1 // in row sorted binary matrix #include #define N 4 using namespace std; // function for finding row with maximum 1 void findMax (int arr[][N]) { int row = 0, i, j; for (i=0, j=N-1; i= 0) { row = i; j--; } } cout << ""Row number = "" << row+1; cout << "", MaxCount = "" << N-1-j; } // driver program int main() { int arr[N][N] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1}; findMax(arr); return 0; }",constant,linear "// Simple c++ code for check a matrix is // symmetric or not. #include using namespace std; const int MAX = 100; // Fills transpose of mat[N][N] in tr[N][N] void transpose(int mat[][MAX], int tr[][MAX], int N) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) tr[i][j] = mat[j][i]; } // Returns true if mat[N][N] is symmetric, else false bool isSymmetric(int mat[][MAX], int N) { int tr[N][MAX]; transpose(mat, tr, N); for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != tr[i][j]) return false; return true; } // Driver code int main() { int mat[][MAX] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) cout << ""Yes""; else cout << ""No""; return 0; }",quadratic,quadratic "// Efficient c++ code for check a matrix is // symmetric or not. #include using namespace std; const int MAX = 100; // Returns true if mat[N][N] is symmetric, else false bool isSymmetric(int mat[][MAX], int N) { for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (mat[i][j] != mat[j][i]) return false; return true; } // Driver code int main() { int mat[][MAX] = { { 1, 3, 5 }, { 3, 2, 4 }, { 5, 4, 1 } }; if (isSymmetric(mat, 3)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,quadratic "// C++ program for the above approach #include using namespace std; // function which tells all cells are visited or not bool isAllCellTraversed(vector>>grid, int n, int m) { bool visited[n][m]; int total = n*m; // starting cell values int startx = grid[0][0].first; int starty = grid[0][0].second; for (int i = 0; i < total - 2; i++) { // if we get {0,0} before the end of loop // then returns false. Because it means we // didn't traverse all the cells if (grid[startx][starty].first == -1 and grid[startx][starty].second == -1) return false; // If found cycle then return false if (visited[startx][starty] == true) return false; visited[startx][starty] = true; int x = grid[startx][starty].first; int y = grid[startx][starty].second; // Update startx and starty values to next // cell values startx = x; starty = y; } // finally if we reach our goal then returns true if (grid[startx][starty].first == -1 and grid[startx][starty].second == -1) return true; return false; } // Driver code int main() { vector>> cell(3, vector> (2)); cell[0][0] = {0, 1}; cell[0][1] = {2, 0}; cell[1][0] = {-1,-1}; cell[1][1] = {1, 0}; cell[2][0] = {2, 1}; cell[2][1] = {1, 1}; if(!isAllCellTraversed(cell, 3, 2)) cout << ""true""; else cout << ""false""; return 0; } // This code is contributed by mohit kumar 29.",quadratic,linear "// CPP program to find number of possible moves of knight #include #define n 4 #define m 4 using namespace std; // To calculate possible moves int findPossibleMoves(int mat[n][m], int p, int q) { // All possible moves of a knight int X[8] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int Y[8] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible move is valid or not for (int i = 0; i < 8; i++) { // Position of knight after move int x = p + X[i]; int y = q + Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count++; } // Return number of possible moves return count; } // Driver program to check findPossibleMoves() int main() { int mat[n][m] = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 } }; int p = 2, q = 2; cout << findPossibleMoves(mat, p, q); return 0; }",constant,constant "// A simple C++ program to find sum of diagonals #include using namespace std; const int MAX = 100; void printDiagonalSums(int mat[][MAX], int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Condition for principal diagonal if (i == j) principal += mat[i][j]; // Condition for secondary diagonal if ((i + j) == (n - 1)) secondary += mat[i][j]; } } cout << ""Principal Diagonal:"" << principal << endl; cout << ""Secondary Diagonal:"" << secondary << endl; } // Driver code int main() { int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); return 0; }",constant,quadratic "// An efficient C++ program to find sum of diagonals #include using namespace std; const int MAX = 100; void printDiagonalSums(int mat[][MAX], int n) { int principal = 0, secondary = 0; for (int i = 0; i < n; i++) { principal += mat[i][i]; secondary += mat[i][n - i - 1]; } cout << ""Principal Diagonal:"" << principal << endl; cout << ""Secondary Diagonal:"" << secondary << endl; } // Driver code int main() { int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; printDiagonalSums(a, 4); return 0; }",constant,linear "// C++ program to print boundary element of // matrix. #include using namespace std; const int MAX = 100; void printBoundary(int a[][MAX], int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0 || i == n - 1 || j == n - 1) cout << a[i][j] << "" ""; else cout << "" "" << "" ""; } cout << ""\n""; } } // Driver code int main() { int a[4][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; // Function call printBoundary(a, 4, 4); return 0; }",constant,quadratic "// C++ program to find sum of boundary elements // of matrix. #include using namespace std; const int MAX = 100; int getBoundarySum(int a[][MAX], int m, int n) { long long int sum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0) sum += a[i][j]; else if (i == m - 1) sum += a[i][j]; else if (j == 0) sum += a[i][j]; else if (j == n - 1) sum += a[i][j]; } } return sum; } // Driver code int main() { int a[][MAX] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 5, 6, 7, 8 } }; // Function call long long int sum = getBoundarySum(a, 4, 4); cout << ""Sum of boundary elements is "" << sum; return 0; }",constant,quadratic "// C++ program to print a matrix in spiral // form. #include using namespace std; const int MAX = 100; void printSpiral(int mat[][MAX], int r, int c) { int i, a = 0, b = 2; int low_row = (0 > a) ? 0 : a; int low_column = (0 > b) ? 0 : b - 1; int high_row = ((a + 1) >= r) ? r - 1 : a + 1; int high_column = ((b + 1) >= c) ? c - 1 : b + 1; while ((low_row > 0 - r && low_column > 0 - c)) { for (i = low_column + 1; i <= high_column && i < c && low_row >= 0; ++i) cout << mat[low_row][i] << "" ""; low_row -= 1; for (i = low_row + 2; i <= high_row && i < r && high_column < c; ++i) cout << mat[i][high_column] << "" ""; high_column += 1; for (i = high_column - 2; i >= low_column && i >= 0 && high_row < r; --i) cout << mat[high_row][i] << "" ""; high_row += 1; for (i = high_row - 2; i > low_row && i >= 0 && low_column >= 0; --i) cout << mat[i][low_column] << "" ""; low_column -= 1; } cout << endl; } // Driver code int main() { int mat[][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int r = 3, c = 3; printSpiral(mat, r, c); }",constant,quadratic "// C++ program to print matrix in snake order #include #define M 4 #define N 4 using namespace std; void print(int mat[M][N]) { // Traverse through all rows for (int i = 0; i < M; i++) { // If current row is even, print from // left to right if (i % 2 == 0) { for (int j = 0; j < N; j++) cout << mat[i][j] << "" ""; // If current row is odd, print from // right to left } else { for (int j = N - 1; j >= 0; j--) cout << mat[i][j] << "" ""; } } } // Driver code int main() { int mat[M][N] = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 } }; print(mat); return 0; }",constant,quadratic "// C++ program to find the difference // between the sum of diagonal. #include #define MAX 100 using namespace std; int difference(int arr[][MAX], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return abs(d1 - d2); } // Driven Program int main() { int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0; }",constant,quadratic "// C++ program to find the difference // between the sum of diagonal. #include #define MAX 100 using namespace std; int difference(int arr[][MAX], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { // d1 store the sum of diagonal from // top-left to bottom-right d1 += arr[i][i]; // d2 store the sum of diagonal from // top-right to bottom-left d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return abs(d1 - d2); } // Driven Program int main() { int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0; }",constant,linear "// C++ program to construct ancestor matrix for // given tree. #include using namespace std; #define MAX 100 /* A binary tree node */ struct Node { int data; Node *left, *right; }; // Creating a global boolean matrix for simplicity bool mat[MAX][MAX]; // anc[] stores all ancestors of current node. This // function fills ancestors for all nodes. // It also returns size of tree. Size of tree is // used to print ancestor matrix. int ancestorMatrixRec(Node *root, vector &anc) { /* base case */ if (root == NULL) return 0;; // Update all ancestors of current node int data = root->data; for (int i=0; ileft, anc); int r = ancestorMatrixRec(root->right, anc); // Remove data from list the list of ancestors // as all descendants of it are processed now. anc.pop_back(); return l+r+1; } // This function mainly calls ancestorMatrixRec() void ancestorMatrix(Node *root) { // Create an empty ancestor array vector anc; // Fill ancestor matrix and find size of // tree. int n = ancestorMatrixRec(root, anc); // Print the filled values for (int i=0; idata = data; node->left = node->right = NULL; return (node); } /* Driver program to test above functions*/ int main() { /* Construct the following binary tree 5 / \ 1 2 / \ / 0 4 3 */ Node *root = newnode(5); root->left = newnode(1); root->right = newnode(2); root->left->left = newnode(0); root->left->right = newnode(4); root->right->left = newnode(3); ancestorMatrix(root); return 0; }",quadratic,quadratic "// C++ program to construct ancestor matrix for // given tree. #include using namespace std; #define size 6 int M[size][size]={0}; /* A binary tree node */ struct Node { int data; Node *left, *right; }; /* Helper function to create a new node */ Node* newnode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } void printMatrix(){ for(int i=0;idata; //Since there is no ancestor for root node, // so we doesn't assign it's value as 1 if(index==-1)index=root->data; else M[index][preData]=1; MatrixUtil(root->left,preData); MatrixUtil(root->right,preData); } void Matrix(Node *root){ // Call Func MatrixUtil MatrixUtil(root,-1); //Applying Transitive Closure for the given Matrix for(int i=0;ileft = newnode(1); root->right = newnode(2); root->left->left = newnode(0); root->left->right = newnode(4); root->right->left = newnode(3); Matrix(root); return 0; }",quadratic,quadratic "// Given an ancestor matrix for binary tree, construct // the tree. #include using namespace std; # define N 6 /* A binary tree node */ struct Node { int data; Node *left, *right; }; /* Helper function to create a new node */ Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node); } // Constructs tree from ancestor matrix Node* ancestorTree(int mat[][N]) { // Binary array to determine whether // parent is set for node i or not int parent[N] = {0}; // Root will store the root of the constructed tree Node* root = NULL; // Create a multimap, sum is used as key and row // numbers are used as values multimap mm; for (int i = 0; i < N; i++) { int sum = 0; // Initialize sum of this row for (int j = 0; j < N; j++) sum += mat[i][j]; // insert(sum, i) pairs into the multimap mm.insert(pair(sum, i)); } // node[i] will store node for i in constructed tree Node* node[N]; // Traverse all entries of multimap. Note that values // are accessed in increasing order of sum for (auto it = mm.begin(); it != mm.end(); ++it) { // create a new node for every value node[it->second] = newNode(it->second); // To store last processed node. This node will be // root after loop terminates root = node[it->second]; // if non-leaf node if (it->first != 0) { // traverse row 'it->second' in the matrix for (int i = 0; i < N; i++) { // if parent is not set and ancestor exits if (!parent[i] && mat[it->second][i]) { // check for unoccupied left/right node // and set parent of node i if (!node[it->second]->left) node[it->second]->left = node[i]; else node[it->second]->right = node[i]; parent[i] = 1; } } } } return root; } /* Given a binary tree, print its nodes in inorder */ void printInorder(Node* node) { if (node == NULL) return; printInorder(node->left); printf(""%d "", node->data); printInorder(node->right); } // Driver code int main() { int mat[N][N] = {{ 0, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1, 0 }, { 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 1, 0 } }; Node* root = ancestorTree(mat); cout << ""Inorder traversal of tree is \n""; // Function call printInorder(root); return 0; }",quadratic,quadratic "// C++ program to fill a matrix with values from // 1 to n*n in spiral fashion. #include using namespace std; const int MAX = 100; // Fills a[m][n] with values from 1 to m*n in // spiral fashion. void spiralFill(int m, int n, int a[][MAX]) { // Initialize value to be filled in matrix int val = 1; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int k = 0, l = 0; while (k < m && l < n) { /* Print the first row from the remaining rows */ for (int i = l; i < n; ++i) a[k][i] = val++; k++; /* Print the last column from the remaining columns */ for (int i = k; i < m; ++i) a[i][n-1] = val++; n--; /* Print the last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) a[m-1][i] = val++; m--; } /* Print the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) a[i][l] = val++; l++; } } } /* Driver program to test above functions */ int main() { int m = 4, n = 4; int a[MAX][MAX]; spiralFill(m, n, a); for (int i=0; i using namespace std; class Sudoku { public: int** mat; int N; // number of columns/rows. int SRN; // square root of N int K; // No. Of missing digits // Constructor Sudoku(int N, int K) { this->N = N; this->K = K; // Compute square root of N double SRNd = sqrt(N); SRN = (int)SRNd; mat = new int*[N]; // Create a row for every pointer for (int i = 0; i < N; i++) { // Note : Rows may not be contiguous mat[i] = new int[N]; // Initialize all entries as false to indicate // that there are no edges initially memset(mat[i], 0, N * sizeof(int)); } } // Sudoku Generator void fillValues() { // Fill the diagonal of SRN x SRN matrices fillDiagonal(); // Fill remaining blocks fillRemaining(0, SRN); // Remove Randomly K digits to make game removeKDigits(); } // Fill the diagonal SRN number of SRN x SRN matrices void fillDiagonal() { for (int i = 0; i < N; i = i + SRN) { // for diagonal box, start coordinates->i==j fillBox(i, i); } } // Returns false if given 3 x 3 block contains num. bool unUsedInBox(int rowStart, int colStart, int num) { for (int i = 0; i < SRN; i++) { for (int j = 0; j < SRN; j++) { if (mat[rowStart + i][colStart + j] == num) { return false; } } } return true; } // Fill a 3 x 3 matrix. void fillBox(int row, int col) { int num; for (int i = 0; i < SRN; i++) { for (int j = 0; j < SRN; j++) { do { num = randomGenerator(N); } while (!unUsedInBox(row, col, num)); mat[row + i][col + j] = num; } } } // Random generator int randomGenerator(int num) { return (int)floor( (float)(rand() / double(RAND_MAX) * num + 1)); } // Check if safe to put in cell bool CheckIfSafe(int i, int j, int num) { return ( unUsedInRow(i, num) && unUsedInCol(j, num) && unUsedInBox(i - i % SRN, j - j % SRN, num)); } // check in the row for existence bool unUsedInRow(int i, int num) { for (int j = 0; j < N; j++) { if (mat[i][j] == num) { return false; } } return true; } // check in the row for existence bool unUsedInCol(int j, int num) { for (int i = 0; i < N; i++) { if (mat[i][j] == num) { return false; } } return true; } // A recursive function to fill remaining // matrix bool fillRemaining(int i, int j) { // System.out.println(i+"" ""+j); if (j >= N && i < N - 1) { i = i + 1; j = 0; } if (i >= N && j >= N) { return true; } if (i < SRN) { if (j < SRN) { j = SRN; } } else if (i < N - SRN) { if (j == (int)(i / SRN) * SRN) { j = j + SRN; } } else { if (j == N - SRN) { i = i + 1; j = 0; if (i >= N) { return true; } } } for (int num = 1; num <= N; num++) { if (CheckIfSafe(i, j, num)) { mat[i][j] = num; if (fillRemaining(i, j + 1)) { return true; } mat[i][j] = 0; } } return false; } // Remove the K no. of digits to // complete game void removeKDigits() { int count = K; while (count != 0) { int cellId = randomGenerator(N * N) - 1; // System.out.println(cellId); // extract coordinates i and j int i = (cellId / N); int j = cellId % 9; if (j != 0) { j = j - 1; } // System.out.println(i+"" ""+j); if (mat[i][j] != 0) { count--; mat[i][j] = 0; } } } // Print sudoku void printSudoku() { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << to_string(mat[i][j]) + "" ""; } cout << endl; } cout << endl; } }; // Driver code int main() { int N = 9; int K = 20; Sudoku* sudoku = new Sudoku(N, K); sudoku->fillValues(); sudoku->printSudoku(); return 0; } // This code is contributed by Aarti_Rathi",quadratic,quadratic "#include using namespace std; // change row and column value to set the canvas size const int row = 5; const int col = 4; // creates row boundary int row_line() { cout << endl; for (int i = 0; i < col; i++) { cout << "" -----""; } cout << endl; } // returns the count of alive neighbours int count_live_neighbour_cell(int a[row][col], int r, int c) { int i, j, count = 0; for (i = r - 1; i <= r + 1; i++) { for (j = c - 1; j <= c + 1; j++) { if ((i == r && j == c) || (i < 0 || j < 0) || (i >= row || j >= col)) { continue; } if (a[i][j] == 1) { count++; } } } return count; } int main() { int a[row][col], b[row][col]; int i, j; int neighbour_live_cell; // generate matrix canvas with random values (live and // dead cells) for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { a[i][j] = rand() % 2; } } // print array matrix cout << ""Initial Stage:""; row_line(); for (i = 0; i < row; i++) { cout << "":""; for (j = 0; j < col; j++) { cout << "" "" << a[i][j] << "" :""; } row_line(); } // next canvas values based on live neighbour count for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { neighbour_live_cell = count_live_neighbour_cell(a, i, j); if (a[i][j] == 1 && (neighbour_live_cell == 2 || neighbour_live_cell == 3)) { b[i][j] = 1; } else if (a[i][j] == 0 && neighbour_live_cell == 3) { b[i][j] = 1; } else { b[i][j] = 0; } } } // print next generation cout << ""\nNext Generation:""; row_line(); for (i = 0; i < row; i++) { cout << "":""; for (j = 0; j < col; j++) { cout << "" "" << b[i][j] << "" :""; } row_line(); } return 0; } /* ###################################### OUTPUT #################################### Initial Stage: ----- ----- ----- ----- : 1 : 1 : 0 : 0 : ----- ----- ----- ----- : 1 : 0 : 0 : 0 : ----- ----- ----- ----- : 0 : 0 : 1 : 1 : ----- ----- ----- ----- : 1 : 1 : 1 : 1 : ----- ----- ----- ----- : 1 : 0 : 1 : 0 : ----- ----- ----- ----- Next Generation: ----- ----- ----- ----- : 1 : 1 : 0 : 0 : ----- ----- ----- ----- : 1 : 0 : 1 : 0 : ----- ----- ----- ----- : 1 : 0 : 0 : 1 : ----- ----- ----- ----- : 1 : 0 : 0 : 0 : ----- ----- ----- ----- : 1 : 0 : 1 : 1 : ----- ----- ----- ----- */ // This code is contributed by Tapesh(tapeshdua420)",quadratic,quadratic "// C++ program to find maximum sum of hour // glass in matrix #include using namespace std; const int R = 5; const int C = 5; // Returns maximum sum of hour glass in ar[][] int findMaxSum(int mat[R][C]) { if (R<3 || C<3){ cout << ""Not possible"" << endl; exit(0); } // Here loop runs (R-2)*(C-2) times considering // different top left cells of hour glasses. int max_sum = INT_MIN; for (int i=0; i using namespace std; #define MAX 100 // Finds maximum and minimum in arr[0..n-1][0..n-1] // using pair wise comparisons void maxMin(int arr[][MAX], int n) { int min = INT_MAX; int max = INT_MIN; // Traverses rows one by one for (int i = 0; i < n; i++) { for (int j = 0; j <= n/2; j++) { // Compare elements from beginning // and end of current row if (arr[i][j] > arr[i][n-j-1]) { if (min > arr[i][n-j-1]) min = arr[i][n-j-1]; if (max< arr[i][j]) max = arr[i][j]; } else { if (min > arr[i][j]) min = arr[i][j]; if (max< arr[i][n-j-1]) max = arr[i][n-j-1]; } } } cout << ""Maximum = "" << max << "", Minimum = "" << min; } /* Driver program to test above function */ int main() { int arr[MAX][MAX] = {5, 9, 11, 25, 0, 14, 21, 6, 4}; maxMin(arr, 3); return 0; }",constant,quadratic "// C++ program to print matrix in anti-spiral form #include using namespace std; #define R 4 #define C 5 void antiSpiralTraversal(int m, int n, int a[R][C]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ stack stk; while (k <= m && l <= n) { /* Print the first row from the remaining rows */ for (i = l; i <= n; ++i) stk.push(a[k][i]); k++; /* Print the last column from the remaining columns */ for (i = k; i <= m; ++i) stk.push(a[i][n]); n--; /* Print the last row from the remaining rows */ if ( k <= m) { for (i = n; i >= l; --i) stk.push(a[m][i]); m--; } /* Print the first column from the remaining columns */ if (l <= n) { for (i = m; i >= k; --i) stk.push(a[i][l]); l++; } } while (!stk.empty()) { cout << stk.top() << "" ""; stk.pop(); } } /* Driver program to test above functions */ int main() { int mat[R][C] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} }; antiSpiralTraversal(R-1, C-1, mat); return 0; }",quadratic,quadratic "// C++ program to find trace and normal // of given matrix #include using namespace std; // Size of given matrix const int MAX = 100; // Returns Normal of a matrix of size n x n int findNormal(int mat[][MAX], int n) { int sum = 0; for (int i=0; i #define N 5 #define M 5 using namespace std; // Return minimum operation required to make all 1s. int minOperation(bool arr[N][M]) { int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = M - 1; j >= 0; j--) { // check if this cell equals 0 if(arr[i][j] == 0) { // increase the number of moves ans++; // flip from this cell to the start point for (int k = 0; k <= i; k++) { for (int h = 0; h <= j; h++) { // flip the cell if (arr[k][h] == 1) arr[k][h] = 0; else arr[k][h] = 1; } } } } } return ans; } // Driven Program int main() { bool mat[N][M] = { 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; cout << minOperation(mat) << endl; return 0; }",quadratic,quadratic "// This is a modified code of // https://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ #include #define R 3 #define C 6 using namespace std; // Function that print matrix in reverse spiral form. void ReversespiralPrint(int m, int n, int a[R][C]) { // Large array to initialize it // with elements of matrix long int b[100]; /* k - starting row index l - starting column index*/ int i, k = 0, l = 0; // Counter for single dimension array //in which elements will be stored int z = 0; // Total elements in matrix int size = m*n; while (k < m && l < n) { // Variable to store value of matrix. int val; /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { // printf(""%d "", a[k][i]); val = a[k][i]; b[z] = val; ++z; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { // printf(""%d "", a[i][n-1]); val = a[i][n-1]; b[z] = val; ++z; } n--; /* Print the last row from the remaining rows */ if ( k < m) { for (i = n-1; i >= l; --i) { // printf(""%d "", a[m-1][i]); val = a[m-1][i]; b[z] = val; ++z; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m-1; i >= k; --i) { // printf(""%d "", a[i][l]); val = a[i][l]; b[z] = val; ++z; } l++; } } for (int i=size-1 ; i>=0 ; --i) { cout< using namespace std; // Return sum of matrix element where each element // is division of its corresponding row and column. int findSum(int n) { int ans = 0; for (int i = 1; i <= n; i++) // for rows for (int j = 1; j <= n; j++) // for columns ans += (i/j); return ans; } // Driven Program int main() { int N = 2; cout << findSum(N) << endl; return 0; }",constant,quadratic "// C++ program to find sum of matrix element // where each element is integer division of // row and column. #include using namespace std; // Return sum of matrix element where each // element is division of its corresponding // row and column. int findSum(int n) { int ans = 0, temp = 0, num; // For each column. for (int i = 1; i <= n && temp < n; i++) { // count the number of elements of // each column. Initialize to i -1 // because number of zeroes are i - 1. temp = i - 1; // For multiply num = 1; while (temp < n) { if (temp + i <= n) ans += (i * num); else ans += ((n - temp) * num); temp += i; num ++; } } return ans; } // Driven Program int main() { int N = 2; cout << findSum(N) << endl; return 0; }",constant,quadratic "// C++ program to find // number of countOpsation // to make two matrix equals #include using namespace std; const int MAX = 1000; int countOps(int A[][MAX], int B[][MAX], int m, int n) { // Update matrix A[][] // so that only A[][] // has to be countOpsed for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) A[i][j] -= B[i][j]; // Check necessary condition // for condition for // existence of full countOpsation for (int i = 1; i < n; i++) for (int j = 1; j < m; j++) if (A[i][j] - A[i][0] - A[0][j] + A[0][0] != 0) return -1; // If countOpsation is possible // calculate total countOpsation int result = 0; for (int i = 0; i < n; i++) result += abs(A[i][0]); for (int j = 0; j < m; j++) result += abs(A[0][j] - A[0][0]); return (result); } // Driver code int main() { int A[MAX][MAX] = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1}}; int B[MAX][MAX] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; cout << countOps(A, B, 3, 3) ; return 0; }",constant,quadratic "// C++ program to print 2 coils of a // 4n x 4n matrix. #include using namespace std; // Print coils in a matrix of size 4n x 4n void printCoils(int n) { // Number of elements in each coil int m = 8*n*n; // Let us fill elements in coil 1. int coil1[m]; // First element of coil1 // 4*n*2*n + 2*n; coil1[0] = 8*n*n + 2*n; int curr = coil1[0]; int nflg = 1, step = 2; // Fill remaining m-1 elements in coil1[] int index = 1; while (index < m) { // Fill elements of current step from // down to up for (int i=0; i= m) break; } if (index >= m) break; // Fill elements of current step from // up to down. for (int i=0; i= m) break; } nflg = nflg*(-1); step += 2; } /* get coil2 from coil1 */ int coil2[m]; for (int i=0; i<8*n*n; i++) coil2[i] = 16*n*n + 1 -coil1[i]; // Print both coils cout << ""Coil 1 : ""; for(int i=0; i<8*n*n; i++) cout << coil1[i] << "" ""; cout << ""\nCoil 2 : ""; for (int i=0; i<8*n*n; i++) cout << coil2[i] << "" ""; } // Driver code int main() { int n = 1; printCoils(n); return 0; }",quadratic,quadratic "// C++ program to find sum of matrix in which each // element is absolute difference of its corresponding // row and column number row. #include using namespace std; // Return the sum of matrix in which each element // is absolute difference of its corresponding row // and column number row int findSum(int n) { // Generate matrix int arr[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) arr[i][j] = abs(i - j); // Compute sum int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += arr[i][j]; return sum; } // Driven Program int main() { int n = 3; cout << findSum(n) << endl; return 0; }",quadratic,quadratic "// C++ program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. #include using namespace std; // Return the sum of matrix in which each // element is absolute difference of its // corresponding row and column number row int findSum(int n) { int sum = 0; for (int i = 0; i < n; i++) sum += i*(n-i); return 2*sum; } // Driven Program int main() { int n = 3; cout << findSum(n) << endl; return 0; }",constant,linear "// C++ program to find sum of matrix in which // each element is absolute difference of its // corresponding row and column number row. #include using namespace std; // Return the sum of matrix in which each element // is absolute difference of its corresponding // row and column number row int findSum(int n) { n--; int sum = 0; sum += (n*(n+1))/2; sum += (n*(n+1)*(2*n + 1))/6; return sum; } // Driven Program int main() { int n = 3; cout << findSum(n) << endl; return 0; }",constant,constant "// C++ program to find if a matrix is symmetric. #include #define MAX 1000 using namespace std; void checkHV(int arr[][MAX], int N, int M) { // Initializing as both horizontal and vertical // symmetric. bool horizontal = true, vertical = true; // Checking for Horizontal Symmetry. We compare // first row with last row, second row with second // last row and so on. for (int i = 0, k = N - 1; i < N / 2; i++, k--) { // Checking each cell of a column. for (int j = 0; j < M; j++) { // check if every cell is identical if (arr[i][j] != arr[k][j]) { horizontal = false; break; } } } // Checking for Vertical Symmetry. We compare // first column with last column, second column // with second last column and so on. for (int j = 0, k = M - 1; j < M / 2; j++, k--) { // Checking each cell of a row. for (int i = 0; i < N; i++) { // check if every cell is identical if (arr[i][j] != arr[i][k]) { vertical = false; break; } } } if (!horizontal && !vertical) cout << ""NO\n""; else if (horizontal && !vertical) cout << ""HORIZONTAL\n""; else if (vertical && !horizontal) cout << ""VERTICAL\n""; else cout << ""BOTH\n""; } // Driven Program int main() { int mat[MAX][MAX] = { { 0, 1, 0 }, { 0, 0, 0 }, { 0, 1, 0 } }; checkHV(mat, 3, 3); return 0; }",constant,quadratic "// C++ program to find maximum possible determinant // of 0/n matrix. #include using namespace std; // Function for maximum determinant int maxDet(int n) { return (2*n*n*n); } // Function to print resultant matrix void resMatrix ( int n) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // three position where 0 appears if (i == 0 && j == 2) cout << ""0 ""; else if (i == 1 && j == 0) cout << ""0 ""; else if (i == 2 && j == 1) cout << ""0 ""; // position where n appears else cout << n << "" ""; } cout << ""\n""; } } // Driver code int main() { int n = 15; cout << ""Maximum Determinant = "" << maxDet(n); cout << ""\nResultant Matrix :\n""; resMatrix(n); return 0; }",constant,constant "// C++ program to find sum of // diagonals of spiral matrix #include using namespace std; // function returns sum of diagonals int spiralDiaSum(int n) { if (n == 1) return 1; // as order should be only odd // we should pass only odd-integers return (4*n*n - 6*n + 6 + spiralDiaSum(n-2)); } // Driver program int main() { int n = 7; cout << spiralDiaSum(n); return 0; }",linear,linear "// C++ program to find all permutations of a given row #include #define MAX 100 using namespace std; // Function to find all permuted rows of a given row r void permutatedRows(int mat[][MAX], int m, int n, int r) { // Creating an empty set unordered_set s; // Count frequencies of elements in given row r for (int j=0; j using namespace std; #define R 3 #define C 5 // Find the number of covered side for mat[i][j]. int numofneighbour(int mat[][C], int i, int j) { int count = 0; // UP if (i > 0 && mat[i - 1][j]) count++; // LEFT if (j > 0 && mat[i][j - 1]) count++; // DOWN if (i < R-1 && mat[i + 1][j]) count++; // RIGHT if (j < C-1 && mat[i][j + 1]) count++; return count; } // Returns sum of perimeter of shapes formed with 1s int findperimeter(int mat[R][C]) { int perimeter = 0; // Traversing the matrix and finding ones to // calculate their contribution. for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (mat[i][j]) perimeter += (4 - numofneighbour(mat, i ,j)); return perimeter; } // Driven Program int main() { int mat[R][C] = { 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, }; cout << findperimeter(mat) << endl; return 0; }",constant,quadratic "// C++ program to print cells with same rectangular // sum diagonally #include using namespace std; #define R 4 #define C 4 // Method prints cell index at which rectangular sum is // same at prime diagonal and other diagonal void printCellWithSameRectangularArea(int mat[R][C], int m, int n) { /* sum[i][j] denotes sum of sub-matrix, mat[0][0] to mat[i][j] sumr[i][j] denotes sum of sub-matrix, mat[i][j] to mat[m - 1][n - 1] */ int sum[m][n], sumr[m][n]; // Initialize both sum matrices by mat int totalSum = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { sumr[i][j] = sum[i][j] = mat[i][j]; totalSum += mat[i][j]; } } // updating first and last row separately for (int i = 1; i < m; i++) { sum[i][0] += sum[i-1][0]; sumr[m-i-1][n-1] += sumr[m-i][n-1]; } // updating first and last column separately for (int j = 1; j < n; j++) { sum[0][j] += sum[0][j-1]; sumr[m-1][n-j-1] += sumr[m-1][n-j]; } // updating sum and sumr indices by nearby indices for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { sum[i][j] += sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1]; sumr[m-i-1][n-j-1] += sumr[m-i][n-j-1] + sumr[m-i-1][n-j] - sumr[m-i][n-j]; } } // Uncomment below code to print sum and reverse sum // matrix /* for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << sum[i][j] << "" ""; } cout << endl; } cout << endl; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << sumr[i][j] << "" ""; } cout << endl; } cout << endl; */ /* print all those indices at which sum of prime diagonal rectangles is half of the total sum of matrix */ for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int mainDiagRectangleSum = sum[i][j] + sumr[i][j] - mat[i][j]; if (totalSum == 2 * mainDiagRectangleSum) cout << ""("" << i << "", "" << j << "")"" << endl; } } } // Driver code to test above methods int main() { int mat[R][C] = { 1, 2, 3, 5, 4, 1, 0, 2, 0, 1, 2, 0, 7, 1, 1, 0 }; printCellWithSameRectangularArea(mat, R, C); return 0; }",quadratic,quadratic "// C++ program to print matrix in diagonal order #include using namespace std; const int MAX = 100; void printMatrixDiagonal(int mat[MAX][MAX], int n) { // Initialize indexes of element to be printed next int i = 0, j = 0; // Direction is initially from down to up bool isUp = true; // Traverse the matrix till all elements get traversed for (int k = 0; k < n * n;) { // If isUp = true then traverse from downward // to upward if (isUp) { for (; i >= 0 && j < n; j++, i--) { cout << mat[i][j] << "" ""; k++; } // Set i and j according to direction if (i < 0 && j <= n - 1) i = 0; if (j == n) i = i + 2, j--; } // If isUp = 0 then traverse up to down else { for (; j >= 0 && i < n; i++, j--) { cout << mat[i][j] << "" ""; k++; } // Set i and j according to direction if (j < 0 && i <= n - 1) j = 0; if (i == n) j = j + 2, i--; } // Revert the isUp to change the direction isUp = !isUp; } } int main() { int mat[MAX][MAX] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3; printMatrixDiagonal(mat, n); return 0; }",constant,quadratic "// C++ program to print matrix in diagonal order #include using namespace std; int main() { // Initialize matrix int mat[][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // n - size // mode - switch to derive up/down traversal // it - iterator count - increases until it // reaches n and then decreases int n = 4, mode = 0, it = 0, lower = 0; // 2n will be the number of iterations for (int t = 0; t < (2 * n - 1); t++) { int t1 = t; if (t1 >= n) { mode++; t1 = n - 1; it--; lower++; } else { lower = 0; it++; } for (int i = t1; i >= lower; i--) { if ((t1 + mode) % 2 == 0) { cout << (mat[i][t1 + lower - i]) << endl; } else { cout << (mat[t1 + lower - i][i]) << endl; } } } return 0; } // This code is contributed by princiraj1992",constant,quadratic "// C++ program to find maximum difference of sum of // elements of two rows #include #define MAX 100 using namespace std; // Function to find maximum difference of sum of // elements of two rows such that second row appears // before first row. int maxRowDiff(int mat[][MAX], int m, int n) { // auxiliary array to store sum of all elements // of each row int rowSum[m]; // calculate sum of each row and store it in // rowSum array for (int i=0; i max_diff) max_diff = rowSum[i] - min_element; // if new element is less than previous minimum // element then update it so that // we may get maximum difference in remaining array if (rowSum[i] < min_element) min_element = rowSum[i]; } return max_diff; } // Driver program to run the case int main() { int m = 5, n = 4; int mat[][MAX] = {{-1, 2, 3, 4}, {5, 3, -2, 1}, {6, 7, 2, -3}, {2, 9, 1, 4}, {2, 1, -2, 0}}; cout << maxRowDiff(mat, m, n); return 0; }",linear,quadratic "// C++ program to find a pair with given sum such that // every element of pair is in different rows. #include using namespace std; const int MAX = 100; // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pair void pairSum(int mat[][MAX], int n, int sum) { // First sort all the rows in ascending order for (int i=0; i=0) { if ((mat[i][left] + mat[j][right]) == sum) { cout << ""("" << mat[i][left] << "", ""<< mat[j][right] << ""), ""; left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } } } // Driver program to run the case int main() { int n = 4, sum = 11; int mat[][MAX] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); return 0; }",constant,cubic "// C++ program to get total coverage of all zeros in // a binary matrix #include using namespace std; #define R 4 #define C 4 // Returns total coverage of all zeros in mat[][] int getTotalCoverageOfMatrix(int mat[R][C]) { int res = 0; // looping for all rows of matrix for (int i = 0; i < R; i++) { bool isOne = false; // 1 is not seen yet // looping in columns from left to right // direction to get left ones for (int j = 0; j < C; j++) { // If one is found from left if (mat[i][j] == 1) isOne = true; // If 0 is found and we have found // a 1 before. else if (isOne) res++; } // Repeat the above process for right to // left direction. isOne = false; for (int j = C-1; j >= 0; j--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } // Traversing across columns for up and down // directions. for (int j = 0; j < C; j++) { bool isOne = false; // 1 is not seen yet for (int i = 0; i < R; i++) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } isOne = false; for (int i = R-1; i >= 0; i--) { if (mat[i][j] == 1) isOne = true; else if (isOne) res++; } } return res; } // Driver code to test above methods int main() { int mat[R][C] = {{0, 0, 0, 0}, {1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 0, 0} }; cout << getTotalCoverageOfMatrix(mat); return 0; }",constant,quadratic "// C++ program to find number of sorted rows #include #define MAX 100 using namespace std; // Function to count all sorted rows in a matrix int sortedCount(int mat[][MAX], int r, int c) { int result = 0; // Initialize result // Start from left side of matrix to // count increasing order rows for (int i=0; i0; j--) if (mat[i][j-1] <= mat[i][j]) break; // Note c > 1 condition is required to make // sure that a single column row is not counted // twice (Note that a single column row is sorted // both in increasing and decreasing order) if (c > 1 && j == 0) result++; } return result; } // Driver program to run the case int main() { int m = 4, n = 5; int mat[][MAX] = {{1, 2, 3, 4, 5}, {4, 3, 1, 2, 6}, {8, 7, 6, 5, 4}, {5, 7, 8, 9, 10}}; cout << sortedCount(mat, m, n); return 0; }",constant,quadratic "// C++ program to Find maximum XOR value in // matrix either row / column wise #include using namespace std; // maximum number of row and column const int MAX = 1000; // function return the maximum xor value that is // either row or column wise int maxXOR(int mat[][MAX], int N) { // for row xor and column xor int r_xor, c_xor; int max_xor = 0; // traverse matrix for (int i = 0 ; i < N ; i++) { r_xor = 0, c_xor = 0; for (int j = 0 ; j < N ; j++) { // xor row element r_xor = r_xor^mat[i][j]; // for each column : j is act as row & i // act as column xor column element c_xor = c_xor^mat[j][i]; } // update maximum between r_xor , c_xor if (max_xor < max(r_xor, c_xor)) max_xor = max(r_xor, c_xor); } // return maximum xor value return max_xor; } // driver Code int main() { int N = 3; int mat[][MAX] = {{1 , 5, 4}, {3 , 7, 2 }, {5 , 9, 10} }; cout << ""maximum XOR value : "" << maxXOR(mat, N); return 0; }",constant,quadratic "// C++ program to find how many mirror can transfer // light from bottom to right #include using namespace std; // method returns number of mirror which can transfer // light from bottom to right int maximumMirrorInMatrix(string mat[], int N) { // To store first obstacles horizontally (from right) // and vertically (from bottom) int horizontal[N], vertical[N]; // initialize both array as -1, signifying no obstacle memset(horizontal, -1, sizeof(horizontal)); memset(vertical, -1, sizeof(vertical)); // looping matrix to mark column for obstacles for (int i=0; i=0; j--) { if (mat[i][j] == 'B') continue; // mark rightmost column with obstacle horizontal[i] = j; break; } } // looping matrix to mark rows for obstacles for (int j=0; j=0; i--) { if (mat[i][j] == 'B') continue; // mark leftmost row with obstacle vertical[j] = i; break; } } int res = 0; // Initialize result // if there is not obstacle on right or below, // then mirror can be placed to transfer light for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { /* if i > vertical[j] then light can from bottom if j > horizontal[i] then light can go to right */ if (i > vertical[j] && j > horizontal[i]) { /* uncomment this code to print actual mirror position also cout << i << "" "" << j << endl; */ res++; } } } return res; } // Driver code to test above method int main() { int N = 5; // B - Blank O - Obstacle string mat[N] = {""BBOBB"", ""BBBBO"", ""BBBBB"", ""BOOBO"", ""BBBOB"" }; cout << maximumMirrorInMatrix(mat, N) << endl; return 0; }",linear,quadratic "// C++ program to tell the Current direction in // R x C grid #include using namespace std; typedef long long int ll; // Function which tells the Current direction void direction(ll R, ll C) { if (R != C && R % 2 == 0 && C % 2 != 0 && R < C) { cout << ""Left"" << endl; return; } if (R != C && R % 2 != 0 && C % 2 == 0 && R > C) { cout << ""Up"" << endl; return; } if (R == C && R % 2 != 0 && C % 2 != 0) { cout << ""Right"" << endl; return; } if (R == C && R % 2 == 0 && C % 2 == 0) { cout << ""Left"" << endl; return; } if (R != C && R % 2 != 0 && C % 2 != 0 && R < C) { cout << ""Right"" << endl; return; } if (R != C && R % 2 != 0 && C % 2 != 0 && R > C) { cout << ""Down"" << endl; return; } if (R != C && R % 2 == 0 && C % 2 == 0 && R < C) { cout << ""Left"" << endl; return; } if (R != C && R % 2 == 0 && C % 2 == 0 && R > C) { cout << ""Up"" << endl; return; } if (R != C && R % 2 == 0 && C % 2 != 0 && R > C) { cout << ""Down"" << endl; return; } if (R != C && R % 2 != 0 && C % 2 == 0 && R < C) { cout << ""Right"" << endl; return; } } // Driver program to test the Cases int main() { ll R = 3, C = 1; direction(R, C); return 0; }",constant,constant "// C++ program to check whether given matrix // is a Toeplitz matrix or not #include using namespace std; #define N 5 #define M 4 // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not bool checkDiagonal(int mat[N][M], int i, int j) { int res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false; } // we only reach here when all elements // in given diagonal are same return true; } // Function to check whether given matrix is a // Toeplitz matrix or not bool isToeplitz(int mat[N][M]) { // do for each element in first row for (int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false; } // do for each element in first column for (int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false; } // we only reach here when each descending // diagonal from left to right is same return true; } // Driver code int main() { int mat[N][M] = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) cout << ""Matrix is a Toeplitz ""; else cout << ""Matrix is not a Toeplitz ""; return 0; }",constant,quadratic "// C++ program to check whether given // matrix is a Toeplitz matrix or not #include using namespace std; bool isToeplitz(vector> matrix) { // row = number of rows // col = number of columns int row = matrix.size(); int col = matrix[0].size(); // HashMap to store key,value pairs map Map; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { int key = i - j; // If key value exists in the hashmap, if (Map[key]) { // We check whether the current // value stored in this key // matches to element at current // index or not. If not, return // false if (Map[key] != matrix[i][j]) return false; } // Else we put key,value pair in hashmap else { Map[i - j] = matrix[i][j]; } } } return true; } // Driver code int main() { vector> matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call string result = (isToeplitz(matrix)) ? ""Yes"" : ""No""; cout << result; return 0; } // This code is contributed by divyesh072019",linear,quadratic "// C++ Program to return previous element in an expanding // matrix. #include using namespace std; // Returns left of str in an expanding matrix of // a, b, c, and d. string findLeft(string str) { int n = str.length(); // Start from rightmost position while (n--) { // If the current character is ‘b’ or ‘d’, // change to ‘a’ or ‘c’ respectively and // break the loop if (str[n] == 'd') { str[n] = 'c'; break; } if (str[n] == 'b') { str[n] = 'a'; break; } // If the current character is ‘a’ or ‘c’, // change it to ‘b’ or ‘d’ respectively if (str[n] == 'a') str[n] = 'b'; else if (str[n] == 'c') str[n] = 'd'; } return str; } // driver program to test above method int main() { string str = ""aacbddc""; cout << ""Left of "" << str << "" is "" << findLeft(str); return 0; }",constant,linear "// C++ program to print a n x n spiral matrix // in clockwise direction using O(1) space #include using namespace std; // Prints spiral matrix of size n x n containing // numbers from 1 to n x n void printSpiral(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // x stores the layer in which (i, j)th // element lies int x; // Finds minimum of four inputs x = min(min(i, j), min(n-1-i, n-1-j)); // For upper right half if (i <= j) printf(""%d\t "", (n-2*x)*(n-2*x) - (i-x) - (j-x)); // for lower left half else printf(""%d\t "", (n-2*x-2)*(n-2*x-2) + (i-x) + (j-x)); } printf(""\n""); } } // Driver code int main() { int n = 5; // print a n x n spiral matrix in O(1) space printSpiral(n); return 0; }",constant,quadratic "#include #include #include #include using namespace std; // Check if it is possible to go to (x, y) from the current position. The // function returns false if the cell has value 0 or already visited bool isSafe(vector> &mat, vector> &visited, int x, int y) { return (x >= 0 && x < mat.size() && y >= 0 && y < mat[0].size()) && mat[x][y] == 1 && !visited[x][y]; } void findShortestPath(vector> &mat, vector> &visited, int i, int j, int x, int y, int &min_dist, int dist){ if (i == x && j == y){ min_dist = min(dist, min_dist); return; } // set (i, j) cell as visited visited[i][j] = true; // go to the bottom cell if (isSafe(mat, visited, i + 1, j)) { findShortestPath(mat, visited, i + 1, j, x, y, min_dist, dist + 1); } // go to the right cell if (isSafe(mat, visited, i, j + 1)) { findShortestPath(mat, visited, i, j + 1, x, y, min_dist, dist + 1); } // go to the top cell if (isSafe(mat, visited, i - 1, j)) { findShortestPath(mat, visited, i - 1, j, x, y, min_dist, dist + 1); } // go to the left cell if (isSafe(mat, visited, i, j - 1)) { findShortestPath(mat, visited, i, j - 1, x, y, min_dist, dist + 1); } // backtrack: remove (i, j) from the visited matrix visited[i][j] = false; } // Wrapper over findShortestPath() function int findShortestPathLength(vector> &mat, pair &src, pair &dest){ if (mat.size() == 0 || mat[src.first][src.second] == 0 || mat[dest.first][dest.second] == 0) return -1; int row = mat.size(); int col = mat[0].size(); // construct an `M × N` matrix to keep track of visited cells vector> visited; visited.resize(row, vector(col)); int dist = INT_MAX; findShortestPath(mat, visited, src.first, src.second, dest.first, dest.second, dist, 0); if (dist != INT_MAX) return dist; return -1; } int main() { vector> mat = {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, {1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, {1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, {0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, {1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, {1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, {1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, {1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, {1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }}; pair src = make_pair(0, 0); pair dest = make_pair(3, 4); int dist = findShortestPathLength(mat, src, dest); if (dist != -1) cout << ""Shortest Path is "" << dist; else cout << ""Shortest Path doesn't exist""; return 0; }",quadratic,np "// C++ program to find the shortest path between // a given source cell to a destination cell. #include using namespace std; #define ROW 9 #define COL 10 //To store matrix cell coordinates struct Point { int x; int y; }; // A Data Structure for queue used in BFS struct queueNode { Point pt; // The coordinates of a cell int dist; // cell's distance of from the source }; // check whether given cell (row, col) is a valid // cell or not. bool isValid(int row, int col) { // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL); } // These arrays are used to get row and column // numbers of 4 neighbours of a given cell int rowNum[] = {-1, 0, 0, 1}; int colNum[] = {0, -1, 1, 0}; // function to find the shortest path between // a given source cell to a destination cell. int BFS(int mat[][COL], Point src, Point dest) { // check source and destination cell // of the matrix have value 1 if (!mat[src.x][src.y] || !mat[dest.x][dest.y]) return -1; bool visited[ROW][COL]; memset(visited, false, sizeof visited); // Mark the source cell as visited visited[src.x][src.y] = true; // Create a queue for BFS queue q; // Distance of source cell is 0 queueNode s = {src, 0}; q.push(s); // Enqueue source cell // Do a BFS starting from source cell while (!q.empty()) { queueNode curr = q.front(); Point pt = curr.pt; // If we have reached the destination cell, // we are done if (pt.x == dest.x && pt.y == dest.y) return curr.dist; // Otherwise dequeue the front // cell in the queue // and enqueue its adjacent cells q.pop(); for (int i = 0; i < 4; i++) { int row = pt.x + rowNum[i]; int col = pt.y + colNum[i]; // if adjacent cell is valid, has path and // not visited yet, enqueue it. if (isValid(row, col) && mat[row][col] && !visited[row][col]) { // mark cell as visited and enqueue it visited[row][col] = true; queueNode Adjcell = { {row, col}, curr.dist + 1 }; q.push(Adjcell); } } } // Return -1 if destination cannot be reached return -1; } // Driver program to test above function int main() { int mat[ROW][COL] = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 }, { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 } }; Point source = {0, 0}; Point dest = {3, 4}; int dist = BFS(mat, source, dest); if (dist != -1) cout << ""Shortest Path is "" << dist ; else cout << ""Shortest Path doesn't exist""; return 0; }",quadratic,quadratic "// C++ program for finding orientation of the pattern // using KMP pattern searching algorithm #include using namespace std; #define N 5 // Used in KMP Search for preprocessing the pattern void computeLPSArray(char *pat, int M, int *lps) { // length of the previous longest prefix suffix int len = 0; int i = 1; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 while (i < M) { if (pat[i] == pat[len]) { len++; lps[i++] = len; } else // (pat[i] != pat[len]) { if (len != 0) { // This is tricky. Consider the example // AAACAAAA and i = 7. len = lps[len - 1]; // Also, note that we do not increment i here } else // if (len == 0) { lps[i++] = 0; } } } } int KMPSearch(char *pat, char *txt) { int M = strlen(pat); // create lps[] that will hold the longest // prefix suffix values for pattern int *lps = (int *)malloc(sizeof(int)*M); int j = 0; // index for pat[] // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); int i = 0; // index for txt[] while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { // return 1 is pattern is found return 1; } // mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } free(lps); // to avoid memory leak // return 0 is pattern is not found return 0; } // Function to find orientation of pattern in the matrix // It uses KMP pattern searching algorithm void findOrientation(char mat[][N], char *pat) { // allocate memory for string containing cols char *col = (char*) malloc(N); for (int i = 0; i < N; i++) { // search in row i if (KMPSearch(pat, mat[i])) { cout << ""Horizontal"" << endl; return; } // Construct an array to store i'th column for (int j = 0; j < N; j++) col[j] = *(mat[j] + i); // Search in column i if (KMPSearch(pat, col)) cout << ""Vertical"" << endl; } // to avoid memory leak free(col); } // Driver Code int main() { char mat[N][N] = {{'a', 'b', 'c', 'd', 'e'}, {'f', 'g', 'h', 'i', 'j'}, {'k', 'l', 'm', 'n', 'o'}, {'p', 'q', 'r', 's', 't'}, {'u', 'v', 'w', 'x', 'y'}}; char pat[] = ""pqrs""; findOrientation(mat, pat); return 0; } // This code is contributed by kumar65",linear,quadratic "// A Naive method to find maximum value of mat[d][e] // - ma[a][b] such that d > a and e > b #include using namespace std; #define N 5 // The function returns maximum value A(d,e) - A(a,b) // over all choices of indexes such that both d > a // and e > b. int findMaxValue(int mat[][N]) { // stores maximum value int maxValue = INT_MIN; // Consider all possible pairs mat[a][b] and // mat[d][e] for (int a = 0; a < N - 1; a++) for (int b = 0; b < N - 1; b++) for (int d = a + 1; d < N; d++) for (int e = b + 1; e < N; e++) if (maxValue < (mat[d][e] - mat[a][b])) maxValue = mat[d][e] - mat[a][b]; return maxValue; } // Driver program to test above function int main() { int mat[N][N] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; cout << ""Maximum Value is "" << findMaxValue(mat); return 0; }",constant,np "// An efficient method to find maximum value of mat[d] // - ma[a][b] such that c > a and d > b #include using namespace std; #define N 5 // The function returns maximum value A(c,d) - A(a,b) // over all choices of indexes such that both c > a // and d > b. int findMaxValue(int mat[][N]) { //stores maximum value int maxValue = INT_MIN; // maxArr[i][j] stores max of elements in matrix // from (i, j) to (N-1, N-1) int maxArr[N][N]; // last element of maxArr will be same's as of // the input matrix maxArr[N-1][N-1] = mat[N-1][N-1]; // preprocess last row int maxv = mat[N-1][N-1]; // Initialize max for (int j = N - 2; j >= 0; j--) { if (mat[N-1][j] > maxv) maxv = mat[N - 1][j]; maxArr[N-1][j] = maxv; } // preprocess last column maxv = mat[N - 1][N - 1]; // Initialize max for (int i = N - 2; i >= 0; i--) { if (mat[i][N - 1] > maxv) maxv = mat[i][N - 1]; maxArr[i][N - 1] = maxv; } // preprocess rest of the matrix from bottom for (int i = N-2; i >= 0; i--) { for (int j = N-2; j >= 0; j--) { // Update maxValue if (maxArr[i+1][j+1] - mat[i][j] > maxValue) maxValue = maxArr[i + 1][j + 1] - mat[i][j]; // set maxArr (i, j) maxArr[i][j] = max(mat[i][j], max(maxArr[i][j + 1], maxArr[i + 1][j]) ); } } return maxValue; } // Driver program to test above function int main() { int mat[N][N] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; cout << ""Maximum Value is "" << findMaxValue(mat); return 0; }",quadratic,quadratic "// An efficient C++ program to find maximum sum sub-square // matrix #include using namespace std; // Size of given matrix #define N 5 // A O(n^2) function to the maximum sum sub-squares of size // k x k in a given square matrix of size n x n void printMaxSumSub(int mat[][N], int k) { // k must be smaller than or equal to n if (k > N) return; // 1: PREPROCESSING // To store sums of all strips of size k x 1 int stripSum[N][N]; // Go column by column for (int j = 0; j < N; j++) { // Calculate sum of first k x 1 rectangle in this // column int sum = 0; for (int i = 0; i < k; i++) sum += mat[i][j]; stripSum[0][j] = sum; // Calculate sum of remaining rectangles for (int i = 1; i < N - k + 1; i++) { sum += (mat[i + k - 1][j] - mat[i - 1][j]); stripSum[i][j] = sum; } } // max_sum stores maximum sum and its position in matrix int max_sum = INT_MIN, *pos = NULL; // 2: CALCULATE SUM of Sub-Squares using stripSum[][] for (int i = 0; i < N - k + 1; i++) { // Calculate and print sum of first subsquare in // this row int sum = 0; for (int j = 0; j < k; j++) sum += stripSum[i][j]; // Update max_sum and position of result if (sum > max_sum) { max_sum = sum; pos = &(mat[i][0]); } // Calculate sum of remaining squares in current row // by removing the leftmost strip of previous // sub-square and adding a new strip for (int j = 1; j < N - k + 1; j++) { sum += (stripSum[i][j + k - 1] - stripSum[i][j - 1]); // Update max_sum and position of result if (sum > max_sum) { max_sum = sum; pos = &(mat[i][j]); } } } // Print the result matrix for (int i = 0; i < k; i++) { for (int j = 0; j < k; j++) cout << *(pos + i * N + j) << "" ""; cout << endl; } } // Driver program to test above function int main() { int mat[N][N] = { { 1, 1, 1, 1, 1 }, { 2, 2, 2, 2, 2 }, { 3, 8, 6, 7, 3 }, { 4, 4, 4, 4, 4 }, { 5, 5, 5, 5, 5 }, }; int k = 3; cout << ""Maximum sum 3 x 3 matrix is\n""; printMaxSumSub(mat, k); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",quadratic,quadratic "// A Program to prints common element in all // rows of matrix #include using namespace std; // Specify number of rows and columns #define M 4 #define N 5 // prints common element in all rows of matrix void printCommonElements(int mat[M][N]) { unordered_map mp; // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) mp[mat[0][j]] = 1; // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp[mat[i][j]] == i) { // we increment count of the element // in map by 1 mp[mat[i][j]] = i + 1; // If this is last row if (i==M-1 && mp[mat[i][j]]==M) cout << mat[i][j] << "" ""; } } } } // driver program to test above function int main() { int mat[M][N] = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; printCommonElements(mat); return 0; }",linear,quadratic "// C++ Code For A Boolean Matrix Question #include using namespace std; #define R 3 #define C 4 void modifyMatrix(bool mat[R][C]) { bool row[R]; bool col[C]; int i, j; /* Initialize all values of row[] as 0 */ for (i = 0; i < R; i++) row[i] = 0; /* Initialize all values of col[] as 0 */ for (i = 0; i < C; i++) col[i] = 0; // Store the rows and columns to be marked as // 1 in row[] and col[] arrays respectively for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (mat[i][j] == 1) { row[i] = 1; col[j] = 1; } } } // Modify the input matrix mat[] using the // above constructed row[] and col[] arrays for (i = 0; i < R; i++) for (j = 0; j < C; j++) if (row[i] == 1 || col[j] == 1) mat[i][j] = 1; } /* A utility function to print a 2D matrix */ void printMatrix(bool mat[R][C]) { int i, j; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) cout << mat[i][j]; cout << endl; } } // Driver Code int main() { bool mat[R][C] = { { 1, 0, 0, 1 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } }; cout << ""Input Matrix \n""; printMatrix(mat); modifyMatrix(mat); printf(""Matrix after modification \n""); printMatrix(mat); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,quadratic "#include using namespace std; #define R 3 #define C 4 void modifyMatrix(int mat[R][C]) { // variables to check if there are any 1 // in first row and column bool row_flag = false; bool col_flag = false; // updating the first row and col if 1 // is encountered for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (i == 0 && mat[i][j] == 1) row_flag = true; if (j == 0 && mat[i][j] == 1) col_flag = true; if (mat[i][j] == 1) { mat[0][j] = 1; mat[i][0] = 1; } } } // Modify the input matrix mat[] using the // first row and first column of Matrix mat for (int i = 1; i < R; i++) for (int j = 1; j < C; j++) if (mat[0][j] == 1 || mat[i][0] == 1) mat[i][j] = 1; // modify first row if there was any 1 if (row_flag == true) for (int i = 0; i < C; i++) mat[0][i] = 1; // modify first col if there was any 1 if (col_flag == true) for (int i = 0; i < R; i++) mat[i][0] = 1; } /* A utility function to print a 2D matrix */ void printMatrix(int mat[R][C]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << mat[i][j] << "" ""; cout << ""\n""; } } // Driver function to test the above function int main() { int mat[R][C] = { { 1, 0, 0, 1 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 } }; cout << ""Input Matrix :\n""; printMatrix(mat); modifyMatrix(mat); cout << ""Matrix After Modification :\n""; printMatrix(mat); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,quadratic "// C++ program to find i such that all entries in i'th row are 0 // and all entries in i't column are 1 #include using namespace std; #define n 5 int find(bool arr[n][n]) { // Start from top-most rightmost corner // (We could start from other corners also) int i=0, j=n-1; // Initialize result int res = -1; // Find the index (This loop runs at most 2n times, we either // increment row number or decrement column number) while (i=0) { // If current element is 0, then this row may be a solution if (arr[i][j] == 0) { // Check for all elements in this row while (j >= 0 && (arr[i][j] == 0 || i == j)) j--; // If all values are 0, then store this row as result if (j == -1) { res = i; break; } // We reach here if we found a 1 in current row, so this // row cannot be a solution, increment row number else i++; } else // If current element is 1 { // Check for all elements in this column while (i using namespace std; // This matrix is used to find indexes to check all // possible winning triplets in board[0..8] int win[8][3] = {{0, 1, 2}, // Check first row. {3, 4, 5}, // Check second Row {6, 7, 8}, // Check third Row {0, 3, 6}, // Check first column {1, 4, 7}, // Check second Column {2, 5, 8}, // Check third Column {0, 4, 8}, // Check first Diagonal {2, 4, 6}}; // Check second Diagonal // Returns true if character 'c' wins. c can be either // 'X' or 'O' bool isCWin(char *board, char c) { // Check all possible winning combinations for (int i=0; i<8; i++) if (board[win[i][0]] == c && board[win[i][1]] == c && board[win[i][2]] == c ) return true; return false; } // Returns true if given board is valid, else returns false bool isValid(char board[9]) { // Count number of 'X' and 'O' in the given board int xCount=0, oCount=0; for (int i=0; i<9; i++) { if (board[i]=='X') xCount++; if (board[i]=='O') oCount++; } // Board can be valid only if either xCount and oCount // is same or count is one more than oCount if (xCount==oCount || xCount==oCount+1) { // Check if 'O' is winner if (isCWin(board, 'O')) { // Check if 'X' is also winner, then // return false if (isCWin(board, 'X')) return false; // Else return true xCount and yCount are same return (xCount == oCount); } // If 'X' wins, then count of X must be greater if (isCWin(board, 'X') && xCount != oCount + 1) return false; // If 'O' is not winner, then return true return true; } return false; } // Driver program int main() { char board[] = {'X', 'X', 'O', 'O', 'O', 'X', 'X', 'O', 'X'}; (isValid(board))? cout << ""Given board is valid"": cout << ""Given board is not valid""; return 0; }",constant,constant "// C++ program to compute submatrix query sum in O(1) // time #include using namespace std; #define M 4 #define N 5 // Function to preprocess input mat[M][N]. This function // mainly fills aux[M][N] such that aux[i][j] stores sum // of elements from (0,0) to (i,j) int preProcess(int mat[M][N], int aux[M][N]) { // Copy first row of mat[][] to aux[][] for (int i=0; i 0) res = res - aux[tli-1][rbj]; // Remove elements between (0, 0) and (rbi, tlj-1) if (tlj > 0) res = res - aux[rbi][tlj-1]; // Add aux[tli-1][tlj-1] as elements between (0, 0) // and (tli-1, tlj-1) are subtracted twice if (tli > 0 && tlj > 0) res = res + aux[tli-1][tlj-1]; return res; } // Driver program int main() { int mat[M][N] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4} }; int aux[M][N]; preProcess(mat, aux); int tli = 2, tlj = 2, rbi = 3, rbj = 4; cout << ""\nQuery1: "" << sumQuery(aux, tli, tlj, rbi, rbj); tli = 0, tlj = 0, rbi = 1, rbj = 1; cout << ""\nQuery2: "" << sumQuery(aux, tli, tlj, rbi, rbj); tli = 1, tlj = 2, rbi = 3, rbj = 3; cout << ""\nQuery3: "" << sumQuery(aux, tli, tlj, rbi, rbj); return 0; }",quadratic,quadratic "// C++ program to find rank of a matrix #include using namespace std; #define R 3 #define C 3 /* function for exchanging two rows of a matrix */ void swap(int mat[R][C], int row1, int row2, int col) { for (int i = 0; i < col; i++) { int temp = mat[row1][i]; mat[row1][i] = mat[row2][i]; mat[row2][i] = temp; } } // Function to display a matrix void display(int mat[R][C], int row, int col); /* function for finding rank of matrix */ int rankOfMatrix(int mat[R][C]) { int rank = C; for (int row = 0; row < rank; row++) { // Before we visit current row 'row', we make // sure that mat[row][0],....mat[row][row-1] // are 0. // Diagonal element is not zero if (mat[row][row]) { for (int col = 0; col < R; col++) { if (col != row) { // This makes all entries of current // column as 0 except entry 'mat[row][row]' double mult = (double)mat[col][row] / mat[row][row]; for (int i = 0; i < rank; i++) mat[col][i] -= mult * mat[row][i]; } } } // Diagonal element is already zero. Two cases // arise: // 1) If there is a row below it with non-zero // entry, then swap this row with that row // and process that row // 2) If all elements in current column below // mat[r][row] are 0, then remove this column // by swapping it with last column and // reducing number of columns by 1. else { bool reduce = true; /* Find the non-zero element in current column */ for (int i = row + 1; i < R; i++) { // Swap the row with non-zero element // with this row. if (mat[i][row]) { swap(mat, row, i, rank); reduce = false; break ; } } // If we did not find any row with non-zero // element in current column, then all // values in this column are 0. if (reduce) { // Reduce number of columns rank--; // Copy the last column here for (int i = 0; i < R; i ++) mat[i][row] = mat[i][rank]; } // Process this row again row--; } // Uncomment these lines to see intermediate results // display(mat, R, C); // printf(""\n""); } return rank; } /* function for displaying the matrix */ void display(int mat[R][C], int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) printf("" %d"", mat[i][j]); printf(""\n""); } } // Driver program to test above functions int main() { int mat[][3] = {{10, 20, 10}, {-20, -30, 10}, {30, 50, 0}}; printf(""Rank of the matrix is : %d"", rankOfMatrix(mat)); return 0; }",constant,quadratic "// C++ program to find largest // rectangle with all 1s // in a binary matrix #include using namespace std; // Rows and columns in input matrix #define R 4 #define C 4 // Finds the maximum area under // the histogram represented // by histogram. See below article for details. int maxHist(int row[]) { // Create an empty stack. // The stack holds indexes of // hist[] array/ The bars stored // in stack are always // in increasing order of their heights. stack result; int top_val; // Top of stack int max_area = 0; // Initialize max area in current // row (or histogram) int area = 0; // Initialize area with current top // Run through all bars of given histogram (or row) int i = 0; while (i < C) { // If this bar is higher than the bar on top stack, // push it to stack if (result.empty() || row[result.top()] <= row[i]) result.push(i++); else { // If this bar is lower than top of stack, then // calculate area of rectangle with stack top as // the smallest (or minimum height) bar. 'i' is // 'right index' for the top and element before // top in stack is 'left index' top_val = row[result.top()]; result.pop(); area = top_val * i; if (!result.empty()) area = top_val * (i - result.top() - 1); max_area = max(area, max_area); } } // Now pop the remaining bars from stack and calculate // area with every popped bar as the smallest bar while (!result.empty()) { top_val = row[result.top()]; result.pop(); area = top_val * i; if (!result.empty()) area = top_val * (i - result.top() - 1); max_area = max(area, max_area); } return max_area; } // Returns area of the largest rectangle with all 1s in // A[][] int maxRectangle(int A[][C]) { // Calculate area for first row and initialize it as // result int result = maxHist(A[0]); // iterate over row to find maximum rectangular area // considering each row as histogram for (int i = 1; i < R; i++) { for (int j = 0; j < C; j++) // if A[i][j] is 1 then add A[i -1][j] if (A[i][j]) A[i][j] += A[i - 1][j]; // Update result if area with current row (as last // row) of rectangle) is more result = max(result, maxHist(A[i])); } return result; } // Driver code int main() { int A[][C] = { { 0, 1, 1, 0 }, { 1, 1, 1, 1 }, { 1, 1, 1, 1 }, { 1, 1, 0, 0 }, }; cout << ""Area of maximum rectangle is "" << maxRectangle(A); return 0; }",linear,quadratic "// C++ code for Maximum size square // sub-matrix with all 1s #include #define bool int #define R 6 #define C 5 using namespace std; void printMaxSubSquare(bool M[R][C]) { int i, j; int S[R][C]; int max_of_s, max_i, max_j; /* Set first column of S[][]*/ for (i = 0; i < R; i++) S[i][0] = M[i][0]; /* Set first row of S[][]*/ for (j = 0; j < C; j++) S[0][j] = M[0][j]; /* Construct other entries of S[][]*/ for (i = 1; i < R; i++) { for (j = 1; j < C; j++) { if (M[i][j] == 1) S[i][j] = min({ S[i][j - 1], S[i - 1][j], S[i - 1][j - 1] }) + 1; // better of using min in case of // arguments more than 2 else S[i][j] = 0; } } /* Find the maximum entry, and indexes of maximum entry in S[][] */ max_of_s = S[0][0]; max_i = 0; max_j = 0; for (i = 0; i < R; i++) { for (j = 0; j < C; j++) { if (max_of_s < S[i][j]) { max_of_s = S[i][j]; max_i = i; max_j = j; } } } cout << ""Maximum size sub-matrix is: \n""; for (i = max_i; i > max_i - max_of_s; i--) { for (j = max_j; j > max_j - max_of_s; j--) { cout << M[i][j] << "" ""; } cout << ""\n""; } } /* Driver code */ int main() { bool M[R][C] = { { 0, 1, 1, 0, 1 }, { 1, 1, 0, 1, 0 }, { 0, 1, 1, 1, 0 }, { 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0 } }; printMaxSubSquare(M); } // This code is contributed by rathbhupendra",quadratic,quadratic "// C++ code for Maximum size square // sub-matrix with all 1s // (space optimized solution) #include using namespace std; #define R 6 #define C 5 void printMaxSubSquare(bool M[R][C]) { int S[2][C], Max = 0; // set all elements of S to 0 first memset(S, 0, sizeof(S)); // Construct the entries for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) { // Compute the entrie at the current position int Entrie = M[i][j]; if (Entrie) if (j) Entrie = 1 + min(S[1][j - 1], min(S[0][j - 1], S[1][j])); // Save the last entrie and add the new one S[0][j] = S[1][j]; S[1][j] = Entrie; // Keep track of the max square length Max = max(Max, Entrie); } // Print the square cout << ""Maximum size sub-matrix is: \n""; for (int i = 0; i < Max; i++, cout << '\n') for (int j = 0; j < Max; j++) cout << ""1 ""; } // Driver code int main() { bool M[R][C] = { { 0, 1, 1, 0, 1 }, { 1, 1, 0, 1, 0 }, { 0, 1, 1, 1, 0 }, { 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0 } }; printMaxSubSquare(M); return 0; // This code is contributed // by Gatea David }",linear,quadratic "// An efficient C++ program to compute sum for given array of cell indexes #include #define R 3 #define C 3 using namespace std; // A structure to represent a cell index struct Cell { int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1 }; void printSums(int mat[][C], struct Cell arr[], int n) { int sum = 0; int row[R] = {}; int col[C] = {}; // Compute sum of all elements, sum of every row and sum every column for (int i=0; i using namespace std; // Size of given matrix is M X N #define M 6 #define N 3 // This function takes a matrix of 'X' and 'O' // and returns the number of rectangular islands // of 'X' where no two islands are row-wise or // column-wise adjacent, the islands may be diagonally // adjacent int countIslands(int mat[][N]) { int count = 0; // Initialize result // Traverse the input matrix for (int i=0; i using namespace std; // Specify number of rows and columns #define M 4 #define N 5 // Returns common element in all rows of mat[M][N]. If there is no // common element, then -1 is returned int findCommon(int mat[M][N]) { // An array to store indexes of current last column int column[M]; int min_row; // To store index of row whose current // last element is minimum // Initialize current last element of all rows int i; for (i = 0; i < M; i++) column[i] = N - 1; min_row = 0; // Initialize min_row as first row // Keep finding min_row in current last column, till either // all elements of last column become same or we hit first column. while (column[min_row] >= 0) { // Find minimum in current last column for (i = 0; i < M; i++) { if (mat[i][column[i]] < mat[min_row][column[min_row]]) min_row = i; } // eq_count is count of elements equal to minimum in current last // column. int eq_count = 0; // Traverse current last column elements again to update it for (i = 0; i < M; i++) { // Decrease last column index of a row whose value is more // than minimum. if (mat[i][column[i]] > mat[min_row][column[min_row]]) { if (column[i] == 0) return -1; column[i] -= 1; // Reduce last column index by 1 } else eq_count++; } // If equal count becomes M, return the value if (eq_count == M) return mat[min_row][column[min_row]]; } return -1; } // Driver Code int main() { int mat[M][N] = { { 1, 2, 3, 4, 5 }, { 2, 4, 5, 8, 10 }, { 3, 5, 7, 9, 11 }, { 1, 3, 5, 7, 9 }, }; int result = findCommon(mat); if (result == -1) cout << ""No common element""; else cout << ""Common element is "" << result; return 0; } // This code is contributed // by Akanksha Rai",linear,quadratic "// A C++ program to find the largest subsquare // surrounded by 'X' in a given matrix of 'O' and 'X' #include using namespace std; // Size of given matrix is N X N #define N 6 // A utility function to find minimum of two numbers int getMin(int x, int y) { return (x < y) ? x : y; } // Returns size of maximum size subsquare matrix // surrounded by 'X' int findSubSquare(int mat[][N]) { int max = 0; // Initialize result // Initialize the left-top value in hor[][] and ver[][] int hor[N][N], ver[N][N]; hor[0][0] = ver[0][0] = (mat[0][0] == 'X'); // Fill values in hor[][] and ver[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (mat[i][j] == 'O') ver[i][j] = hor[i][j] = 0; else { hor[i][j] = (j == 0) ? 1 : hor[i][j - 1] + 1; ver[i][j] = (i == 0) ? 1 : ver[i - 1][j] + 1; } } } // Start from the rightmost-bottommost corner element // and find the largest ssubsquare with the help of // hor[][] and ver[][] for (int i = N - 1; i >= 1; i--) { for (int j = N - 1; j >= 1; j--) { // Find smaller of values in hor[][] and ver[][] // A Square can only be made by taking smaller // value int small = getMin(hor[i][j], ver[i][j]); // At this point, we are sure that there is a // right vertical line and bottom horizontal // line of length at least 'small'. // We found a bigger square if following // conditions are met: 1)If side of square is // greater than max. 2)There is a left vertical // line of length >= 'small' 3)There is a top // horizontal line of length >= 'small' while (small > max) { if (ver[i][j - small + 1] >= small && hor[i - small + 1][j] >= small) { max = small; } small--; } } } return max; } // Driver code int main() { int mat[][N] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call cout << findSubSquare(mat); return 0; }",quadratic,quadratic "// A C++ program to find the largest subsquare // surrounded by 'X' in a given matrix of 'O' and 'X' #include using namespace std; // Size of given matrix is N X N #define N 6 int maximumSubSquare(int arr[][N]) { pair dp[51][51]; int maxside[51][51]; // Initialize maxside with 0 memset(maxside, 0, sizeof(maxside)); int x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (int i = 0; i < N; i++) { x = 0; for (int j = 0; j < N; j++) { if (arr[i][j] == 'X') x += 1; else x = 0; dp[i][j].first = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (int i = 0; i < N; i++) { y=0; for (int j = 0; j < N; j++) { if (arr[j][i] == 'X') y += 1; else y = 0; dp[j][i].second = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. int maxval = 0, val = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { val = min(dp[i][j].first, dp[i][j].second); if (dp[i][j - val + 1].second >= val && dp[i - val + 1][j].first >= val) maxside[i][j] = val; else maxside[i][j] = 0; // store the final answer in maxval maxval = max(maxval, maxside[i][j]); } } // return the final answe. return maxval; } // Driver code int main() { int mat[][N] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call cout << maximumSubSquare(mat); return 0; }",quadratic,quadratic "// A C++ program to implement flood fill algorithm #include using namespace std; // Dimensions of paint screen #define M 8 #define N 8 // A recursive function to replace previous color 'prevC' at '(x, y)' // and all surrounding pixels of (x, y) with new color 'newC' and void floodFillUtil(int screen[][N], int x, int y, int prevC, int newC) { // Base cases if (x < 0 || x >= M || y < 0 || y >= N) return; if (screen[x][y] != prevC) return; if (screen[x][y] == newC) return; // Replace the color at (x, y) screen[x][y] = newC; // Recur for north, east, south and west floodFillUtil(screen, x+1, y, prevC, newC); floodFillUtil(screen, x-1, y, prevC, newC); floodFillUtil(screen, x, y+1, prevC, newC); floodFillUtil(screen, x, y-1, prevC, newC); } // It mainly finds the previous color on (x, y) and // calls floodFillUtil() void floodFill(int screen[][N], int x, int y, int newC) { int prevC = screen[x][y]; if(prevC==newC) return; floodFillUtil(screen, x, y, prevC, newC); } // Driver code int main() { int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 1}, {1, 2, 2, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 0, 1, 0}, {1, 1, 1, 2, 2, 2, 2, 0}, {1, 1, 1, 1, 1, 2, 1, 1}, {1, 1, 1, 1, 1, 2, 2, 1}, }; int x = 4, y = 4, newC = 3; floodFill(screen, x, y, newC); cout << ""Updated screen after call to floodFill: \n""; for (int i=0; i using namespace std; // Function to check valid coordinate int validCoord(int x, int y, int n, int m) { if (x < 0 || y < 0) { return 0; } if (x >= n || y >= m) { return 0; } return 1; } // Function to run bfs void bfs(int n, int m, int data[][8], int x, int y, int color) { // Visiting array int vis[101][101]; // Initializing all as zero memset(vis, 0, sizeof(vis)); // Creating queue for bfs queue > obj; // Pushing pair of {x, y} obj.push({ x, y }); // Marking {x, y} as visited vis[x][y] = 1; // Until queue is empty while (obj.empty() != 1) { // Extracting front pair pair coord = obj.front(); int x = coord.first; int y = coord.second; int preColor = data[x][y]; data[x][y] = color; // Popping front pair of queue obj.pop(); // For Upside Pixel or Cell if (validCoord(x + 1, y, n, m) && vis[x + 1][y] == 0 && data[x + 1][y] == preColor) { obj.push({ x + 1, y }); vis[x + 1][y] = 1; } // For Downside Pixel or Cell if (validCoord(x - 1, y, n, m) && vis[x - 1][y] == 0 && data[x - 1][y] == preColor) { obj.push({ x - 1, y }); vis[x - 1][y] = 1; } // For Right side Pixel or Cell if (validCoord(x, y + 1, n, m) && vis[x][y + 1] == 0 && data[x][y + 1] == preColor) { obj.push({ x, y + 1 }); vis[x][y + 1] = 1; } // For Left side Pixel or Cell if (validCoord(x, y - 1, n, m) && vis[x][y - 1] == 0 && data[x][y - 1] == preColor) { obj.push({ x, y - 1 }); vis[x][y - 1] = 1; } } // Printing The Changed Matrix Of Pixels for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << data[i][j] << "" ""; } cout << endl; } cout << endl; } // Driver Code int main() { int n, m, x, y, color; n = 8; m = 8; int data[8][8] = { { 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 1, 1, 0, 0 }, { 1, 0, 0, 1, 1, 0, 1, 1 }, { 1, 2, 2, 2, 2, 0, 1, 0 }, { 1, 1, 1, 2, 2, 0, 1, 0 }, { 1, 1, 1, 2, 2, 2, 2, 0 }, { 1, 1, 1, 1, 1, 2, 1, 1 }, { 1, 1, 1, 1, 1, 2, 2, 1 }, }; x = 4, y = 4, color = 3; // Function Call bfs(n, m, data, x, y, color); return 0; }",quadratic,quadratic "#include using namespace std; // Function to print all elements of matrix in sorted orderd void sortedMatrix(int N, vector > Mat) { vector temp; // Store all elements of matrix into temp for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { temp.push_back(Mat[i][j]); } } // Sort the temp sort(temp.begin(), temp.end()); // Print the values of temp for (int i = 0; i < temp.size(); i++) { cout << temp[i] << "" ""; } } int main() { int N = 4; vector > Mat = { { 10, 20, 30, 40 }, { 15, 25, 35, 45 }, { 27, 29, 37, 48 }, { 32, 33, 39, 50 }, }; sortedMatrix(N, Mat); return 0; } // This code is contributed by pratiknawale999",quadratic,quadratic "// C++ program to merge k sorted arrays of size n each. #include #include using namespace std; #define N 4 // A min heap node struct MinHeapNode { int element; // The element to be stored int i; // index of the row from which the element is taken int j; // index of the next element to be picked from row }; // Prototype of a utility function to swap two min heap nodes void swap(MinHeapNode *x, MinHeapNode *y); // A class for Min Heap class MinHeap { MinHeapNode *harr; // pointer to array of elements in heap int heap_size; // size of min heap public: // Constructor: creates a min heap of given size MinHeap(MinHeapNode a[], int size); // to heapify a subtree with root at given index void MinHeapify(int ); // to get index of left child of node at index i int left(int i) { return (2*i + 1); } // to get index of right child of node at index i int right(int i) { return (2*i + 2); } // to get the root MinHeapNode getMin() { return harr[0]; } // to replace root with new node x and heapify() new root void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); } }; // This function prints elements of a given matrix in non-decreasing // order. It assumes that ma[][] is sorted row wise sorted. void printSorted(int mat[][N]) { // Create a min heap with k heap nodes. Every heap node // has first element of an array MinHeapNode *harr = new MinHeapNode[N]; for (int i = 0; i < N; i++) { harr[i].element = mat[i][0]; // Store the first element harr[i].i = i; // index of row harr[i].j = 1; // Index of next element to be stored from row } MinHeap hp(harr, N); // Create the min heap // Now one by one get the minimum element from min // heap and replace it with next element of its array for (int count = 0; count < N*N; count++) { // Get the minimum element and store it in output MinHeapNode root = hp.getMin(); cout << root.element << "" ""; // Find the next element that will replace current // root of heap. The next element belongs to same // array as the current root. if (root.j < N) { root.element = mat[root.i][root.j]; root.j += 1; } // If root was the last element of its array else root.element = INT_MAX; //INT_MAX is for infinite // Replace root with next element of array hp.replaceMin(root); } } // FOLLOWING ARE IMPLEMENTATIONS OF STANDARD MIN HEAP METHODS // FROM CORMEN BOOK // Constructor: Builds a heap from a given array a[] of given size MinHeap::MinHeap(MinHeapNode a[], int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1)/2; while (i >= 0) { MinHeapify(i); i--; } } // A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l].element < harr[i].element) smallest = l; if (r < heap_size && harr[r].element < harr[smallest].element) smallest = r; if (smallest != i) { swap(↔[i], ↔[smallest]); MinHeapify(smallest); } } // A utility function to swap two elements void swap(MinHeapNode *x, MinHeapNode *y) { MinHeapNode temp = *x; *x = *y; *y = temp; } // driver program to test above function int main() { int mat[N][N] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}, }; printSorted(mat); return 0; }",linear,quadratic "// A simple C++ program to find sum of all subsquares of // size k x k #include using namespace std; // Size of given matrix #define n 5 // A simple function to find sum of all sub-squares of size // k x k in a given square matrix of size n x n void printSumSimple(int mat[][n], int k) { // k must be smaller than or equal to n if (k > n) return; // row number of first cell in current sub-square of // size k x k for (int i = 0; i < n - k + 1; i++) { // column of first cell in current sub-square of // size k x k for (int j = 0; j < n - k + 1; j++) { // Calculate and print sum of current sub-square int sum = 0; for (int p = i; p < k + i; p++) for (int q = j; q < k + j; q++) sum += mat[p][q]; cout << sum << "" ""; } // Line separator for sub-squares starting with next // row cout << endl; } } // Driver program to test above function int main() { int mat[n][n] = { { 1, 1, 1, 1, 1 }, { 2, 2, 2, 2, 2 }, { 3, 3, 3, 3, 3 }, { 4, 4, 4, 4, 4 }, { 5, 5, 5, 5, 5 }, }; int k = 3; printSumSimple(mat, k); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,quadratic "// An efficient C++ program to find sum of all subsquares of // size k x k #include using namespace std; // Size of given matrix #define n 5 // A O(n^2) function to find sum of all sub-squares of size // k x k in a given square matrix of size n x n void printSumTricky(int mat[][n], int k) { // k must be smaller than or equal to n if (k > n) return; // 1: PREPROCESSING // To store sums of all strips of size k x 1 int stripSum[n][n]; // Go column by column for (int j = 0; j < n; j++) { // Calculate sum of first k x 1 rectangle in this // column int sum = 0; for (int i = 0; i < k; i++) sum += mat[i][j]; stripSum[0][j] = sum; // Calculate sum of remaining rectangles for (int i = 1; i < n - k + 1; i++) { sum += (mat[i + k - 1][j] - mat[i - 1][j]); stripSum[i][j] = sum; } } // 2: CALCULATE SUM of Sub-Squares using stripSum[][] for (int i = 0; i < n - k + 1; i++) { // Calculate and print sum of first subsquare in // this row int sum = 0; for (int j = 0; j < k; j++) sum += stripSum[i][j]; cout << sum << "" ""; // Calculate sum of remaining squares in current row // by removing the leftmost strip of previous // sub-square and adding a new strip for (int j = 1; j < n - k + 1; j++) { sum += (stripSum[i][j + k - 1] - stripSum[i][j - 1]); cout << sum << "" ""; } cout << endl; } } // Driver program to test above function int main() { int mat[n][n] = { { 1, 1, 1, 1, 1 }, { 2, 2, 2, 2, 2 }, { 3, 3, 3, 3, 3 }, { 4, 4, 4, 4, 4 }, { 5, 5, 5, 5, 5 }, }; int k = 3; printSumTricky(mat, k); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",quadratic,quadratic "// C++ program to find // transpose of a matrix #include using namespace std; #define N 4 // This function stores transpose // of A[][] in B[][] void transpose(int A[][N], int B[][N]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i]; } // Driver code int main() { int A[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; // Note dimensions of B[][] int B[N][N], i, j; // Function call transpose(A, B); cout << ""Result matrix is \n""; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << "" "" << B[i][j]; cout << ""\n""; } return 0; } // This code is contributed by shivanisinghss2110",quadratic,quadratic "#include using namespace std; #define N 4 // Converts A[][] to its transpose void transpose(int A[][N]) { for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) swap(A[i][j], A[j][i]); } int main() { int A[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; transpose(A); printf(""Modified matrix is \n""); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(""%d "", A[i][j]); printf(""\n""); } return 0; }",constant,quadratic "// C++ program for addition // of two matrices #include using namespace std; #define N 4 // This function adds A[][] and B[][], and stores // the result in C[][] void add(int A[][N], int B[][N], int C[][N]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) C[i][j] = A[i][j] + B[i][j]; } // Driver code int main() { int A[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int B[N][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } }; int C[N][N]; // To store result int i, j; // Function Call add(A, B, C); cout << ""Result matrix is "" << endl; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout << C[i][j] << "" ""; cout << endl; } return 0; } // This code is contributed by rathbhupendra",quadratic,quadratic "// A Memoization based program to find maximum collection // using two traversals of a grid #include using namespace std; #define R 5 #define C 4 // checks whether a given input is valid or not bool isValid(int x, int y1, int y2) { return (x >= 0 && x < R && y1 >=0 && y1 < C && y2 >=0 && y2 < C); } // Driver function to collect max value int getMaxUtil(int arr[R][C], int mem[R][C][C], int x, int y1, int y2) { /*---------- BASE CASES -----------*/ // if P1 or P2 is at an invalid cell if (!isValid(x, y1, y2)) return INT_MIN; // if both traversals reach their destinations if (x == R-1 && y1 == 0 && y2 == C-1) return (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; // If both traversals are at last row but not at their destination if (x == R-1) return INT_MIN; // If subproblem is already solved if (mem[x][y1][y2] != -1) return mem[x][y1][y2]; // Initialize answer for this subproblem int ans = INT_MIN; // this variable is used to store gain of current cell(s) int temp = (y1 == y2)? arr[x][y1]: arr[x][y1] + arr[x][y2]; /* Recur for all possible cases, then store and return the one with max value */ ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1)); ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1)); return (mem[x][y1][y2] = ans); } // This is mainly a wrapper over recursive function getMaxUtil(). // This function creates a table for memoization and calls // getMaxUtil() int geMaxCollection(int arr[R][C]) { // Create a memoization table and initialize all entries as -1 int mem[R][C][C]; memset(mem, -1, sizeof(mem)); // Calculation maximum value using memoization based function // getMaxUtil() return getMaxUtil(arr, mem, 0, 0, C-1); } // Driver program to test above functions int main() { int arr[R][C] = {{3, 6, 8, 2}, {5, 2, 4, 3}, {1, 1, 20, 10}, {1, 1, 20, 10}, {1, 1, 20, 10}, }; cout << ""Maximum collection is "" << geMaxCollection(arr); return 0; }",quadratic,cubic " // A Naive Recursive C++ program // to count paths with exactly // 'k' coins #include #define R 3 #define C 3 using namespace std; // Recursive function to count paths with sum k from // (0, 0) to (m, n) int pathCountRec(int mat[][C], int m, int n, int k) { // Base cases if (m < 0 || n < 0 || k < 0) return 0; if (m==0 && n==0) return (k == mat[m][n]); // (m, n) can be reached either through (m-1, n) or // through (m, n-1) return pathCountRec(mat, m-1, n, k-mat[m][n]) + pathCountRec(mat, m, n-1, k-mat[m][n]); } // A wrapper over pathCountRec() int pathCount(int mat[][C], int k) { return pathCountRec(mat, R-1, C-1, k); } // Driver program int main() { int k = 12; int mat[R][C] = { {1, 2, 3}, {4, 6, 5}, {3, 2, 1} }; cout << pathCount(mat, k); return 0; }",quadratic,linear "// A Dynamic Programming based C++ program to count paths with // exactly 'k' coins #include #define R 3 #define C 3 #define MAX_K 1000 using namespace std; int dp[R][C][MAX_K]; int pathCountDPRecDP(int mat[][C], int m, int n, int k) { // Base cases if (m < 0 || n < 0 || k < 0) return 0; if (m==0 && n==0) return (k == mat[m][n]); // If this subproblem is already solved if (dp[m][n][k] != -1) return dp[m][n][k]; // (m, n) can be reached either through (m-1, n) or // through (m, n-1) dp[m][n][k] = pathCountDPRecDP(mat, m-1, n, k-mat[m][n]) + pathCountDPRecDP(mat, m, n-1, k-mat[m][n]); return dp[m][n][k]; } // This function mainly initializes dp[][][] and calls // pathCountDPRecDP() int pathCountDP(int mat[][C], int k) { memset(dp, -1, sizeof dp); return pathCountDPRecDP(mat, R-1, C-1, k); } // Driver Program to test above functions int main() { int k = 12; int mat[R][C] = { {1, 2, 3}, {4, 6, 5}, {3, 2, 1} }; cout << pathCountDP(mat, k); return 0; }",quadratic,quadratic "// C++ program to find minimum initial points to reach // destination #include #define R 3 #define C 3 using namespace std; int minInitialPoints(int points[][C]) { // dp[i][j] represents the minimum initial points player // should have so that when starts with cell(i, j) // successfully reaches the destination cell(m-1, n-1) int dp[R][C]; int m = R, n = C; // Base case dp[m - 1][n - 1] = points[m - 1][n - 1] > 0 ? 1 : abs(points[m - 1][n - 1]) + 1; // Fill last row and last column as base to fill // entire table for (int i = m - 2; i >= 0; i--) dp[i][n - 1] = max(dp[i + 1][n - 1] - points[i][n - 1], 1); for (int j = n - 2; j >= 0; j--) dp[m - 1][j] = max(dp[m - 1][j + 1] - points[m - 1][j], 1); // fill the table in bottom-up fashion for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { int min_points_on_exit = min(dp[i + 1][j], dp[i][j + 1]); dp[i][j] = max(min_points_on_exit - points[i][j], 1); } } return dp[0][0]; } // Driver Program int main() { int points[R][C] = { { -2, -3, 3 }, { -5, -10, 1 }, { 10, 30, -5 } }; cout << ""Minimum Initial Points Required: "" << minInitialPoints(points); return 0; }",quadratic,quadratic "// Program to find maximum sum subarray // in a given 2D array #include using namespace std; #define ROW 4 #define COL 5 // Implementation of Kadane's algorithm for // 1D array. The function returns the maximum // sum and stores starting and ending indexes // of the maximum sum subarray at addresses // pointed by start and finish pointers // respectively. int kadane(int* arr, int* start, int* finish, int n) { // initialize sum, maxSum and int sum = 0, maxSum = INT_MIN, i; // Just some initial value to check // for all negative values case *finish = -1; // local variable int local_start = 0; for (i = 0; i < n; ++i) { sum += arr[i]; if (sum < 0) { sum = 0; local_start = i + 1; } else if (sum > maxSum) { maxSum = sum; *start = local_start; *finish = i; } } // There is at-least one // non-negative number if (*finish != -1) return maxSum; // Special Case: When all numbers // in arr[] are negative maxSum = arr[0]; *start = *finish = 0; // Find the maximum element in array for (i = 1; i < n; i++) { if (arr[i] > maxSum) { maxSum = arr[i]; *start = *finish = i; } } return maxSum; } // The main function that finds // maximum sum rectangle in M[][] void findMaxSum(int M[][COL]) { // Variables to store the final output int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom; int left, right, i; int temp[ROW], sum, start, finish; // Set the left column for (left = 0; left < COL; ++left) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left // column set by outer loop for (right = left; right < COL; ++right) { // Calculate sum between current left // and right for every row 'i' for (i = 0; i < ROW; ++i) temp[i] += M[i][right]; // Find the maximum sum subarray in temp[]. // The kadane() function also sets values // of start and finish. So 'sum' is sum of // rectangle between (start, left) and // (finish, right) which is the maximum sum // with boundary columns strictly as left // and right. sum = kadane(temp, &start, &finish, ROW); // Compare sum with maximum sum so far. // If sum is more, then update maxSum and // other output values if (sum > maxSum) { maxSum = sum; finalLeft = left; finalRight = right; finalTop = start; finalBottom = finish; } } } // Print final values cout << ""(Top, Left) ("" << finalTop << "", "" << finalLeft << "")"" << endl; cout << ""(Bottom, Right) ("" << finalBottom << "", "" << finalRight << "")"" << endl; cout << ""Max sum is: "" << maxSum << endl; } // Driver Code int main() { int M[ROW][COL] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call findMaxSum(M); return 0; } // This code is contributed by // rathbhupendra",linear,cubic "/* Program to implement a stack using two queue */ #include using namespace std; class Stack { // Two inbuilt queues queue q1, q2; public: void push(int x) { // Push x first in empty q2 q2.push(x); // Push all the remaining // elements in q1 to q2. while (!q1.empty()) { q2.push(q1.front()); q1.pop(); } // swap the names of two queues queue q = q1; q1 = q2; q2 = q; } void pop() { // if no elements are there in q1 if (q1.empty()) return; q1.pop(); } int top() { if (q1.empty()) return -1; return q1.front(); } int size() { return q1.size(); } }; // Driver code int main() { Stack s; s.push(1); s.push(2); s.push(3); cout << ""current size: "" << s.size() << endl; cout << s.top() << endl; s.pop(); cout << s.top() << endl; s.pop(); cout << s.top() << endl; cout << ""current size: "" << s.size() << endl; return 0; } // This code is contributed by Chhavi",linear,linear "// Program to implement a stack // using two queue #include using namespace std; class Stack { queue q1, q2; public: void pop() { if (q1.empty()) return; // Leave one element in q1 and // push others in q2. while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } // Pop the only left element // from q1 q1.pop(); // swap the names of two queues queue q = q1; q1 = q2; q2 = q; } void push(int x) { q1.push(x); } int top() { if (q1.empty()) return -1; while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } // last pushed element int temp = q1.front(); // to empty the auxiliary queue after // last operation q1.pop(); // push last element to q2 q2.push(temp); // swap the two queues names queue q = q1; q1 = q2; q2 = q; return temp; } int size() { return q1.size(); } }; // Driver code int main() { Stack s; s.push(1); s.push(2); s.push(3); cout << ""current size: "" << s.size() << endl; cout << s.top() << endl; s.pop(); cout << s.top() << endl; s.pop(); cout << s.top() << endl; cout << ""current size: "" << s.size() << endl; return 0; } // This code is contributed by Chhavi",linear,linear "#include using namespace std; // Stack Class that acts as a queue class Stack { queue q; public: void push(int data); void pop(); int top(); int size(); bool empty(); }; // Push operation void Stack::push(int data) { // Get previous size of queue int s = q.size(); // Push the current element q.push(data); // Pop all the previous elements and put them after // current element for (int i = 0; i < s; i++) { // Add the front element again q.push(q.front()); // Delete front element q.pop(); } } // Removes the top element void Stack::pop() { if (q.empty()) cout << ""No elements\n""; else q.pop(); } // Returns top of stack int Stack::top() { return (q.empty()) ? -1 : q.front(); } // Returns true if Stack is empty else false bool Stack::empty() { return (q.empty()); } int Stack::size() { return q.size(); } int main() { Stack st; st.push(1); st.push(2); st.push(3); cout << ""current size: "" << st.size() << ""\n""; cout << st.top() << ""\n""; st.pop(); cout << st.top() << ""\n""; st.pop(); cout << st.top() << ""\n""; cout << ""current size: "" << st.size(); return 0; }",linear,linear "#include using namespace std; struct QNode { int data; QNode* next; QNode(int d) { data = d; next = NULL; } }; struct Queue { QNode *front, *rear; Queue() { front = rear = NULL; } void enQueue(int x) { // Create a new LL node QNode* temp = new QNode(x); // If queue is empty, then // new node is front and rear both if (rear == NULL) { front = rear = temp; return; } // Add the new node at // the end of queue and change rear rear->next = temp; rear = temp; } // Function to remove // a key from given queue q void deQueue() { // If queue is empty, return NULL. if (front == NULL) return; // Store previous front and // move front one node ahead QNode* temp = front; front = front->next; // If front becomes NULL, then // change rear also as NULL if (front == NULL) rear = NULL; delete (temp); } }; // Driven Program int main() { Queue q; q.enQueue(10); q.enQueue(20); q.deQueue(); q.deQueue(); q.enQueue(30); q.enQueue(40); q.enQueue(50); q.deQueue(); cout << ""Queue Front : "" << (q.front)->data << endl; cout << ""Queue Rear : "" << (q.rear)->data; } // This code is contributed by rathbhupendra",constant,constant "// C++ implementation of De-queue using circular // array #include using namespace std; // Maximum size of array or Dequeue #define MAX 100 // A structure to represent a Deque class Deque { int arr[MAX]; int front; int rear; int size; public: Deque(int size) { front = -1; rear = 0; this->size = size; } // Operations on Deque: void insertfront(int key); void insertrear(int key); void deletefront(); void deleterear(); bool isFull(); bool isEmpty(); int getFront(); int getRear(); }; // Checks whether Deque is full or not. bool Deque::isFull() { return ((front == 0 && rear == size - 1) || front == rear + 1); } // Checks whether Deque is empty or not. bool Deque::isEmpty() { return (front == -1); } // Inserts an element at front void Deque::insertfront(int key) { // check whether Deque if full or not if (isFull()) { cout << ""Overflow\n"" << endl; return; } // If queue is initially empty if (front == -1) { front = 0; rear = 0; } // front is at first position of queue else if (front == 0) front = size - 1; else // decrement front end by '1' front = front - 1; // insert current element into Deque arr[front] = key; } // function to inset element at rear end // of Deque. void Deque ::insertrear(int key) { if (isFull()) { cout << "" Overflow\n "" << endl; return; } // If queue is initially empty if (front == -1) { front = 0; rear = 0; } // rear is at last position of queue else if (rear == size - 1) rear = 0; // increment rear end by '1' else rear = rear + 1; // insert current element into Deque arr[rear] = key; } // Deletes element at front end of Deque void Deque ::deletefront() { // check whether Deque is empty or not if (isEmpty()) { cout << ""Queue Underflow\n"" << endl; return; } // Deque has only one element if (front == rear) { front = -1; rear = -1; } else // back to initial position if (front == size - 1) front = 0; else // increment front by '1' to remove current // front value from Deque front = front + 1; } // Delete element at rear end of Deque void Deque::deleterear() { if (isEmpty()) { cout << "" Underflow\n"" << endl; return; } // Deque has only one element if (front == rear) { front = -1; rear = -1; } else if (rear == 0) rear = size - 1; else rear = rear - 1; } // Returns front element of Deque int Deque::getFront() { // check whether Deque is empty or not if (isEmpty()) { cout << "" Underflow\n"" << endl; return -1; } return arr[front]; } // function return rear element of Deque int Deque::getRear() { // check whether Deque is empty or not if (isEmpty() || rear < 0) { cout << "" Underflow\n"" << endl; return -1; } return arr[rear]; } // Driver code int main() { Deque dq(5); // Function calls cout << ""Insert element at rear end : 5 \n""; dq.insertrear(5); cout << ""insert element at rear end : 10 \n""; dq.insertrear(10); cout << ""get rear element "" << "" "" << dq.getRear() << endl; dq.deleterear(); cout << ""After delete rear element new rear"" << "" become "" << dq.getRear() << endl; cout << ""inserting element at front end \n""; dq.insertfront(15); cout << ""get front element "" << "" "" << dq.getFront() << endl; dq.deletefront(); cout << ""After delete front element new "" << ""front become "" << dq.getFront() << endl; return 0; }",linear,linear "// C++ Program to implement stack and queue using Deque #include using namespace std; // structure for a node of deque struct DQueNode { int value; DQueNode* next; DQueNode* prev; }; // Implementation of deque class class Deque { private: // pointers to head and tail of deque DQueNode* head; DQueNode* tail; public: // constructor Deque() { head = tail = NULL; } // if list is empty bool isEmpty() { if (head == NULL) return true; return false; } // count the number of nodes in list int size() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; int len = 0; while (temp != NULL) { len++; temp = temp->next; } return len; } return 0; } // insert at the first position void insert_first(int element) { // allocating node of DQueNode type DQueNode* temp = new DQueNode[sizeof(DQueNode)]; temp->value = element; // if the element is first element if (head == NULL) { head = tail = temp; temp->next = temp->prev = NULL; } else { head->prev = temp; temp->next = head; temp->prev = NULL; head = temp; } } // insert at last position of deque void insert_last(int element) { // allocating node of DQueNode type DQueNode* temp = new DQueNode[sizeof(DQueNode)]; temp->value = element; // if element is the first element if (head == NULL) { head = tail = temp; temp->next = temp->prev = NULL; } else { tail->next = temp; temp->next = NULL; temp->prev = tail; tail = temp; } } // remove element at the first position void remove_first() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; head = head->next; if(head) head->prev = NULL; delete temp; if(head == NULL) tail = NULL; return; } cout << ""List is Empty"" << endl; } // remove element at the last position void remove_last() { // if list is not empty if (!isEmpty()) { DQueNode* temp = tail; tail = tail->prev; if(tail) tail->next = NULL; delete temp; if(tail == NULL) head = NULL; return; } cout << ""List is Empty"" << endl; } // displays the elements in deque void display() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; while (temp != NULL) { cout << temp->value << "" ""; temp = temp->next; } cout << endl; return; } cout << ""List is Empty"" << endl; } }; // Class to implement stack using Deque class Stack : public Deque { public: // push to push element at top of stack // using insert at last function of deque void push(int element) { insert_last(element); } // pop to remove element at top of stack // using remove at last function of deque void pop() { remove_last(); } }; // class to implement queue using deque class Queue : public Deque { public: // enqueue to insert element at last // using insert at last function of deque void enqueue(int element) { insert_last(element); } // dequeue to remove element from first // using remove at first function of deque void dequeue() { remove_first(); } }; // Driver Code int main() { // object of Stack Stack stk; // push 7 and 8 at top of stack stk.push(7); stk.push(8); cout << ""Stack: ""; stk.display(); // pop an element stk.pop(); cout << ""Stack: ""; stk.display(); // object of Queue Queue que; // insert 12 and 13 in queue que.enqueue(12); que.enqueue(13); cout << ""Queue: ""; que.display(); // delete an element from queue que.dequeue(); cout << ""Queue: ""; que.display(); cout << ""Size of Stack is "" << stk.size() << endl; cout << ""Size of Queue is "" << que.size() << endl; return 0; }",linear,linear "// Program to print BFS traversal from a given // source vertex. BFS(int s) traverses vertices // reachable from s. #include using namespace std; // This class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing adjacency // lists vector> adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints BFS traversal from a given source s void BFS(int s); }; Graph::Graph(int V) { this->V = V; adj.resize(V); } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::BFS(int s) { // Mark all the vertices as not visited vector visited; visited.resize(V,false); // Create a queue for BFS list queue; // Mark the current node as visited and enqueue it visited[s] = true; queue.push_back(s); while(!queue.empty()) { // Dequeue a vertex from queue and print it s = queue.front(); cout << s << "" ""; queue.pop_front(); // Get all adjacent vertices of the dequeued // vertex s. If a adjacent has not been visited, // then mark it visited and enqueue it for (auto adjecent: adj[s]) { if (!visited[adjecent]) { visited[adjecent] = true; queue.push_back(adjecent); } } } } // Driver program to test methods of graph class int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << ""Following is Breadth First Traversal "" << ""(starting from vertex 2) \n""; g.BFS(2); return 0; }",linear,linear "// Recursive CPP program for level // order traversal of Binary Tree #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ class node { public: int data; node *left, *right; }; /* Function prototypes */ void printCurrentLevel(node* root, int level); int height(node* node); node* newNode(int data); /* Function to print level order traversal a tree*/ void printLevelOrder(node* root) { int h = height(root); int i; for (i = 1; i <= h; i++) printCurrentLevel(root, i); } /* Print nodes at a current level */ void printCurrentLevel(node* root, int level) { if (root == NULL) return; if (level == 1) cout << root->data << "" ""; else if (level > 1) { printCurrentLevel(root->left, level - 1); printCurrentLevel(root->right, level - 1); } } /* Compute the ""height"" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(node* node) { if (node == NULL) return 0; else { /* compute the height of each subtree */ int lheight = height(node->left); int rheight = height(node->right); /* use the larger one */ if (lheight > rheight) { return (lheight + 1); } else { return (rheight + 1); } } } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ node* newNode(int data) { node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node); } /* Driver code*/ int main() { node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << ""Level Order traversal of binary tree is \n""; printLevelOrder(root); return 0; } // This code is contributed by rathbhupendra",linear,quadratic "/* C++ program to print level order traversal using STL */ #include using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // Iterative method to find height of Binary Tree void printLevelOrder(Node* root) { // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue q; // Enqueue Root and initialize height q.push(root); while (q.empty() == false) { // Print front of queue and remove it from queue Node* node = q.front(); cout << node->data << "" ""; q.pop(); /* Enqueue left child */ if (node->left != NULL) q.push(node->left); /*Enqueue right child */ if (node->right != NULL) q.push(node->right); } } // Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } // Driver program to test above functions int main() { // Let us create binary tree shown in above diagram Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << ""Level Order traversal of binary tree is \n""; printLevelOrder(root); return 0; }",linear,linear "// C++ program to create a Complete Binary tree from its Linked List // Representation #include #include #include using namespace std; // Linked list node struct ListNode { int data; ListNode* next; }; // Binary tree node structure struct BinaryTreeNode { int data; BinaryTreeNode *left, *right; }; // Function to insert a node at the beginning of the Linked List void push(struct ListNode** head_ref, int new_data) { // allocate node and assign data struct ListNode* new_node = new ListNode; new_node->data = new_data; // link the old list off the new node new_node->next = (*head_ref); // move the head to point to the new node (*head_ref) = new_node; } // method to create a new binary tree node from the given data BinaryTreeNode* newBinaryTreeNode(int data) { BinaryTreeNode *temp = new BinaryTreeNode; temp->data = data; temp->left = temp->right = NULL; return temp; } // converts a given linked list representing a complete binary tree into the // linked representation of binary tree. void convertList2Binary(ListNode *head, BinaryTreeNode* &root) { // queue to store the parent nodes queue q; // Base Case if (head == NULL) { root = NULL; // Note that root is passed by reference return; } // 1.) The first node is always the root node, and add it to the queue root = newBinaryTreeNode(head->data); q.push(root); // advance the pointer to the next node head = head->next; // until the end of linked list is reached, do the following steps while (head) { // 2.a) take the parent node from the q and remove it from q BinaryTreeNode* parent = q.front(); q.pop(); // 2.c) take next two nodes from the linked list. We will add // them as children of the current parent node in step 2.b. Push them // into the queue so that they will be parents to the future nodes BinaryTreeNode *leftChild = NULL, *rightChild = NULL; leftChild = newBinaryTreeNode(head->data); q.push(leftChild); head = head->next; if (head) { rightChild = newBinaryTreeNode(head->data); q.push(rightChild); head = head->next; } // 2.b) assign the left and right children of parent parent->left = leftChild; parent->right = rightChild; } } // Utility function to traverse the binary tree after conversion void inorderTraversal(BinaryTreeNode* root) { if (root) { inorderTraversal( root->left ); cout << root->data << "" ""; inorderTraversal( root->right ); } } // Driver program to test above functions int main() { // create a linked list shown in above diagram struct ListNode* head = NULL; push(&head, 36); /* Last node of Linked List */ push(&head, 30); push(&head, 25); push(&head, 15); push(&head, 12); push(&head, 10); /* First node of Linked List */ BinaryTreeNode *root; convertList2Binary(head, root); cout << ""Inorder Traversal of the constructed Binary Tree is: \n""; inorderTraversal(root); return 0; }",np,linear "// C++ program to check if a given binary tree is complete // or not #include using namespace std; // A binary tree node has data, pointer to left child and a // pointer to right child struct node { int data; struct node* left; struct node* right; }; // Given a binary tree, return true if the tree is complete // else false bool isCompleteBT(node* root) { // Base Case: An empty tree is complete Binary Tree if (root == NULL) return true; // Create an empty queue // int rear, front; // node **queue = createQueue(&front, &rear); queue q; q.push(root); // Create a flag variable which will be set true when a // non full node is seen bool flag = false; // Do level order traversal using queue. // enQueue(queue, &rear, root); while (!q.empty()) { node* temp = q.front(); q.pop(); /* Check if left child is present*/ if (temp->left) { // If we have seen a non full node, and we see a // node with non-empty left child, then the // given tree is not a complete Binary Tree if (flag == true) return false; q.push(temp->left); // Enqueue Left Child } // If this a non-full node, set the flag as true else flag = true; /* Check if right child is present*/ if (temp->right) { // If we have seen a non full node, and we see a // node with non-empty right child, then the // given tree is not a complete Binary Tree if (flag == true) return false; q.push(temp->right); // Enqueue Right Child } // If this a non-full node, set the flag as true else flag = true; } // If we reach here, then the tree is complete Binary // Tree return true; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } /* Driver code*/ int main() { /* Let us construct the following Binary Tree which is not a complete Binary Tree 1 / \ 2 3 / \ / 4 5 6 */ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); if (isCompleteBT(root) == true) cout << ""Complete Binary Tree""; else cout << ""NOT Complete Binary Tree""; return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)",linear,linear "// C++ implementation of a O(n) time method for // Zigzag order traversal #include #include using namespace std; // Binary Tree node struct Node { int data; struct Node *left, *right; }; // function to print the zigzag traversal void zizagtraversal(struct Node* root) { // if null then return if (!root) return; // declare two stacks stack currentlevel; stack nextlevel; // push the root currentlevel.push(root); // check if stack is empty bool lefttoright = true; while (!currentlevel.empty()) { // pop out of stack struct Node* temp = currentlevel.top(); currentlevel.pop(); // if not null if (temp) { // print the data in it cout << temp->data << "" ""; // store data according to current // order. if (lefttoright) { if (temp->left) nextlevel.push(temp->left); if (temp->right) nextlevel.push(temp->right); } else { if (temp->right) nextlevel.push(temp->right); if (temp->left) nextlevel.push(temp->left); } } if (currentlevel.empty()) { lefttoright = !lefttoright; swap(currentlevel, nextlevel); } } } // A utility function to create a new node struct Node* newNode(int data) { struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node); } // driver program to test the above function int main() { // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << ""ZigZag Order traversal of binary tree is \n""; zizagtraversal(root); return 0; }",linear,linear "// C++ implementation of a O(n) time method for // Zigzag order traversal #include #include using namespace std; // Binary Tree node class Node { public: int data; Node *left, *right; }; // Function to print the zigzag traversal vector zigZagTraversal(Node* root) { deque q; vector v; q.push_back(root); v.push_back(root->data); Node* temp; // set initial level as 1, because root is // already been taken care of. int l = 1; while (!q.empty()) { int n = q.size(); for (int i = 0; i < n; i++) { // popping mechanism if (l % 2 == 0) { temp = q.back(); q.pop_back(); } else { temp = q.front(); q.pop_front(); } // pushing mechanism if (l % 2 != 0) { if (temp->right) { q.push_back(temp->right); v.push_back(temp->right->data); } if (temp->left) { q.push_back(temp->left); v.push_back(temp->left->data); } } else if (l % 2 == 0) { if (temp->left) { q.push_front(temp->left); v.push_back(temp->left->data); } if (temp->right) { q.push_front(temp->right); v.push_back(temp->right->data); } } } l++; // level plus one } return v; } // A utility function to create a new node struct Node* newNode(int data) { struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver program to test // the above function int main() { // vector to store the traversal order. vector v; // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << ""ZigZag Order traversal of binary tree is \n""; v = zigZagTraversal(root); for (int i = 0; i < v.size(); i++) { // to print the order cout << v[i] << "" ""; } return 0; } // This code is contributed by Ritvik Mahajan",linear,linear "// C++ implementation of a O(n) time method for // Zigzag order traversal #include #include using namespace std; // Binary Tree node class Node { public: int data; Node *left, *right; }; // Function to print the zigzag traversal vector zigZagTraversal(Node* root) { if(root == NULL){return { } ; } vector ans ; queue q ; q.push(root) ; bool flag = false ; while(!q.empty()){ int size = q.size() ; vector level ; for(int i=0 ; i < size ; i++){ Node* node = q.front() ; q.pop() ; level.push_back(node->data) ; if(node->left != NULL) {q.push(node->left) ;} if(node->right != NULL) {q.push(node->right) ;} } flag = !flag ; if(flag == false){ reverse(level.begin() , level.end()) ; } for(int i = 0 ; i < level.size() ; i++){ ans.push_back(level[i]) ; } } return ans ; } // A utility function to create a new node struct Node* newNode(int data) { struct Node* node = new struct Node; node->data = data; node->left = node->right = NULL; return (node); } // Driver program to test // the above function int main() { // vector to store the traversal order. vector v; // create tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << ""ZigZag Order traversal of binary tree is \n""; v = zigZagTraversal(root); for (int i = 0; i < v.size(); i++) { // to print the order cout << v[i] << "" ""; } return 0; }",linear,linear "// C++ program to demonstrate // working of LIFO // using stack in C++ #include using namespace std; // Pushing element on the top of the stack stack stack_push(stack stack) { for (int i = 0; i < 5; i++) { stack.push(i); } return stack; } // Popping element from the top of the stack stack stack_pop(stack stack) { cout << ""Pop :""; for (int i = 0; i < 5; i++) { int y = (int)stack.top(); stack.pop(); cout << (y) << endl; } return stack; } // Displaying element on the top of the stack void stack_peek(stack stack) { int element = (int)stack.top(); cout << ""Element on stack top : "" << element << endl; } // Searching element in the stack void stack_search(stack stack, int element) { int pos = -1,co = 0; while(stack.size() > 0) { co++; if(stack.top() == element) { pos = co; break; } stack.pop(); } if (pos == -1) cout << ""Element not found"" << endl; else cout << ""Element is found at position "" << pos << endl; } // Driver code int main() { stack stack ; stack = stack_push(stack); stack = stack_pop(stack); stack = stack_push(stack); stack_peek(stack); stack_search(stack, 2); stack_search(stack, 6); return 0; } // This code is contributed by Arnab Kundu",linear,linear "// CPP program to reverse a Queue #include using namespace std; // Utility function to print the queue void Print(queue& Queue) { while (!Queue.empty()) { cout << Queue.front() << "" ""; Queue.pop(); } } // Function to reverse the queue void reverseQueue(queue& Queue) { stack Stack; while (!Queue.empty()) { Stack.push(Queue.front()); Queue.pop(); } while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } } // Driver code int main() { queue Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); Print(Queue); }",linear,linear "// CPP program to reverse a Queue #include using namespace std; // Utility function to print the queue void Print(queue& Queue) { while (!Queue.empty()) { cout << Queue.front() << "" ""; Queue.pop(); } } // Function to reverse the queue void reverseQueue(queue& q) { // base case if (q.size() == 0) return; // storing front(first element) of queue int fr = q.front(); // removing front q.pop(); // asking recursion to reverse the // leftover queue reverseQueue(q); // placing first element // at its correct position q.push(fr); } // Driver code int main() { queue Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); Print(Queue); } // This code is contributed by Nakshatra Chhillar",linear,linear "// C++ code for reversing a queue #include using namespace std; // Utility function to print the queue void printQueue(queue Queue) { while (!Queue.empty()) { cout << Queue.front() << "" ""; Queue.pop(); } } // Recursive function to reverse the queue void reverseQueue(queue& q) { // Base case if (q.empty()) return; // Dequeue current item (from front) long long int data = q.front(); q.pop(); // Reverse remaining queue reverseQueue(q); // Enqueue current item (to rear) q.push(data); } // Driver code int main() { queue Queue; Queue.push(56); Queue.push(27); Queue.push(30); Queue.push(45); Queue.push(85); Queue.push(92); Queue.push(58); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); printQueue(Queue); }",linear,linear "// C++ program to reverse first // k elements of a queue. #include using namespace std; /* Function to reverse the first K elements of the Queue */ void reverseQueueFirstKElements(int k, queue& Queue) { if (Queue.empty() == true || k > Queue.size()) return; if (k <= 0) return; stack Stack; /* Push the first K elements into a Stack*/ for (int i = 0; i < k; i++) { Stack.push(Queue.front()); Queue.pop(); } /* Enqueue the contents of stack at the back of the queue*/ while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } /* Remove the remaining elements and enqueue them at the end of the Queue*/ for (int i = 0; i < Queue.size() - k; i++) { Queue.push(Queue.front()); Queue.pop(); } } /* Utility Function to print the Queue */ void Print(queue& Queue) { while (!Queue.empty()) { cout << Queue.front() << "" ""; Queue.pop(); } } // Driver code int main() { queue Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); int k = 5; reverseQueueFirstKElements(k, Queue); Print(Queue); }",linear,linear "// C++ program to interleave the first half of the queue // with the second half #include using namespace std; // Function to interleave the queue void interLeaveQueue(queue& q) { // To check the even number of elements if (q.size() % 2 != 0) cout << ""Input even number of integers."" << endl; // Initialize an empty stack of int type stack s; int halfSize = q.size() / 2; // Push first half elements into the stack // queue:16 17 18 19 20, stack: 15(T) 14 13 12 11 for (int i = 0; i < halfSize; i++) { s.push(q.front()); q.pop(); } // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while (!s.empty()) { q.push(s.top()); s.pop(); } // dequeue the first half elements of queue // and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for (int i = 0; i < halfSize; i++) { q.push(q.front()); q.pop(); } // Again push the first half elements into the stack // queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15 for (int i = 0; i < halfSize; i++) { s.push(q.front()); q.pop(); } // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while (!s.empty()) { q.push(s.top()); s.pop(); q.push(q.front()); q.pop(); } } // Driver program to test above function int main() { queue q; q.push(11); q.push(12); q.push(13); q.push(14); q.push(15); q.push(16); q.push(17); q.push(18); q.push(19); q.push(20); interLeaveQueue(q); int length = q.size(); for (int i = 0; i < length; i++) { cout << q.front() << "" ""; q.pop(); } return 0; }",linear,linear "// C++ program for recursive level // order traversal in spiral form #include using namespace std; // A binary tree node has data, // pointer to left child and a // pointer to right child struct node { int data; struct node* left; struct node* right; }; // Function prototypes void printGivenLevel(struct node* root, int level, int ltr); int height(struct node* node); struct node* newNode(int data); // Function to print spiral traversal of a tree void printSpiral(struct node* root) { int h = height(root); int i; // ltr -> Left to Right. If this variable // is set,then the given level is traversed // from left to right. bool ltr = false; for (i = 1; i <= h; i++) { printGivenLevel(root, i, ltr); // Revert ltr to traverse next // level in opposite order ltr = !ltr; } } // Print nodes at a given level void printGivenLevel(struct node* root, int level, int ltr) { if (root == NULL) return; if (level == 1) cout << root->data << "" ""; else if (level > 1) { if (ltr) { printGivenLevel(root->left, level - 1, ltr); printGivenLevel(root->right, level - 1, ltr); } else { printGivenLevel(root->right, level - 1, ltr); printGivenLevel(root->left, level - 1, ltr); } } } // Compute the ""height"" of a tree -- the number of // nodes along the longest path from the root node // down to the farthest leaf node. int height(struct node* node) { if (node == NULL) return 0; else { // Compute the height of each subtree int lheight = height(node->left); int rheight = height(node->right); // Use the larger one if (lheight > rheight) return (lheight + 1); else return (rheight + 1); } } // Helper function that allocates a new // node with the given data and NULL left // and right pointers. struct node* newNode(int data) { node* newnode = new node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return (newnode); } // Driver code int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); printf(""Spiral Order traversal of "" ""binary tree is \n""); printSpiral(root); return 0; } // This code is contributed by samrat2825",linear,quadratic "// C++ implementation of a O(n) time method for spiral order // traversal #include #include using namespace std; // Binary Tree node struct node { int data; struct node *left, *right; }; void printSpiral(struct node* root) { if (root == NULL) return; // NULL check // Create two stacks to store alternate levels stack s1; // For levels to be printed from right to left stack s2; // For levels to be printed from left to right // Push first level to first stack 's1' s1.push(root); // Keep printing while any of the stacks has some nodes while (!s1.empty() || !s2.empty()) { // Print nodes of current level from s1 and push // nodes of next level to s2 while (!s1.empty()) { struct node* temp = s1.top(); s1.pop(); cout << temp->data << "" ""; // Note that is right is pushed before left if (temp->right) s2.push(temp->right); if (temp->left) s2.push(temp->left); } // Print nodes of current level from s2 and push // nodes of next level to s1 while (!s2.empty()) { struct node* temp = s2.top(); s2.pop(); cout << temp->data << "" ""; // Note that is left is pushed before right if (temp->left) s1.push(temp->left); if (temp->right) s1.push(temp->right); } } } // A utility function to create a new node struct node* newNode(int data) { struct node* node = new struct node; node->data = data; node->left = NULL; node->right = NULL; return (node); } int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << ""Spiral Order traversal of binary tree is \n""; printSpiral(root); return 0; }",linear,linear "// C++ implementation of above approach #include #include using namespace std; // Binary Tree node struct Node { int key; struct Node *left, *right; }; void spiralPrint(struct Node* root) { // Declare a deque deque dq; // Insert the root of the tree into the deque dq.push_back(root); // Create a variable that will switch in each iteration bool reverse = true; // Start iteration while (!dq.empty()) { // Save the size of the deque here itself, as in // further steps the size of deque will frequently // change int n = dq.size(); // If we are printing left to right if (!reverse) { // Iterate from left to right while (n--) { // Insert the child from the back of the // deque Left child first if (dq.front()->left != NULL) dq.push_back(dq.front()->left); if (dq.front()->right != NULL) dq.push_back(dq.front()->right); // Print the current processed element cout << dq.front()->key << "" ""; dq.pop_front(); } // Switch reverse for next traversal reverse = !reverse; } else { // If we are printing right to left // Iterate the deque in reverse order and insert // the children from the front while (n--) { // Insert the child in the front of the // deque Right child first if (dq.back()->right != NULL) dq.push_front(dq.back()->right); if (dq.back()->left != NULL) dq.push_front(dq.back()->left); // Print the current processed element cout << dq.back()->key << "" ""; dq.pop_back(); } // Switch reverse for next traversal reverse = !reverse; } } } // A utility function to create a new node struct Node* newNode(int data) { struct Node* node = new struct Node; node->key = data; node->left = NULL; node->right = NULL; return (node); } int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(7); root->left->right = newNode(6); root->right->left = newNode(5); root->right->right = newNode(4); cout << ""Spiral Order traversal of binary tree is :\n""; spiralPrint(root); return 0; } // This code is contributed by Abhijeet Kumar(abhijeet19403)",linear,linear "// C++ program for the above approach #include using namespace std; // Method to find the maximum for each // and every contiguous subarray of size K. void printKMax(int arr[], int N, int K) { int j, max; for (int i = 0; i <= N - K; i++) { max = arr[i]; for (j = 1; j < K; j++) { if (arr[i + j] > max) max = arr[i + j]; } cout << max << "" ""; } } // Driver's code int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 3; // Function call printKMax(arr, N, K); return 0; } // This code is contributed by rathbhupendra",constant,quadratic "// CPP program for the above approach #include using namespace std; // A Dequeue (Double ended queue) based // method for printing maximum element of // all subarrays of size k void printKMax(int arr[], int N, int K) { // Create a Double Ended Queue, // Qi that will store indexes // of array elements // The queue will store indexes // of useful elements in every // window and it will // maintain decreasing order of // values from front to rear in Qi, i.e., // arr[Qi.front[]] to arr[Qi.rear()] // are sorted in decreasing order std::deque Qi(K); /* Process first k (or first window) elements of array */ int i; for (i = 0; i < K; ++i) { // For every element, the previous // smaller elements are useless so // remove them from Qi while ((!Qi.empty()) && arr[i] >= arr[Qi.back()]) // Remove from rear Qi.pop_back(); // Add new element at rear of queue Qi.push_back(i); } // Process rest of the elements, // i.e., from arr[k] to arr[n-1] for (; i < N; ++i) { // The element at the front of // the queue is the largest element of // previous window, so print it cout << arr[Qi.front()] << "" ""; // Remove the elements which // are out of this window while ((!Qi.empty()) && Qi.front() <= i - K) // Remove from front of queue Qi.pop_front(); // Remove all elements // smaller than the currently // being added element (remove // useless elements) while ((!Qi.empty()) && arr[i] >= arr[Qi.back()]) Qi.pop_back(); // Add current element at the rear of Qi Qi.push_back(i); } // Print the maximum element // of last window cout << arr[Qi.front()]; } // Driver's code int main() { int arr[] = { 12, 1, 78, 90, 57, 89, 56 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 3; // Function call printKMax(arr, N, K); return 0; }",linear,linear "// C++ program for the above approach #include using namespace std; struct node { int data; int maximum; }; // It is a modification in the way of implementation of // queue using two stack void insert(stack& s2, int val) { // inserting the element in s2 node other; other.data = val; if (s2.empty()) other.maximum = val; else { node front = s2.top(); // updating maximum in that stack push it other.maximum = max(val, front.maximum); } s2.push(other); return; } void Delete (stack& s1, stack& s2) { // if s1 is not empty directly pop // else we have to push all element from s2 and thatn // pop from s1 while pushing from s2 to s1 update maximum // variable in s1 if (s1.size()) s1.pop(); else { while (!s2.empty()) { node val = s2.top(); insert(s1, val.data); s2.pop(); } s1.pop(); } } int get_max(stack& s1, stack& s2) { // the maximum of both stack will be the maximum of // overall window int ans = -1; if (s1.size()) ans = max(ans, s1.top().maximum); if (s2.size()) ans = max(ans, s2.top().maximum); return ans; } vector slidingMaximum(int a[], int b, int N) { // s2 for push // s1 for pop vector ans; stack s1, s2; // shifting all value except the last one if first // window for (int i = 0; i < b - 1; i++) insert(s2, a[i]); for (int i = 0; i <= N - b; i++) { // removing the last element of previous window as // window has shift by one if (i - 1 >= 0) Delete (s1, s2); // adding the new element to the window as the // window is shift by one insert(s2, a[i + b - 1]); ans.push_back(get_max(s1, s2)); } return ans; } // Driver's code int main() { int arr[] = { 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 4; // Function call vector ans = slidingMaximum(arr, K, N); for (auto x : ans) cout << x << "" ""; return 0; }",linear,linear "// C++ program to find circular tour for a truck #include using namespace std; // A petrol pump has petrol and distance to next petrol pump class petrolPump { public: int petrol; int distance; }; // The function returns starting point if there is a possible solution, // otherwise returns -1 int printTour(petrolPump arr[], int n) { // Consider first petrol pump as a starting point int start = 0; int end = 1; int curr_petrol = arr[start].petrol - arr[start].distance; /* Run a loop while all petrol pumps are not visited. And we have reached first petrol pump again with 0 or more petrol */ while (end != start || curr_petrol < 0) { // If current amount of petrol in truck becomes less than 0, then // remove the starting petrol pump from tour while (curr_petrol < 0 && start != end) { // Remove starting petrol pump. Change start curr_petrol -= arr[start].petrol - arr[start].distance; start = (start + 1) % n; // If 0 is being considered as start again, then there is no // possible solution if (start == 0) return -1; } // Add a petrol pump to current tour curr_petrol += arr[end].petrol - arr[end].distance; end = (end + 1) % n; } // Return starting point return start; } // Driver code int main() { petrolPump arr[] = {{6, 4}, {3, 6}, {7, 3}}; int n = sizeof(arr)/sizeof(arr[0]); int start = printTour(arr, n); (start == -1)? cout<<""No solution"": cout<<""Start = ""< using namespace std; // A petrol pump has petrol and distance to next petrol pump class petrolPump { public: int petrol; int distance; }; // The function returns starting point if there is a // possible solution, otherwise returns -1 int printTour(petrolPump arr[], int n) { int start; for (int i = 0; i < n; i++) { // Identify the first petrol pump from where we // might get a full circular tour if (arr[i].petrol >= arr[i].distance) { start = i; break; } } // To store the excess petrol int curr_petrol = 0; int i; for (i = start; i < n;) { curr_petrol += (arr[i].petrol - arr[i].distance); // If at any point remaining petrol is less than 0, // it means that we cannot start our journey from // current start if (curr_petrol < 0) { // We move to the next petrol pump i++; // We try to identify the next petrol pump from // where we might get a full circular tour for (; i < n; i++) { if (arr[i].petrol >= arr[i].distance) { start = i; // Reset rem_petrol curr_petrol = 0; break; } } } else { // Move to the next petrolpump if curr_petrol is // >= 0 i++; } } // If remaining petrol is less than 0 while we reach the // first petrol pump, it means no circular tour is // possible if (curr_petrol < 0) { return -1; } for (int j = 0; j < start; j++) { curr_petrol += (arr[j].petrol - arr[j].distance); // If remaining petrol is less than 0 at any point // before we reach initial start, it means no // circular tour is possible if (curr_petrol < 0) { return -1; } } // If we have successfully reached intial_start, it // means can get a circular tour from final_start, hence // return it return start; } // Driver code int main() { petrolPump arr[] = { { 6, 4 }, { 3, 6 }, { 7, 3 } }; int n = sizeof(arr) / sizeof(arr[0]); int start = printTour(arr, n); (start == -1) ? cout << ""No solution"" : cout << ""Start = "" << start; return 0; } // This code is contributed by supratik_mitra",constant,linear "// C++ program to find circular tour for a truck #include using namespace std; // A petrol pump has petrol and distance to next petrol pump class petrolPump { public: int petrol; int distance; }; // The function returns starting point if there is a // possible solution, otherwise returns -1 int printTour(petrolPump p[], int n) { // deficit is used to store the value of the capacity as // soon as the value of capacity becomes negative so as // not to traverse the array twice in order to get the // solution int start = 0, deficit = 0; int capacity = 0; for (int i = 0; i < n; i++) { capacity += p[i].petrol - p[i].distance; if (capacity < 0) { // If this particular step is not done then the // between steps would be redundant start = i + 1; deficit += capacity; capacity = 0; } } return (capacity + deficit >= 0) ? start : -1; } // Driver code int main() { petrolPump arr[] = { { 6, 4 }, { 3, 6 }, { 7, 3 } }; int n = sizeof(arr) / sizeof(arr[0]); int start = printTour(arr, n); (start == -1) ? cout << ""No solution"" : cout << ""Start = "" << start; return 0; } // This code is contributed by aditya kumar",constant,linear "// CPP program to find smallest multiple of a // given number made of digits 0 and 9 only #include using namespace std; // Maximum number of numbers made of 0 and 9 #define MAX_COUNT 10000 // vector to store all numbers that can be formed // using digits 0 and 9 and are less than 10^5 vector vec; /* Preprocessing function to generate all possible numbers formed by 0 and 9 */ void generateNumbersUtil() { // Create an empty queue of strings queue q; // enqueue the first number q.push(""9""); // This loops is like BFS of a tree with 9 as root // 0 as left child and 9 as right child and so on for (int count = MAX_COUNT; count > 0; count--) { string s1 = q.front(); q.pop(); // storing the front of queue in the vector vec.push_back(s1); string s2 = s1; // Append ""0"" to s1 and enqueue it q.push(s1.append(""0"")); // Append ""9"" to s2 and enqueue it. Note that // s2 contains the previous front q.push(s2.append(""9"")); } } // function to find smallest number made up of only // digits 9’s and 0’s, which is a multiple of n. string findSmallestMultiple(int n) { // traverse the vector to find the smallest // multiple of n for (int i = 0; i < vec.size(); i++) // stoi() is used for string to int conversion if (stoi(vec[i])%n == 0) return vec[i]; } // Driver Code int main() { generateNumbersUtil(); int n = 7; cout << findSmallestMultiple(n); return 0; }",np,linear "#include #include using namespace std; // This approach counts the number of nodes from root to the // leaf to calculate the height of the tree. // Defining the structure of a Node. class Node { public: int data; Node* left; Node* right; }; // Helper function to create a newnode. // Input: Data for the newnode. // Return: Address of the newly created node. Node* createNode(int data) { Node* newnode = new Node(); newnode->data = data; newnode->left = NULL; newnode->right = NULL; return newnode; } // Function to calculate the height of given Binary Tree. // Input: Address of the root node of Binary Tree. // Return: Height of Binary Tree as a integer. This includes // the number of nodes from root to the leaf. int calculateHeight(Node* root) { queue nodesInLevel; int height = 0; int nodeCount = 0; // Calculate number of nodes in a level. Node* currentNode; // Pointer to store the address of a // node in the current level. if (root == NULL) { return 0; } nodesInLevel.push(root); while (!nodesInLevel.empty()) { // This while loop runs for every level and // increases the height by 1 in each iteration. If // the queue is empty then it implies that the last // level of tree has been parsed. height++; // Create another while loop which will insert all // the child nodes of the current level in the // queue. nodeCount = nodesInLevel.size(); while (nodeCount--) { currentNode = nodesInLevel.front(); // Check if the current nodes has left child and // insert it in the queue. if (currentNode->left != NULL) { nodesInLevel.push(currentNode->left); } // Check if the current nodes has right child // and insert it in the queue. if (currentNode->right != NULL) { nodesInLevel.push(currentNode->right); } // Once the children of the current node are // inserted. Delete the current node. nodesInLevel.pop(); } } return height; } // Driver Function. int main() { // Creating a binary tree. Node* root = NULL; root = createNode(1); root->left = createNode(2); root->left->left = createNode(4); root->left->right = createNode(5); root->right = createNode(3); cout << ""The height of the binary tree using iterative "" ""method is: "" << calculateHeight(root) << "".""; return 0; }",linear,linear "// C++ program to generate binary numbers from 1 to n #include using namespace std; // This function uses queue data structure to print binary // numbers void generatePrintBinary(int n) { // Create an empty queue of strings queue q; // Enqueue the first binary number q.push(""1""); // This loops is like BFS of a tree with 1 as root // 0 as left child and 1 as right child and so on while (n--) { // print the front of queue string s1 = q.front(); q.pop(); cout << s1 << ""\n""; string s2 = s1; // Store s1 before changing it // Append ""0"" to s1 and enqueue it q.push(s1.append(""0"")); // Append ""1"" to s2 and enqueue it. Note that s2 // contains the previous front q.push(s2.append(""1"")); } } // Driver code int main() { int n = 10; // Function call generatePrintBinary(n); return 0; }",linear,linear "// C++ program to find minimum time required to make all // oranges rotten #include #define R 3 #define C 5 using namespace std; // function to check whether a cell is valid / invalid bool isvalid(int i, int j) { return (i >= 0 && j >= 0 && i < R && j < C); } // structure for storing coordinates of the cell struct ele { int x, y; }; // Function to check whether the cell is delimiter // which is (-1, -1) bool isdelim(ele temp) { return (temp.x == -1 && temp.y == -1); } // Function to check whether there is still a fresh // orange remaining bool checkall(int arr[][C]) { for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (arr[i][j] == 1) return true; return false; } // This function finds if it is possible to rot all oranges // or not. If possible, then it returns minimum time // required to rot all, otherwise returns -1 int rotOranges(int arr[][C]) { // Create a queue of cells queue Q; ele temp; int ans = 0; // Store all the cells having rotten orange in first // time frame for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (arr[i][j] == 2) { temp.x = i; temp.y = j; Q.push(temp); } } } // Separate these rotten oranges from the oranges which // will rotten due the oranges in first time frame using // delimiter which is (-1, -1) temp.x = -1; temp.y = -1; Q.push(temp); // Process the grid while there are rotten oranges in // the Queue while (!Q.empty()) { // This flag is used to determine whether even a // single fresh orange gets rotten due to rotten // oranges in current time frame so we can increase // the count of the required time. bool flag = false; // Process all the rotten oranges in current time // frame. while (!isdelim(Q.front())) { temp = Q.front(); // Check right adjacent cell that if it can be // rotten if (isvalid(temp.x + 1, temp.y) && arr[temp.x + 1][temp.y] == 1) { // if this is the first orange to get // rotten, increase count and set the flag. if (!flag) ans++, flag = true; // Make the orange rotten arr[temp.x + 1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.push(temp); temp.x--; // Move back to current cell } // Check left adjacent cell that if it can be // rotten if (isvalid(temp.x - 1, temp.y) && arr[temp.x - 1][temp.y] == 1) { if (!flag) ans++, flag = true; arr[temp.x - 1][temp.y] = 2; temp.x--; Q.push(temp); // push this cell to Queue temp.x++; } // Check top adjacent cell that if it can be // rotten if (isvalid(temp.x, temp.y + 1) && arr[temp.x][temp.y + 1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y + 1] = 2; temp.y++; Q.push(temp); // Push this cell to Queue temp.y--; } // Check bottom adjacent cell if it can be // rotten if (isvalid(temp.x, temp.y - 1) && arr[temp.x][temp.y - 1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y - 1] = 2; temp.y--; Q.push(temp); // push this cell to Queue } Q.pop(); } // Pop the delimiter Q.pop(); // If oranges were rotten in current frame then // separate the rotten oranges using delimiter for // the next frame for processing. if (!Q.empty()) { temp.x = -1; temp.y = -1; Q.push(temp); } // If Queue was empty then no rotten oranges left to // process so exit } // Return -1 if all arranges could not rot, otherwise // return ans. return (checkall(arr)) ? -1 : ans; } // Driver program int main() { int arr[][C] = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; int ans = rotOranges(arr); if (ans == -1) cout << ""All oranges cannot rotn""; else cout << ""Time required for all oranges to rot => "" << ans << endl; return 0; }",quadratic,quadratic "// C++ program to find sum of all minimum and maximum // elements Of Sub-array Size k. #include using namespace std; // Returns sum of min and max element of all subarrays // of size k int SumOfKsubArray(int arr[] , int n , int k) { int sum = 0; // Initialize result // The queue will store indexes of useful elements // in every window // In deque 'G' we maintain decreasing order of // values from front to rear // In deque 'S' we maintain increasing order of // values from front to rear deque< int > S(k), G(k); // Process first window of size K int i = 0; for (i = 0; i < k; i++) { // Remove all previous greater elements // that are useless. while ( (!S.empty()) && arr[S.back()] >= arr[i]) S.pop_back(); // Remove from rear // Remove all previous smaller that are elements // are useless. while ( (!G.empty()) && arr[G.back()] <= arr[i]) G.pop_back(); // Remove from rear // Add current element at rear of both deque G.push_back(i); S.push_back(i); } // Process rest of the Array elements for ( ; i < n; i++ ) { // Element at the front of the deque 'G' & 'S' // is the largest and smallest // element of previous window respectively sum += arr[S.front()] + arr[G.front()]; // Remove all elements which are out of this // window while ( !S.empty() && S.front() <= i - k) S.pop_front(); while ( !G.empty() && G.front() <= i - k) G.pop_front(); // remove all previous greater element that are // useless while ( (!S.empty()) && arr[S.back()] >= arr[i]) S.pop_back(); // Remove from rear // remove all previous smaller that are elements // are useless while ( (!G.empty()) && arr[G.back()] <= arr[i]) G.pop_back(); // Remove from rear // Add current element at rear of both deque G.push_back(i); S.push_back(i); } // Sum of minimum and maximum element of last window sum += arr[S.front()] + arr[G.front()]; return sum; } // Driver program to test above functions int main() { int arr[] = {2, 5, -1, 7, -3, -1, -2} ; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << SumOfKsubArray(arr, n, k) ; return 0; }",constant,linear "// C++ program to find distance of nearest // cell having 1 in a binary matrix. #include #define N 3 #define M 4 using namespace std; // Print the distance of nearest cell // having 1 for each cell. void printDistance(int mat[N][M]) { int ans[N][M]; // Initialize the answer matrix with INT_MAX. for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) ans[i][j] = INT_MAX; // For each cell for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { // Traversing the whole matrix // to find the minimum distance. for (int k = 0; k < N; k++) for (int l = 0; l < M; l++) { // If cell contain 1, check // for minimum distance. if (mat[k][l] == 1) ans[i][j] = min(ans[i][j], abs(i - k) + abs(j - l)); } } // Printing the answer. for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << ans[i][j] << "" ""; cout << endl; } } // Driver code int main() { int mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 }; // Function call printDistance(mat); return 0; }",quadratic,quadratic "// C++ program to find distance of nearest // cell having 1 in a binary matrix. #include #define MAX 500 #define N 3 #define M 4 using namespace std; // Making a class of graph with bfs function. class graph { private: vector g[MAX]; int n, m; public: graph(int a, int b) { n = a; m = b; } // Function to create graph with N*M nodes // considering each cell as a node and each // boundary as an edge. void createGraph() { int k = 1; // A number to be assigned to a cell for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // If last row, then add edge on right side. if (i == n) { // If not bottom right cell. if (j != m) { g[k].push_back(k + 1); g[k + 1].push_back(k); } } // If last column, then add edge toward // down. else if (j == m) { g[k].push_back(k + m); g[k + m].push_back(k); } // Else makes an edge in all four // directions. else { g[k].push_back(k + 1); g[k + 1].push_back(k); g[k].push_back(k + m); g[k + m].push_back(k); } k++; } } } // BFS function to find minimum distance void bfs(bool visit[], int dist[], queue q) { while (!q.empty()) { int temp = q.front(); q.pop(); for (int i = 0; i < g[temp].size(); i++) { if (visit[g[temp][i]] != 1) { dist[g[temp][i]] = min(dist[g[temp][i]], dist[temp] + 1); q.push(g[temp][i]); visit[g[temp][i]] = 1; } } } } // Printing the solution void print(int dist[]) { for (int i = 1, c = 1; i <= n * m; i++, c++) { cout << dist[i] << "" ""; if (c % m == 0) cout << endl; } } }; // Find minimum distance void findMinDistance(bool mat[N][M]) { // Creating a graph with nodes values assigned // from 1 to N x M and matrix adjacent. graph g1(N, M); g1.createGraph(); // To store minimum distance int dist[MAX]; // To mark each node as visited or not in BFS bool visit[MAX] = { 0 }; // Initialising the value of distance and visit. for (int i = 1; i <= M * N; i++) { dist[i] = INT_MAX; visit[i] = 0; } // Inserting nodes whose value in matrix // is 1 in the queue. int k = 1; queue q; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i][j] == 1) { dist[k] = 0; visit[k] = 1; q.push(k); } k++; } } // Calling for Bfs with given Queue. g1.bfs(visit, dist, q); // Printing the solution. g1.print(dist); } // Driver code int main() { bool mat[N][M] = { 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0 }; // Function call findMinDistance(mat); return 0; }",quadratic,quadratic "// Java program to find distance of nearest // cell having 1 in a binary matrix. import java.util.*; class gfg { static int N = 3; static int M = 4; static int MAX = 500; // Making a class of graph with bfs function. static class graph { ArrayList > g; int n, m; graph(int a, int b) { g = new ArrayList<>(); n = a; m = b; } // Function to create graph with N*M nodes // considering each cell as a node and each // boundary as an edge. void createGraph() { int k = 1; // A number to be assigned to a cell for (int i = 0; i <= MAX; i++) { g.add(new ArrayList<>()); } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // If last row, then add edge on right // side. if (i == n) { // If not bottom right cell. if (j != m) { g.get(k).add(k + 1); g.get(k + 1).add(k); } } // If last column, then add edge toward // down. else if (j == m) { g.get(k).add(k + m); g.get(k + m).add(k); } // Else makes an edge in all four // directions. else { g.get(k).add(k + 1); g.get(k + 1).add(k); g.get(k).add(k + m); g.get(k + m).add(k); } k++; } } } // BFS function to find minimum distance void bfs(boolean visit[], int dist[], Queue q) { while (!q.isEmpty()) { int temp = q.peek(); q.remove(); for (int i = 0; i < g.get(temp).size(); i++) { if (visit[g.get(temp).get(i)] != true) { dist[g.get(temp).get(i)] = Math.min( dist[g.get(temp).get(i)], dist[temp] + 1); q.add(g.get(temp).get(i)); visit[g.get(temp).get(i)] = true; } } } } // Printing the solution void print(int dist[]) { for (int i = 1, c = 1; i <= n * m; i++, c++) { System.out.print(dist[i] + "" ""); if (c % m == 0) System.out.println(); } } }; // Find minimum distance static void findMinDistance(boolean mat[][]) { // Creating a graph with nodes values assigned // from 1 to N x M and matrix adjacent. graph g1 = new graph(N, M); g1.createGraph(); // To store minimum distance int dist[] = new int[MAX]; // To mark each node as visited or not in BFS boolean visit[] = new boolean[MAX]; // Initialising the value of distance and visit. for (int i = 1; i <= M * N; i++) { dist[i] = Integer.MAX_VALUE; visit[i] = false; } // Inserting nodes whose value in matrix // is 1 in the queue. int k = 1; Queue q = new ArrayDeque<>(); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (mat[i][j]) { dist[k] = 0; visit[k] = true; q.add(k); } k++; } } // Calling for Bfs with given Queue. g1.bfs(visit, dist, q); // Printing the solution. g1.print(dist); } // Driver code public static void main(String[] args) { int matrix[][] = { { 0, 0, 0, 1 }, { 0, 0, 1, 1 }, { 0, 1, 1, 0 } }; boolean[][] mat = new boolean[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (matrix[i][j] == 1) mat[i][j] = true; } } // Function call findMinDistance(mat); } } // This code is contributed by karandeep1234",quadratic,quadratic "// C++ program to do level order traversal line by // line #include using namespace std; struct Node { int data; Node *left, *right; }; // Prints level order traversal line by line // using two queues. void levelOrder(Node *root) { queue q1, q2; if (root == NULL) return; // Pushing first level node into first queue q1.push(root); // Executing loop till both the queues // become empty while (!q1.empty() || !q2.empty()) { while (!q1.empty()) { // Pushing left child of current node in // first queue into second queue if (q1.front()->left != NULL) q2.push(q1.front()->left); // pushing right child of current node // in first queue into second queue if (q1.front()->right != NULL) q2.push(q1.front()->right); cout << q1.front()->data << "" ""; q1.pop(); } cout << ""\n""; while (!q2.empty()) { // pushing left child of current node // in second queue into first queue if (q2.front()->left != NULL) q1.push(q2.front()->left); // pushing right child of current // node in second queue into first queue if (q2.front()->right != NULL) q1.push(q2.front()->right); cout << q2.front()->data << "" ""; q2.pop(); } cout << ""\n""; } } // Utility function to create a new tree node Node* newNode(int data) { Node *temp = new Node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } // Driver program to test above functions int main() { Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); levelOrder(root); return 0; }",linear,linear "// C++ program to find min sum of squares // of characters after k removals #include using namespace std; const int MAX_CHAR = 26; // Main Function to calculate min sum of // squares of characters after k removals int minStringValue(string str, int k) { int l = str.length(); // find length of string // if K is greater than length of string // so reduced string will become 0 if (k >= l) return 0; // Else find Frequency of each character and // store in an array int frequency[MAX_CHAR] = { 0 }; for (int i = 0; i < l; i++) frequency[str[i] - 'a']++; // Push each char frequency into a priority_queue priority_queue q; for (int i = 0; i < MAX_CHAR; i++) q.push(frequency[i]); // Removal of K characters while (k--) { // Get top element in priority_queue, // remove it. Decrement by 1 and again // push into priority_queue int temp = q.top(); q.pop(); temp = temp - 1; q.push(temp); } // After removal of K characters find sum // of squares of string Value int result = 0; // Initialize result while (!q.empty()) { int temp = q.top(); result += temp * temp; q.pop(); } return result; } // Driver Code int main() { string str = ""abbccc""; // Input 1 int k = 2; cout << minStringValue(str, k) << endl; str = ""aaab""; // Input 2 k = 2; cout << minStringValue(str, k); return 0; }",constant,nlogn "// C++ program to find min sum of squares // of characters after k removals #include using namespace std; const int MAX_CHAR = 26; // Main Function to calculate min sum of // squares of characters after k removals int minStringValue(string str, int k) { int alphabetCount[MAX_CHAR]= {0}; // Here the array stored frequency the number of // occurrences in string m[frequency]=number of alphabets // with frequency i.e, in our example abbccc m[1]=1(1 // a's occur),m[2]=1(2 b's occur),m[3]=1(3 c'soccur) int m[str.length()] = { 0 }; for (int i = 0; i < str.length(); i++) { alphabetCount[str[i] - 'a']++; } // Store the maximum int maximum = 0; for (int i = 0; i < MAX_CHAR; i++) { m[alphabetCount[i]]++; maximum = max(maximum, alphabetCount[i]); } while (k > 0) { int z = m[maximum]; if (z <= k) { // Remove one occurrence of alphabet from each // with frequency as maximum. // So we will have k-z more remove operations to // perform as z is number of characters and we // perform one removal from each of the alphabet // with that frequency. k = k - z; // As we removed one occurrence from each the // alphabets will no longer have the frequency // of maximum their frequency will be decreased // by one so add these number of alphabets to // group with frequency one less than maximum. // Remove them from maximum count. m[maximum] = 0; // Add those to frequency one less. m[maximum - 1] += z; // new maximum will be one less. maximum--; } else { // if all the elements of that frequency cannot // be removed we should partially remove them. m[maximum] -= k; maximum--; m[maximum] += k; k = 0; } } int ans = 0; for (int i = 0; i < str.length(); i++) { //(square of frequency)*(number of // characters corresponding to that frequency) ans += (i * i) * m[i]; } return ans; } // Driver Code int main() { string str = ""abbccc""; // Input 1 int k = 2; cout << minStringValue(str, k) << endl; str = ""aaab""; // Input 2 k = 2; cout << minStringValue(str, k); return 0; } // This code is contributed by Kasina Dheeraj.",linear,linear "// C++ program for a Queue based approach // to find first non-repeating character #include using namespace std; const int MAX_CHAR = 26; // function to find first non repeating // character of sa stream void firstnonrepeating(char str[]) { queue q; int charCount[MAX_CHAR] = { 0 }; // traverse whole stream for (int i = 0; str[i]; i++) { // push each character in queue q.push(str[i]); // increment the frequency count charCount[str[i] - 'a']++; // check for the non repeating character while (!q.empty()) { if (charCount[q.front() - 'a'] > 1) q.pop(); else { cout << q.front() << "" ""; break; } } if (q.empty()) cout << -1 << "" ""; } cout << endl; } // Driver function int main() { char str[] = ""aabc""; firstnonrepeating(str); return 0; }",linear,linear "// C++ code for the above approach #include using namespace std; // A binary tree node has data, pointer to // left child and a pointer to right child struct Node { int val; struct Node *left, *right; }; // Initialising a map with key as levels of the tree map > mp; void avg(Node* r, int l) { // If the node is NULL if (r == NULL) return; // Add the current value to the sum of this level mp[l].first += r->val; // Increase the number of elements in the current level mp[l].second++; // Traverse left avg(r->left, l + 1); // Traverse right avg(r->right, l + 1); } void averageOfLevels(Node* root) { avg(root, 0); // Travaersing for levels in map for (auto i : mp) { // Printing average of all levels cout << (i.second.first / i.second.second) << ' '; } } // Function to create a new node Node* newNode(int data) { Node* temp = new Node; temp->val = data; temp->left = temp->right = NULL; return temp; } int main() { /* Let us construct a Binary Tree 4 / \ 2 9 / \ \ 3 5 7 */ Node* root = NULL; root = newNode(4); root->left = newNode(2); root->right = newNode(9); root->left->left = newNode(3); root->left->right = newNode(8); root->right->right = newNode(7); // Function Call averageOfLevels(root); } // This Code has been contributed by Alok Khansali",logn,nlogn "// Given two arrays, check if one array is // stack permutation of other. #include using namespace std; // function to check if input queue is // permutable to output queue bool checkStackPermutation(int ip[], int op[], int n) { // Input queue queue input; for (int i=0;i output; for (int i=0;i tempStack; while (!input.empty()) { int ele = input.front(); input.pop(); if (ele == output.front()) { output.pop(); while (!tempStack.empty()) { if (tempStack.top() == output.front()) { tempStack.pop(); output.pop(); } else break; } } else tempStack.push(ele); } // If after processing, both input queue and // stack are empty then the input queue is // permutable otherwise not. return (input.empty()&&tempStack.empty()); } // Driver program to test above function int main() { // Input Queue int input[] = {1, 2, 3}; // Output Queue int output[] = {2, 1, 3}; int n = 3; if (checkStackPermutation(input, output, n)) cout << ""Yes""; else cout << ""Not Possible""; return 0; }",linear,linear "// Given two arrays, check if one array is // stack permutation of other. #include using namespace std; // function to check if input array is // permutable to output array bool checkStackPermutation(int ip[], int op[], int n) { // we will be pushing elements from input array to stack uptill top of our stack // matches with first element of output array stacks; // will maintain a variable j to iterate on output array int j=0; // will iterate one by one in input array for(int i=0;i using namespace std; typedef pair pi; // User defined stack class class Stack{ // cnt is used to keep track of the number of //elements in the stack and also serves as key //for the priority queue. int cnt; priority_queue > pq; public: Stack():cnt(0){} void push(int n); void pop(); int top(); bool isEmpty(); }; // push function increases cnt by 1 and // inserts this cnt with the original value. void Stack::push(int n){ cnt++; pq.push(pi(cnt, n)); } // pops element and reduces count. void Stack::pop(){ if(pq.empty()){ cout<<""Nothing to pop!!!"";} cnt--; pq.pop(); } // returns the top element in the stack using // cnt as key to determine top(highest priority), // default comparator for pairs works fine in this case int Stack::top(){ pi temp=pq.top(); return temp.second; } // return true if stack is empty bool Stack::isEmpty(){ return pq.empty(); } // Driver code int main() { Stack* s=new Stack(); s->push(1); s->push(2); s->push(3); while(!s->isEmpty()){ cout<top()<pop(); } }",linear,logn "// program to demonstrate customized data structure // which supports functions in O(1) #include #include using namespace std; const int MAXX = 1000; // class stack class stack { int minn; int size; public: stack() { minn = 99999; size = -1; } vector > arr; int GetLastElement(); int RemoveLastElement(); int AddElement(int element); int GetMin(); }; // utility function for adding a new element int stack::AddElement(int element) { if (size > MAXX) { cout << ""stack overflow, max size reached!\n""; return 0; } if (element < minn) minn = element; arr.push_back(make_pair(element, minn)); size++; return 1; } // utility function for returning last element of stack int stack::GetLastElement() { if (size == -1) { cout << ""No elements in stack\n""; return 0; } return arr[size].first; } // utility function for removing last element successfully; int stack::RemoveLastElement() { if (size == -1) { cout << ""stack empty!!!\n""; return 0; } // updating minimum element if (size > 0 && arr[size - 1].second > arr[size].second) { minn = arr[size - 1].second; } arr.pop_back(); size -= 1; return 1; } // utility function for returning min element till now; int stack::GetMin() { if (size == -1) { cout << ""stack empty!!\n""; return 0; } return arr[size].second; } // Driver code int main() { stack s; int success = s.AddElement(5); if (success == 1) cout << ""5 inserted successfully\n""; success = s.AddElement(7); if (success == 1) cout << ""7 inserted successfully\n""; success = s.AddElement(3); if (success == 1) cout << ""3 inserted successfully\n""; int min1 = s.GetMin(); cout << ""min element :: "" << min1 << endl; success = s.RemoveLastElement(); if (success == 1) cout << ""removed successfully\n""; success = s.AddElement(2); if (success == 1) cout << ""2 inserted successfully\n""; success = s.AddElement(9); if (success == 1) cout << ""9 inserted successfully\n""; int last = s.GetLastElement(); cout << ""Last element :: "" << last << endl; success = s.AddElement(0); if (success == 1) cout << ""0 inserted successfully\n""; min1 = s.GetMin(); cout << ""min element :: "" << min1 << endl; success = s.RemoveLastElement(); if (success == 1) cout << ""removed successfully\n""; success = s.AddElement(11); if (success == 1) cout << ""11 inserted successfully\n""; min1 = s.GetMin(); cout << ""min element :: "" << min1 << endl; return 0; }",linear,constant "// C++ Program to implement stack and queue using Deque #include using namespace std; // structure for a node of deque struct DQueNode { int value; DQueNode* next; DQueNode* prev; }; // Implementation of deque class class Deque { private: // pointers to head and tail of deque DQueNode* head; DQueNode* tail; public: // constructor Deque() { head = tail = NULL; } // if list is empty bool isEmpty() { if (head == NULL) return true; return false; } // count the number of nodes in list int size() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; int len = 0; while (temp != NULL) { len++; temp = temp->next; } return len; } return 0; } // insert at the first position void insert_first(int element) { // allocating node of DQueNode type DQueNode* temp = new DQueNode[sizeof(DQueNode)]; temp->value = element; // if the element is first element if (head == NULL) { head = tail = temp; temp->next = temp->prev = NULL; } else { head->prev = temp; temp->next = head; temp->prev = NULL; head = temp; } } // insert at last position of deque void insert_last(int element) { // allocating node of DQueNode type DQueNode* temp = new DQueNode[sizeof(DQueNode)]; temp->value = element; // if element is the first element if (head == NULL) { head = tail = temp; temp->next = temp->prev = NULL; } else { tail->next = temp; temp->next = NULL; temp->prev = tail; tail = temp; } } // remove element at the first position void remove_first() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; head = head->next; if(head) head->prev = NULL; delete temp; if(head == NULL) tail = NULL; return; } cout << ""List is Empty"" << endl; } // remove element at the last position void remove_last() { // if list is not empty if (!isEmpty()) { DQueNode* temp = tail; tail = tail->prev; if(tail) tail->next = NULL; delete temp; if(tail == NULL) head = NULL; return; } cout << ""List is Empty"" << endl; } // displays the elements in deque void display() { // if list is not empty if (!isEmpty()) { DQueNode* temp = head; while (temp != NULL) { cout << temp->value << "" ""; temp = temp->next; } cout << endl; return; } cout << ""List is Empty"" << endl; } }; // Class to implement stack using Deque class Stack : public Deque { public: // push to push element at top of stack // using insert at last function of deque void push(int element) { insert_last(element); } // pop to remove element at top of stack // using remove at last function of deque void pop() { remove_last(); } }; // class to implement queue using deque class Queue : public Deque { public: // enqueue to insert element at last // using insert at last function of deque void enqueue(int element) { insert_last(element); } // dequeue to remove element from first // using remove at first function of deque void dequeue() { remove_first(); } }; // Driver Code int main() { // object of Stack Stack stk; // push 7 and 8 at top of stack stk.push(7); stk.push(8); cout << ""Stack: ""; stk.display(); // pop an element stk.pop(); cout << ""Stack: ""; stk.display(); // object of Queue Queue que; // insert 12 and 13 in queue que.enqueue(12); que.enqueue(13); cout << ""Queue: ""; que.display(); // delete an element from queue que.dequeue(); cout << ""Queue: ""; que.display(); cout << ""Size of Stack is "" << stk.size() << endl; cout << ""Size of Queue is "" << que.size() << endl; return 0; }",linear,linear "// C++ Program to convert prefix to Infix #include #include using namespace std; // function to check if character is operator or not bool isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': case '^': case '%': return true; } return false; } // Convert prefix to Infix expression string preToInfix(string pre_exp) { stack s; // length of expression int length = pre_exp.size(); // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = ""("" + op1 + pre_exp[i] + op2 + "")""; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, pre_exp[i])); } } // Stack now contains the Infix expression return s.top(); } // Driver Code int main() { string pre_exp = ""*-A/BC-/AKL""; cout << ""Infix : "" << preToInfix(pre_exp); return 0; }",linear,linear "// CPP Program to convert postfix to prefix #include using namespace std; // function to check if character is operator or not bool isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert postfix to Prefix expression string postToPre(string post_exp) { stack s; // length of expression int length = post_exp.size(); // reading from right to left for (int i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = post_exp[i] + op2 + op1; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, post_exp[i])); } } string ans = """"; while (!s.empty()) { ans += s.top(); s.pop(); } return ans; } // Driver Code int main() { string post_exp = ""ABC/-AK/L-*""; // Function call cout << ""Prefix : "" << postToPre(post_exp); return 0; }",linear,linear "// C++ linear time solution for stock span problem #include #include using namespace std; // A stack based efficient method to calculate // stock span values void calculateSpan(int price[], int n, int S[]) { // Create a stack and push index of first // element to it stack st; st.push(0); // Span value of first element is always 1 S[0] = 1; // Calculate span values for rest of the elements for (int i = 1; i < n; i++) { // Pop elements from stack while stack is not // empty and top of stack is smaller than // price[i] while (!st.empty() && price[st.top()] <= price[i]) st.pop(); // If stack becomes empty, then price[i] is // greater than all elements on left of it, // i.e., price[0], price[1], ..price[i-1]. Else // price[i] is greater than elements after // top of stack S[i] = (st.empty()) ? (i + 1) : (i - st.top()); // Push this element to stack st.push(i); } } // A utility function to print elements of array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << "" ""; } // Driver program to test above function int main() { int price[] = { 10, 4, 5, 90, 120, 80 }; int n = sizeof(price) / sizeof(price[0]); int S[n]; // Fill the span values in array S[] calculateSpan(price, n, S); // print the calculated span values printArray(S, n); return 0; }",linear,linear "// C++ program for brute force method // to calculate stock span values #include using namespace std; vector calculateSpan(int arr[], int n) { // Your code here stack s; vector ans; for(int i=0;i arr) { for (int i = 0; i < arr.size(); i++) cout << arr[i] << "" ""; } // Driver code int main() { int price[] = { 10, 4, 5, 90, 120, 80 }; int n = sizeof(price) / sizeof(price[0]); int S[n]; vector arr = calculateSpan(price, n); printArray(arr); return 0; } // This is code is contributed by Arpit Jain",linear,linear "// C++ program to check for balanced brackets. #include using namespace std; // Function to check if brackets are balanced bool areBracketsBalanced(string expr) { // Declare a stack to hold the previous brackets. stack temp; for (int i = 0; i < expr.length(); i++) { if (temp.empty()) { // If the stack is empty // just push the current bracket temp.push(expr[i]); } else if ((temp.top() == '(' && expr[i] == ')') || (temp.top() == '{' && expr[i] == '}') || (temp.top() == '[' && expr[i] == ']')) { // If we found any complete pair of bracket // then pop temp.pop(); } else { temp.push(expr[i]); } } if (temp.empty()) { // If stack is empty return true return true; } return false; } // Driver code int main() { string expr = ""{()}[]""; // Function call if (areBracketsBalanced(expr)) cout << ""Balanced""; else cout << ""Not Balanced""; return 0; }",linear,linear "// C++ program of Next Greater Frequency Element #include #include #include using namespace std; /*NFG function to find the next greater frequency element for each element in the array*/ void NFG(int a[], int n, int freq[]) { // stack data structure to store the position // of array element stack s; s.push(0); // res to store the value of next greater // frequency element for each element int res[n] = { 0 }; for (int i = 1; i < n; i++) { /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ if (freq[a[s.top()]] > freq[a[i]]) s.push(i); else { /*If the frequency of the element which is pointed by the top of stack is less than frequency of the current element, then pop the stack and continuing popping until the above condition is true while the stack is not empty*/ while ( !s.empty() && freq[a[s.top()]] < freq[a[i]]) { res[s.top()] = a[i]; s.pop(); } // now push the current element s.push(i); } } while (!s.empty()) { res[s.top()] = -1; s.pop(); } for (int i = 0; i < n; i++) { // Print the res list containing next // greater frequency element cout << res[i] << "" ""; } } // Driver code int main() { int a[] = { 1, 1, 2, 3, 4, 2, 1 }; int len = 7; int max = INT16_MIN; for (int i = 0; i < len; i++) { // Getting the max element of the array if (a[i] > max) { max = a[i]; } } int freq[max + 1] = { 0 }; // Calculating frequency of each element for (int i = 0; i < len; i++) { freq[a[i]]++; } // Function call NFG(a, len, freq); return 0; }",linear,linear "// C++ program of Next Greater Frequency Element #include using namespace std; stack> mystack; map mymap; /*NFG function to find the next greater frequency element for each element and for placing it in the resultant array */ void NGF(int arr[], int res[], int n) { // Initially store the frequencies of all elements // in a hashmap for(int i = 0; i < n; i++) { mymap[arr[i]] += 1; } // Get the frequency of the last element int curr_freq = mymap[arr[n-1]]; // push it to the stack mystack.push({arr[n-1], curr_freq}); // place -1 as next greater freq for the last // element as it does not have next greater. res[n-1] = -1; // iterate through array in reverse order for(int i = n-2;i>=0;i--) { curr_freq = mymap[arr[i]]; /* If the frequency of the element which is pointed by the top of stack is greater than frequency of the current element then push the current position i in stack*/ while(mystack.size() > 0 && curr_freq >= mystack.top().second) mystack.pop(); // If the stack is empty, place -1. If it is not empty // then we will have next higher freq element at the top of the stack. res[i] = (mystack.size() == 0) ? -1 : mystack.top().first; // push the element at current position mystack.push({arr[i], mymap[arr[i]]}); } } int main() { int arr[] = {1, 1, 1, 2, 2, 2, 2, 11, 3, 3}; int n = sizeof(arr) / sizeof(arr[0]); int res[n]; NGF(arr, res, n); cout << ""[""; for(int i = 0; i < n - 1; i++) { cout << res[i] << "", ""; } cout << res[n - 1] << ""]""; return 0; } // This code is contributed by divyeshrabadiya07.",linear,linear "// C++ code for the above approach #include using namespace std; // Function to find number of next // greater elements on the right of // a given element int nextGreaterElements(vector& a, int index) { int count = 0, N = a.size(); for (int i = index + 1; i < N; i++) if (a[i] > a[index]) count++; return count; } // Driver's code int main() { vector a = { 3, 4, 2, 7, 5, 8, 10, 6 }; int Q = 2; vector queries = { 0, 5 }; for (int i = 0; i < Q; i++) // Function call cout << nextGreaterElements(a, queries[i]) << "" ""; return 0; }",constant,linear "// C++ program to find celebrity #include #include using namespace std; // Max # of persons in the party #define N 8 // Person with 2 is celebrity bool MATRIX[N][N] = { { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 } }; bool knows(int a, int b) { return MATRIX[a][b]; } // Returns -1 if celebrity // is not present. If present, // returns id (value from 0 to n-1). int findCelebrity(int n) { // the graph needs not be constructed // as the edges can be found by // using knows function // degree array; int indegree[n] = { 0 }, outdegree[n] = { 0 }; // query for all edges for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int x = knows(i, j); // set the degrees outdegree[i] += x; indegree[j] += x; } } // find a person with indegree n-1 // and out degree 0 for (int i = 0; i < n; i++) if (indegree[i] == n - 1 && outdegree[i] == 0) return i; return -1; } // Driver code int main() { int n = 4; int id = findCelebrity(n); id == -1 ? cout << ""No celebrity"" : cout << ""Celebrity ID "" << id; return 0; }",linear,quadratic "// C++ program to find celebrity #include #include using namespace std; // Max # of persons in the party #define N 8 // Person with 2 is celebrity bool MATRIX[N][N] = { { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 } }; bool knows(int a, int b) { return MATRIX[a][b]; } // Returns -1 if a 'potential celebrity' // is not present. If present, // returns id (value from 0 to n-1). int findPotentialCelebrity(int n) { // base case - when n reaches 0 , returns -1 // since n represents the number of people, // 0 people implies no celebrity(= -1) if (n == 0) return -1; // find the celebrity with n-1 // persons int id = findPotentialCelebrity(n - 1); // if there are no celebrities if (id == -1) return n - 1; // if the id knows the nth person // then the id cannot be a celebrity, but nth person // could be one else if (knows(id, n - 1)) { return n - 1; } // if the nth person knows the id, // then the nth person cannot be a celebrity and the id // could be one else if (knows(n - 1, id)) { return id; } // if there is no celebrity return -1; } // Returns -1 if celebrity // is not present. If present, // returns id (value from 0 to n-1). // a wrapper over findCelebrity int Celebrity(int n) { // find the celebrity int id = findPotentialCelebrity(n); // check if the celebrity found // is really the celebrity if (id == -1) return id; else { int c1 = 0, c2 = 0; // check the id is really the // celebrity for (int i = 0; i < n; i++) if (i != id) { c1 += knows(id, i); c2 += knows(i, id); } // if the person is known to // everyone. if (c1 == 0 && c2 == n - 1) return id; return -1; } } // Driver code int main() { int n = 4; int id = Celebrity(n); id == -1 ? cout << ""No celebrity"" : cout << ""Celebrity ID "" << id; return 0; }",constant,linear "// C++ program to find celebrity #include #include using namespace std; // Max # of persons in the party #define N 8 // Person with 2 is celebrity bool MATRIX[N][N] = { { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 } }; bool knows(int a, int b) { return MATRIX[a][b]; } // Returns -1 if celebrity // is not present. If present, // returns id (value from 0 to n-1). int findCelebrity(int n) { stack s; // Celebrity int C; // Push everybody to stack for (int i = 0; i < n; i++) s.push(i); // Extract top 2 // Find a potential celebrity while (s.size() > 1) { int A = s.top(); s.pop(); int B = s.top(); s.pop(); if (knows(A, B)) { s.push(B); } else { s.push(A); } } // Potential candidate? C = s.top(); s.pop(); // Check if C is actually // a celebrity or not for (int i = 0; i < n; i++) { // If any person doesn't // know 'C' or 'C' doesn't // know any person, return -1 if ((i != C) && (knows(C, i) || !knows(i, C))) return -1; } return C; } // Driver code int main() { int n = 4; int id = findCelebrity(n); id == -1 ? cout << ""No celebrity"" : cout << ""Celebrity ID "" << id; return 0; }",linear,linear "#include using namespace std; class Solution { public: // Function to find if there is a celebrity in the party // or not. int celebrity(int M[4][4], int n) { // r=row number int r = 0; for (int i = 1; i < n; i++) { // checking if r th person knows i th person if (M[r][i] == 1) { M[r][r] = 1; r = i; } else { M[i][i] = 1; } } for (int i = 0; i < n; i++) { // checking if i th person can be a celebrity or // not if (M[i][i] == 0) { int flag = 0; // iterating in the i th column to check // whether everyone knows i th person or not for (int j = 0; j < n; j++) { // checking if M[j][i] is not a diagonal // element and if j th person knows i th // person if (j != i && M[j][i] == 0) { flag = 1; break; } } if (flag == 0) return i; } } return -1; } }; int main() { int M[4][4] = { { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 } }; Solution ob; int a = ob.celebrity(M, 4); if (a == -1) { cout << ""No Celebrity"" << endl; } else { cout << ""Celebrity ID "" << a << endl; } } // Contributed by Yash Goyal",constant,linear "// C++ program to find celebrity // in the given Matrix of people #include using namespace std; #define N 4 int celebrity(int M[N][N], int n) { // This function returns the celebrity // index 0-based (if any) int i = 0, j = n - 1; while (i < j) { if (M[j][i] == 1) // j knows i j--; else // j doesnt know i so i cant be celebrity i++; } // i points to our celebrity candidate int candidate = i; // Now, all that is left is to check that whether // the candidate is actually a celebrity i.e: he is // known by everyone but he knows no one for (i = 0; i < n; i++) { if (i != candidate) { if (M[i][candidate] == 0 || M[candidate][i] == 1) return -1; } } // if we reach here this means that the candidate // is really a celebrity return candidate; } int main() { int M[N][N] = { { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 } }; int celebIdx = celebrity(M, 4); if (celebIdx == -1) cout << (""No Celebrity""); else { cout << ""Celebrity ID "" << celebIdx; } return 0; } // This code contributed by gauravrajput1",constant,linear "// CPP program to evaluate a given // expression where tokens are // separated by space. #include using namespace std; // Function to find precedence of // operators. int precedence(char op){ if(op == '+'||op == '-') return 1; if(op == '*'||op == '/') return 2; return 0; } // Function to perform arithmetic operations. int applyOp(int a, int b, char op){ switch(op){ case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } } // Function that returns value of // expression after evaluation. int evaluate(string tokens){ int i; // stack to store integer values. stack values; // stack to store operators. stack ops; for(i = 0; i < tokens.length(); i++){ // Current token is a whitespace, // skip it. if(tokens[i] == ' ') continue; // Current token is an opening // brace, push it to 'ops' else if(tokens[i] == '('){ ops.push(tokens[i]); } // Current token is a number, push // it to stack for numbers. else if(isdigit(tokens[i])){ int val = 0; // There may be more than one // digits in number. while(i < tokens.length() && isdigit(tokens[i])) { val = (val*10) + (tokens[i]-'0'); i++; } values.push(val); // right now the i points to // the character next to the digit, // since the for loop also increases // the i, we would skip one // token position; we need to // decrease the value of i by 1 to // correct the offset. i--; } // Closing brace encountered, solve // entire brace. else if(tokens[i] == ')') { while(!ops.empty() && ops.top() != '(') { int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // pop opening brace. if(!ops.empty()) ops.pop(); } // Current token is an operator. else { // While top of 'ops' has same or greater // precedence to current token, which // is an operator. Apply operator on top // of 'ops' to top two elements in values stack. while(!ops.empty() && precedence(ops.top()) >= precedence(tokens[i])){ int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // Push current token to 'ops'. ops.push(tokens[i]); } } // Entire expression has been parsed at this // point, apply remaining ops to remaining // values. while(!ops.empty()){ int val2 = values.top(); values.pop(); int val1 = values.top(); values.pop(); char op = ops.top(); ops.pop(); values.push(applyOp(val1, val2, op)); } // Top of 'values' contains result, return it. return values.top(); } int main() { cout << evaluate(""10 + 2 * 6"") << ""\n""; cout << evaluate(""100 * 2 + 12"") << ""\n""; cout << evaluate(""100 * ( 2 + 12 )"") << ""\n""; cout << evaluate(""100 * ( 2 + 12 ) / 14""); return 0; } // This code is contributed by Nikhil jindal.",linear,linear "// C++ program to evaluate value of a postfix expression #include #include using namespace std; // Stack type struct Stack { int top; unsigned capacity; int* array; }; // Stack Operations struct Stack* createStack( unsigned capacity ) { struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = (int*) malloc(stack->capacity * sizeof(int)); if (!stack->array) return NULL; return stack; } int isEmpty(struct Stack* stack) { return stack->top == -1 ; } char peek(struct Stack* stack) { return stack->array[stack->top]; } char pop(struct Stack* stack) { if (!isEmpty(stack)) return stack->array[stack->top--] ; return '$'; } void push(struct Stack* stack, char op) { stack->array[++stack->top] = op; } // The main function that returns value of a given postfix expression int evaluatePostfix(char* exp) { // Create a stack of capacity equal to expression size struct Stack* stack = createStack(strlen(exp)); int i; // See if stack was created successfully if (!stack) return -1; // Scan all characters one by one for (i = 0; exp[i]; ++i) { // If the scanned character is an operand (number here), // push it to the stack. if (isdigit(exp[i])) push(stack, exp[i] - '0'); // If the scanned character is an operator, pop two // elements from stack apply the operator else { int val1 = pop(stack); int val2 = pop(stack); switch (exp[i]) { case '+': push(stack, val2 + val1); break; case '-': push(stack, val2 - val1); break; case '*': push(stack, val2 * val1); break; case '/': push(stack, val2/val1); break; } } } return pop(stack); } // Driver program to test above functions int main() { char exp[] = ""231*+9-""; cout<<""postfix evaluation: ""<< evaluatePostfix(exp); return 0; }",linear,linear "// C++ program to evaluate value of a postfix // expression having multiple digit operands #include using namespace std; // Stack type class Stack { public: int top; unsigned capacity; int* array; }; // Stack Operations Stack* createStack( unsigned capacity ) { Stack* stack = new Stack(); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = new int[(stack->capacity * sizeof(int))]; if (!stack->array) return NULL; return stack; } int isEmpty(Stack* stack) { return stack->top == -1 ; } int peek(Stack* stack) { return stack->array[stack->top]; } int pop(Stack* stack) { if (!isEmpty(stack)) return stack->array[stack->top--] ; return '$'; } void push(Stack* stack,int op) { stack->array[++stack->top] = op; } // The main function that returns value // of a given postfix expression int evaluatePostfix(char* exp) { // Create a stack of capacity equal to expression size Stack* stack = createStack(strlen(exp)); int i; // See if stack was created successfully if (!stack) return -1; // Scan all characters one by one for (i = 0; exp[i]; ++i) { //if the character is blank space then continue if(exp[i] == ' ')continue; // If the scanned character is an // operand (number here),extract the full number // Push it to the stack. else if (isdigit(exp[i])) { int num=0; //extract full number while(isdigit(exp[i])) { num = num * 10 + (int)(exp[i] - '0'); i++; } i--; //push the element in the stack push(stack,num); } // If the scanned character is an operator, pop two // elements from stack apply the operator else { int val1 = pop(stack); int val2 = pop(stack); switch (exp[i]) { case '+': push(stack, val2 + val1); break; case '-': push(stack, val2 - val1); break; case '*': push(stack, val2 * val1); break; case '/': push(stack, val2/val1); break; } } } return pop(stack); } // Driver code int main() { char exp[] = ""100 200 + 2 / 5 * 7 +""; cout << evaluatePostfix(exp); return 0; } // This code is contributed by rathbhupendra",linear,linear "// C++ code to reverse a // stack using recursion #include using namespace std; // Below is a recursive function // that inserts an element // at the bottom of a stack. void insert_at_bottom(stack& st, int x) { if (st.size() == 0) { st.push(x); } else { // All items are held in Function Call // Stack until we reach end of the stack // When the stack becomes empty, the // st.size() becomes 0, the above if // part is executed and the item is // inserted at the bottom int a = st.top(); st.pop(); insert_at_bottom(st, x); // push allthe items held in // Function Call Stack // once the item is inserted // at the bottom st.push(a); } } // Below is the function that // reverses the given stack using // insert_at_bottom() void reverse(stack& st) { if (st.size() > 0) { // Hold all items in Function // Call Stack until we // reach end of the stack int x = st.top(); st.pop(); reverse(st); // Insert all the items held // in Function Call Stack // one by one from the bottom // to top. Every item is // inserted at the bottom insert_at_bottom(st, x); } return; } // Driver Code int main() { stack st, st2; // push elements into // the stack for (int i = 1; i <= 4; i++) { st.push(i); } st2 = st; cout << ""Original Stack"" << endl; // printing the stack after reversal while (!st2.empty()) { cout << st2.top() << "" ""; st2.pop(); } cout< using namespace std; // Stack is represented using linked list struct stack { int data; struct stack* next; }; // Utility function to initialize stack void initStack(struct stack** s) { *s = NULL; } // Utility function to check if stack is empty int isEmpty(struct stack* s) { if (s == NULL) return 1; return 0; } // Utility function to push an item to stack void push(struct stack** s, int x) { struct stack* p = (struct stack*)malloc(sizeof(*p)); if (p == NULL) { fprintf(stderr, ""Memory allocation failed.\n""); return; } p->data = x; p->next = *s; *s = p; } // Utility function to remove an item from stack int pop(struct stack** s) { int x; struct stack* temp; x = (*s)->data; temp = *s; (*s) = (*s)->next; free(temp); return x; } // Function to find top item int top(struct stack* s) { return (s->data); } // Recursive function to insert an item x in sorted way void sortedInsert(struct stack** s, int x) { // Base case: Either stack is empty or newly inserted // item is greater than top (more than all existing) if (isEmpty(*s) or x > top(*s)) { push(s, x); return; } // If top is greater, remove the top item and recur int temp = pop(s); sortedInsert(s, x); // Put back the top item removed earlier push(s, temp); } // Function to sort stack void sortStack(struct stack** s) { // If stack is not empty if (!isEmpty(*s)) { // Remove the top item int x = pop(s); // Sort remaining stack sortStack(s); // Push the top item back in sorted stack sortedInsert(s, x); } } // Utility function to print contents of stack void printStack(struct stack* s) { while (s) { cout << s->data << "" ""; s = s->next; } cout << ""\n""; } // Driver code int main(void) { struct stack* top; initStack(⊤); push(⊤, 30); push(⊤, -5); push(⊤, 18); push(⊤, 14); push(⊤, -3); cout << ""Stack elements before sorting:\n""; printStack(top); sortStack(⊤); cout << ""\n""; cout << ""Stack elements after sorting:\n""; printStack(top); return 0; } // This code is contributed by SHUBHAMSINGH10",linear,quadratic "// C++ program to sort a stack using an // auxiliary stack. #include using namespace std; // This function return the sorted stack stack sortStack(stack &input) { stack tmpStack; while (!input.empty()) { // pop out the first element int tmp = input.top(); input.pop(); // while temporary stack is not empty and top // of stack is greater than temp while (!tmpStack.empty() && tmpStack.top() > tmp) { // pop from temporary stack and push // it to the input stack input.push(tmpStack.top()); tmpStack.pop(); } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack; } // main function int main() { stack input; input.push(34); input.push(3); input.push(31); input.push(98); input.push(92); input.push(23); // This is the temporary stack stack tmpStack = sortStack(input); cout << ""Sorted numbers are:\n""; while (!tmpStack.empty()) { cout << tmpStack.top()<< "" ""; tmpStack.pop(); } }",linear,quadratic "// C++ program to implement Stack // using linked list so that reverse // can be done with O(1) extra space. #include using namespace std; class StackNode { public: int data; StackNode *next; StackNode(int data) { this->data = data; this->next = NULL; } }; class Stack { StackNode *top; public: // Push and pop operations void push(int data) { if (top == NULL) { top = new StackNode(data); return; } StackNode *s = new StackNode(data); s->next = top; top = s; } StackNode* pop() { StackNode *s = top; top = top->next; return s; } // prints contents of stack void display() { StackNode *s = top; while (s != NULL) { cout << s->data << "" ""; s = s->next; } cout << endl; } // Reverses the stack using simple // linked list reversal logic. void reverse() { StackNode *prev, *cur, *succ; cur = prev = top; cur = cur->next; prev->next = NULL; while (cur != NULL) { succ = cur->next; cur->next = prev; prev = cur; cur = succ; } top = prev; } }; // driver code int main() { Stack *s = new Stack(); s->push(1); s->push(2); s->push(3); s->push(4); cout << ""Original Stack"" << endl;; s->display(); cout << endl; // reverse s->reverse(); cout << ""Reversed Stack"" << endl; s->display(); return 0; } // This code is contributed by Chhavi.",constant,linear "// C++ code to delete middle of a stack // without using additional data structure. #include using namespace std; // Deletes middle of stack of size // n. Curr is current item number void deleteMid_util(stack&s, int sizeOfStack, int current) { //if current pointer is half of the size of stack then we //are accessing the middle element of stack. if(current==sizeOfStack/2) { s.pop(); return; } //storing the top element in a variable and popping it. int x = s.top(); s.pop(); current+=1; //calling the function recursively. deleteMid_util(s,sizeOfStack,current); //pushing the elements (except middle element) back //into stack after recursion calls. s.push(x); } void deleteMid(stack&s, int sizeOfStack) { deleteMid_util(s,sizeOfStack,0); } //Driver function to test above functions int main() { stack st; //push elements into the stack st.push('1'); st.push('2'); st.push('3'); st.push('4'); st.push('5'); st.push('6'); st.push('7'); deleteMid(st, st.size()); // Printing stack after deletion // of middle. while (!st.empty()) { char p=st.top(); st.pop(); cout << p << "" ""; } return 0; }",linear,linear "// C++ code to delete middle of a stack with iterative method #include using namespace std; // Deletes middle of stack of size n. Curr is current item number void deleteMid(stack& st) { int n = st.size(); stack tempSt; int count = 0; // Put first n/2 element of st in tempSt while (count < n / 2) { char c = st.top(); st.pop(); tempSt.push(c); count++; } // Delete middle element st.pop(); // Put all (n/2) element of tempSt in st while (!tempSt.empty()) { st.push(tempSt.top()); tempSt.pop(); } } // Driver Code int main() { stack st; // Push elements into the stack st.push('1'); st.push('2'); st.push('3'); st.push('4'); st.push('5'); st.push('6'); st.push('7'); deleteMid(st); // Printing stack after deletion of middle. while (!st.empty()) { char p = st.top(); st.pop(); cout << p << "" ""; } return 0; }",linear,linear "// C++ program to sort an array using stack #include using namespace std; // This function return the sorted stack stack sortStack(stack input) { stack tmpStack; while (!input.empty()) { // pop out the first element int tmp = input.top(); input.pop(); // while temporary stack is not empty // and top of stack is smaller than temp while (!tmpStack.empty() && tmpStack.top() < tmp) { // pop from temporary stack and // push it to the input stack input.push(tmpStack.top()); tmpStack.pop(); } // push temp in temporary of stack tmpStack.push(tmp); } return tmpStack; } void sortArrayUsingStacks(int arr[], int n) { // Push array elements to stack stack input; for (int i=0; i tmpStack = sortStack(input); // Put stack elements in arrp[] for (int i=0; i using namespace std; // Function for deleting k elements void deleteElements(int arr[], int n, int k) { // Create a stack and push arr[0] stack s; s.push(arr[0]); int count = 0; // traversing a loop from i = 1 to n for (int i=1; i v(m); // Size of vector is m while (!s.empty()) { // push element from stack to vector v v[--m] = s.top(); s.pop(); } // printing result for (auto x : v) cout << x << "" ""; cout << endl; } // Driver code int main() { int n = 5, k = 2; int arr[] = {20, 10, 25, 30, 40}; deleteElements(arr, n, k); return 0; }",linear,quadratic "// C++ program to count number of distinct instance // where second highest number lie // before highest number in all subarrays. #include #define MAXN 100005 using namespace std; // Finding the next greater element of the array. void makeNext(int arr[], int n, int nextBig[]) { stack > s; for (int i = n - 1; i >= 0; i--) { nextBig[i] = i; while (!s.empty() && s.top().first < arr[i]) s.pop(); if (!s.empty()) nextBig[i] = s.top().second; s.push(pair(arr[i], i)); } } // Finding the previous greater element of the array. void makePrev(int arr[], int n, int prevBig[]) { stack > s; for (int i = 0; i < n; i++) { prevBig[i] = -1; while (!s.empty() && s.top().first < arr[i]) s.pop(); if (!s.empty()) prevBig[i] = s.top().second; s.push(pair(arr[i], i)); } } // Wrapper Function int wrapper(int arr[], int n) { int nextBig[MAXN]; int prevBig[MAXN]; int maxi[MAXN]; int ans = 0; // Finding previous largest element makePrev(arr, n, prevBig); // Finding next largest element makeNext(arr, n, nextBig); for (int i = 0; i < n; i++) if (nextBig[i] != i) maxi[nextBig[i] - i] = max(maxi[nextBig[i] - i], i - prevBig[i]); for (int i = 0; i < n; i++) ans += maxi[i]; return ans; } // Driven Program int main() { int arr[] = { 1, 3, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << wrapper(arr, n) << endl; return 0; }",linear,linear "// A C++ program for merging overlapping intervals #include using namespace std; // An interval has start time and end time struct Interval { int start, end; }; // Compares two intervals according to their starting time. // This is needed for sorting the intervals using library // function std::sort(). See http://goo.gl/iGspV bool compareInterval(Interval i1, Interval i2) { return (i1.start < i2.start); } // The main function that takes a set of intervals, merges // overlapping intervals and prints the result void mergeIntervals(Interval arr[], int n) { // Test if the given set has at least one interval if (n <= 0) return; // Create an empty stack of intervals stack s; // sort the intervals in increasing order of start time sort(arr, arr + n, compareInterval); // push the first interval to stack s.push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1; i < n; i++) { // get interval from stack top Interval top = s.top(); // if current interval is not overlapping with stack // top, push it to the stack if (top.end < arr[i].start) s.push(arr[i]); // Otherwise update the ending time of top if ending // of current interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; s.pop(); s.push(top); } } // Print contents of stack cout << ""\n The Merged Intervals are: ""; while (!s.empty()) { Interval t = s.top(); cout << ""["" << t.start << "","" << t.end << ""] ""; s.pop(); } return; } // Driver program int main() { Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); mergeIntervals(arr, n); return 0; }",linear,nlogn "// C++ program to merge overlapping Intervals in // O(n Log n) time and O(1) extra space. #include using namespace std; // An Interval struct Interval { int s, e; }; // Function used in sort bool mycomp(Interval a, Interval b) { return a.s < b.s; } void mergeIntervals(Interval arr[], int n) { // Sort Intervals in increasing order of // start time sort(arr, arr + n, mycomp); int index = 0; // Stores index of last element // in output array (modified arr[]) // Traverse all input Intervals for (int i = 1; i < n; i++) { // If this is not first Interval and overlaps // with the previous one if (arr[index].e >= arr[i].s) { // Merge previous and current Intervals arr[index].e = max(arr[index].e, arr[i].e); } else { index++; arr[index] = arr[i]; } } // Now arr[0..index-1] stores the merged Intervals cout << ""\n The Merged Intervals are: ""; for (int i = 0; i <= index; i++) cout << ""["" << arr[i].s << "", "" << arr[i].e << ""] ""; } // Driver program int main() { Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); mergeIntervals(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,nlogn "// C++ program to find maximum rectangular area in // linear time #include using namespace std; // The main function to find the maximum rectangular // area under given histogram with n bars int getMaxArea(int hist[], int n) { // Create an empty stack. The stack holds indexes // of hist[] array. The bars stored in stack are // always in increasing order of their heights. stack s; int max_area = 0; // Initialize max area int tp; // To store top of stack int area_with_top; // To store area with top bar // as the smallest bar // Run through all bars of given histogram int i = 0; while (i < n) { // If this bar is higher than the bar on top // stack, push it to stack if (s.empty() || hist[s.top()] <= hist[i]) s.push(i++); // If this bar is lower than top of stack, // then calculate area of rectangle with stack // top as the smallest (or minimum height) bar. // 'i' is 'right index' for the top and element // before top in stack is 'left index' else { tp = s.top(); // store the top index s.pop(); // pop the top // Calculate the area with hist[tp] stack // as smallest bar area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1); // update max area, if needed if (max_area < area_with_top) max_area = area_with_top; } } // Now pop the remaining bars from stack and calculate // area with every popped bar as the smallest bar while (s.empty() == false) { tp = s.top(); s.pop(); area_with_top = hist[tp] * (s.empty() ? i : i - s.top() - 1); if (max_area < area_with_top) max_area = area_with_top; } return max_area; } // Driver code int main() { int hist[] = { 6, 2, 5, 4, 5, 1, 6 }; int n = sizeof(hist) / sizeof(hist[0]); // Function call cout << ""Maximum area is "" << getMaxArea(hist, n); return 0; }",linear,linear "// C++ code for the above approach #include using namespace std; // Function to find largest rectangular area possible in a // given histogram. int getMaxArea(int arr[], int n) { // Your code here // we create an empty stack here. stack s; // we push -1 to the stack because for some elements // there will be no previous smaller element in the // array and we can store -1 as the index for previous // smaller. s.push(-1); int area = arr[0]; int i = 0; // We declare left_smaller and right_smaller array of // size n and initialize them with -1 and n as their // default value. left_smaller[i] will store the index // of previous smaller element for ith element of the // array. right_smaller[i] will store the index of next // smaller element for ith element of the array. vector left_smaller(n, -1), right_smaller(n, n); while (i < n) { while (!s.empty() && s.top() != -1 && arr[s.top()] > arr[i]) { // if the current element is smaller than // element with index stored on the top of stack // then, we pop the top element and store the // current element index as the right_smaller // for the popped element. right_smaller[s.top()] = i; s.pop(); } if (i > 0 && arr[i] == arr[i - 1]) { // we use this condition to avoid the // unnecessary loop to find the left_smaller. // since the previous element is same as current // element, the left_smaller will always be the // same for both. left_smaller[i] = left_smaller[i - 1]; } else { // Element with the index stored on the top of // the stack is always smaller than the current // element. Therefore the left_smaller[i] will // always be s.top(). left_smaller[i] = s.top(); } s.push(i); i++; } for (int j = 0; j < n; j++) { // here we find area with every element as the // smallest element in their range and compare it // with the previous area. // in this way we get our max Area form this. area = max(area, arr[j] * (right_smaller[j] - left_smaller[j] - 1)); } return area; } // Driver code int main() { int hist[] = { 6, 2, 5, 4, 5, 1, 6 }; int n = sizeof(hist) / sizeof(hist[0]); // Function call cout << ""maxArea = "" << getMaxArea(hist, n) << endl; return 0; } // This code is Contributed by Arunit Kumar.",linear,linear "// C++ program to reverse a string using stack #include using namespace std; // A structure to represent a stack class Stack { public: int top; unsigned capacity; char* array; }; // function to create a stack of given // capacity. It initializes size of stack as 0 Stack* createStack(unsigned capacity) { Stack* stack = new Stack(); stack->capacity = capacity; stack->top = -1; stack->array = new char[(stack->capacity * sizeof(char))]; return stack; } // Stack is full when top is equal to the last index int isFull(Stack* stack) { return stack->top == stack->capacity - 1; } // Stack is empty when top is equal to -1 int isEmpty(Stack* stack) { return stack->top == -1; } // Function to add an item to stack. // It increases top by 1 void push(Stack* stack, char item) { if (isFull(stack)) return; stack->array[++stack->top] = item; } // Function to remove an item from stack. // It decreases top by 1 char pop(Stack* stack) { if (isEmpty(stack)) return -1; return stack->array[stack->top--]; } // A stack based function to reverse a string void reverse(char str[]) { // Create a stack of capacity // equal to length of string int n = strlen(str); Stack* stack = createStack(n); // Push all characters of string to stack int i; for (i = 0; i < n; i++) push(stack, str[i]); // Pop all characters of string and // put them back to str for (i = 0; i < n; i++) str[i] = pop(stack); } // Driver code int main() { char str[] = ""GeeksQuiz""; reverse(str); cout << ""Reversed string is "" << str; return 0; } // This code is contributed by rathbhupendra",linear,linear "// C++ recursive function to // solve tower of hanoi puzzle #include using namespace std; void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { if (n == 0) { return; } towerOfHanoi(n - 1, from_rod, aux_rod, to_rod); cout << ""Move disk "" << n << "" from rod "" << from_rod << "" to rod "" << to_rod << endl; towerOfHanoi(n - 1, aux_rod, to_rod, from_rod); } // Driver code int main() { int N = 3; // A, B and C are names of rods towerOfHanoi(N, 'A', 'C', 'B'); return 0; } // This is code is contributed by rathbhupendra",linear,linear "// A C++ program to find the maximum depth of nested // parenthesis in a given expression #include using namespace std; int maxDepth(string& s) { int count = 0; stack st; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') st.push(i); // pushing the bracket in the stack else if (s[i] == ')') { if (count < st.size()) count = st.size(); /*keeping track of the parenthesis and storing it before removing it when it gets balanced*/ st.pop(); } } return count; } // Driver program int main() { string s = ""( ((X)) (((Y))) )""; cout << maxDepth(s); // This code is contributed by rakeshsahni return 0; }",constant,linear "// A C++ program to find the maximum depth of nested // parenthesis in a given expression #include using namespace std; // function takes a string and returns the // maximum depth nested parenthesis int maxDepth(string S) { int current_max = 0; // current count int max = 0; // overall maximum count int n = S.length(); // Traverse the input string for (int i = 0; i < n; i++) { if (S[i] == '(') { current_max++; // update max if required if (current_max > max) max = current_max; } else if (S[i] == ')') { if (current_max > 0) current_max--; else return -1; } } // finally check for unbalanced string if (current_max != 0) return -1; return max; } // Driver program int main() { string s = ""( ((X)) (((Y))) )""; cout << maxDepth(s); return 0; }",constant,linear "// A naive method to find maximum of // minimum of all windows of different // sizes #include using namespace std; void printMaxOfMin(int arr[], int n) { // Consider all windows of different // sizes starting from size 1 for (int k = 1; k <= n; k++) { // Initialize max of min for // current window size k int maxOfMin = INT_MIN; // Traverse through all windows // of current size k for (int i = 0; i <= n - k; i++) { // Find minimum of current window int min = arr[i]; for (int j = 1; j < k; j++) { if (arr[i + j] < min) min = arr[i + j]; } // Update maxOfMin if required if (min > maxOfMin) maxOfMin = min; } // Print max of min for current // window size cout << maxOfMin << "" ""; } } // Driver program int main() { int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; int n = sizeof(arr) / sizeof(arr[0]); printMaxOfMin(arr, n); return 0; }",constant,cubic "// An efficient C++ program to find // maximum of all minimums of // windows of different sizes #include #include using namespace std; void printMaxOfMin(int arr[], int n) { // Used to find previous and next smaller stack s; // Arrays to store previous and next smaller int left[n + 1]; int right[n + 1]; // Initialize elements of left[] and right[] for (int i = 0; i < n; i++) { left[i] = -1; right[i] = n; } // Fill elements of left[] using logic discussed on // https://www.geeksforgeeks.org/next-greater-element/ for (int i = 0; i < n; i++) { while (!s.empty() && arr[s.top()] >= arr[i]) s.pop(); if (!s.empty()) left[i] = s.top(); s.push(i); } // Empty the stack as stack is // going to be used for right[] while (!s.empty()) s.pop(); // Fill elements of right[] using same logic for (int i = n - 1; i >= 0; i--) { while (!s.empty() && arr[s.top()] >= arr[i]) s.pop(); if (!s.empty()) right[i] = s.top(); s.push(i); } // Create and initialize answer array int ans[n + 1]; for (int i = 0; i <= n; i++) ans[i] = 0; // Fill answer array by comparing minimums of all // lengths computed using left[] and right[] for (int i = 0; i < n; i++) { // length of the interval int len = right[i] - left[i] - 1; // arr[i] is a possible answer for this length // 'len' interval, check if arr[i] is more than // max for 'len' ans[len] = max(ans[len], arr[i]); } // Some entries in ans[] may not be filled yet. Fill // them by taking values from right side of ans[] for (int i = n - 1; i >= 1; i--) ans[i] = max(ans[i], ans[i + 1]); // Print the result for (int i = 1; i <= n; i++) cout << ans[i] << "" ""; } // Driver program int main() { int arr[] = { 10, 20, 30, 50, 10, 70, 30 }; int n = sizeof(arr) / sizeof(arr[0]); printMaxOfMin(arr, n); return 0; }",linear,linear "/* C++ Program to check whether valid expression is redundant or not*/ #include using namespace std; // Function to check redundant brackets in a // balanced expression bool checkRedundancy(string& str) { // create a stack of characters stack st; // Iterate through the given expression for (auto& ch : str) { // if current character is close parenthesis ')' if (ch == ')') { char top = st.top(); st.pop(); // If immediate pop have open parenthesis '(' // duplicate brackets found bool flag = true; while (!st.empty() and top != '(') { // Check for operators in expression if (top == '+' || top == '-' || top == '*' || top == '/') flag = false; // Fetch top element of stack top = st.top(); st.pop(); } // If operators not found if (flag == true) return true; } else st.push(ch); // push open parenthesis '(', // operators and operands to stack } return false; } // Function to check redundant brackets void findRedundant(string& str) { bool ans = checkRedundancy(str); if (ans == true) cout << ""Yes\n""; else cout << ""No\n""; } // Driver code int main() { string str = ""((a+b))""; findRedundant(str); return 0; }",linear,linear "// CPP program to mark balanced and unbalanced // parenthesis. #include using namespace std; void identifyParenthesis(string a) { stack st; // run the loop upto end of the string for (int i = 0; i < a.length(); i++) { // if a[i] is opening bracket then push // into stack if (a[i] == '(') st.push(i); // if a[i] is closing bracket ')' else if (a[i] == ')') { // If this closing bracket is unmatched if (st.empty()) a.replace(i, 1, ""-1""); else { // replace all opening brackets with 0 // and closing brackets with 1 a.replace(i, 1, ""1""); a.replace(st.top(), 1, ""0""); st.pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (!st.empty()) { a.replace(st.top(), 1, ""-1""); st.pop(); } // print final string cout << a << endl; } // Driver code int main() { string str = ""(a))""; identifyParenthesis(str); return 0; }",linear,linear "// CPP program to check if two expressions // evaluate to same. #include using namespace std; const int MAX_CHAR = 26; // Return local sign of the operand. For example, // in the expr a-b-(c), local signs of the operands // are +a, -b, +c bool adjSign(string s, int i) { if (i == 0) return true; if (s[i - 1] == '-') return false; return true; }; // Evaluate expressions into the count vector of // the 26 alphabets.If add is true, then add count // to the count vector of the alphabets, else remove // count from the count vector. void eval(string s, vector& v, bool add) { // stack stores the global sign // for operands. stack stk; stk.push(true); // + means true // global sign is positive initially int i = 0; while (s[i] != '\0') { if (s[i] == '+' || s[i] == '-') { i++; continue; } if (s[i] == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.push(stk.top()); else stk.push(!stk.top()); } // global sign is popped out which // was pushed in for the last bracket else if (s[i] == ')') stk.pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk.top()) v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; } }; // Returns true if expr1 and expr2 represent // same expressions bool areSame(string expr1, string expr2) { // Create a vector for all operands and // initialize the vector as 0. vector v(MAX_CHAR, 0); // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (int i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true; } // Driver code int main() { string expr1 = ""-(a+b+c)"", expr2 = ""-a-b-c""; if (areSame(expr1, expr2)) cout << ""Yes\n""; else cout << ""No\n""; return 0; }",linear,linear "// CPP program to find index of closing // bracket for given opening bracket. #include using namespace std; // Function to find index of closing // bracket for given opening bracket. void test(string expression, int index){ int i; // If index given is invalid and is // not an opening bracket. if(expression[index]!='['){ cout << expression << "", "" << index << "": -1\n""; return; } // Stack to store opening brackets. stack st; // Traverse through string starting from // given index. for(i = index; i < expression.length(); i++){ // If current character is an // opening bracket push it in stack. if(expression[i] == '[') st.push(expression[i]); // If current character is a closing // bracket, pop from stack. If stack // is empty, then this closing // bracket is required bracket. else if(expression[i] == ']'){ st.pop(); if(st.empty()){ cout << expression << "", "" << index << "": "" << i << ""\n""; return; } } } // If no matching closing bracket // is found. cout << expression << "", "" << index << "": -1\n""; } // Driver Code int main() { test(""[ABC[23]][89]"", 0); // should be 8 test(""[ABC[23]][89]"", 4); // should be 7 test(""[ABC[23]][89]"", 9); // should be 12 test(""[ABC[23]][89]"", 1); // No matching bracket return 0; } // This code is contributed by Nikhil Jindal.",linear,linear "// C++ program to check for balanced brackets. #include using namespace std; // Function to check if brackets are balanced bool areBracketsBalanced(string expr) { // Declare a stack to hold the previous brackets. stack temp; for (int i = 0; i < expr.length(); i++) { if (temp.empty()) { // If the stack is empty // just push the current bracket temp.push(expr[i]); } else if ((temp.top() == '(' && expr[i] == ')') || (temp.top() == '{' && expr[i] == '}') || (temp.top() == '[' && expr[i] == ']')) { // If we found any complete pair of bracket // then pop temp.pop(); } else { temp.push(expr[i]); } } if (temp.empty()) { // If stack is empty return true return true; } return false; } // Driver code int main() { string expr = ""{()}[]""; // Function call if (areBracketsBalanced(expr)) cout << ""Balanced""; else cout << ""Not Balanced""; return 0; }",linear,linear "// C++ program to determine whether given // expression is balanced/ parenthesis // expression or not. #include using namespace std; // Function to check if two brackets are matching // or not. int isMatching(char a, char b) { if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') return 1; return 0; } // Recursive function to check if given expression // is balanced or not. int isBalanced(string s, stack ele, int ind) { // Base case. // If the string is balanced then all the opening // brackets had been popped and stack should be // empty after string is traversed completely. if (ind == s.length()) return ele.empty(); // variable to store element at the top of the stack. char topEle; // variable to store result of recursive call. int res; // Case 1: When current element is an opening bracket // then push that element in the stack. if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') { ele.push(s[ind]); return isBalanced(s, ele, ind + 1); } // Case 2: When current element is a closing bracket // then check for matching bracket at the top of the // stack. else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') { // If stack is empty then there is no matching opening // bracket for current closing bracket and the // expression is not balanced. if (ele.empty()) return 0; topEle = ele.top(); ele.pop(); // Check bracket is matching or not. if (!isMatching(topEle, s[ind])) return 0; return isBalanced(s, ele, ind + 1); } // Case 3: If current element is 'X' then check // for both the cases when 'X' could be opening // or closing bracket. else if (s[ind] == 'X') { stack tmp = ele; tmp.push(s[ind]); res = isBalanced(s, tmp, ind + 1); if (res) return 1; if (ele.empty()) return 0; ele.pop(); return isBalanced(s, ele, ind + 1); } } int main() { string s = ""{(X}[]""; stack ele; //Check if the String is of even length if(s.length()%2==0){ if (isBalanced(s, ele, 0)) cout << ""Balanced""; else cout << ""Not Balanced""; } // If the length of the string is not even // then it is not a balanced string else{ cout << ""Not Balanced""; } return 0; }",linear,np "// C++ program for an efficient solution to check if // a given array can represent Preorder traversal of // a Binary Search Tree #include using namespace std; bool canRepresentBST(int pre[], int n) { // Create an empty stack stack s; // Initialize current root as minimum possible // value int root = INT_MIN; // Traverse given array for (int i=0; i using namespace std; // We are actually not building the tree void buildBST_helper(int& preIndex, int n, int pre[], int min, int max) { if (preIndex >= n) return; if (min <= pre[preIndex] && pre[preIndex] <= max) { // build node int rootData = pre[preIndex]; preIndex++; // build left subtree buildBST_helper(preIndex, n, pre, min, rootData); // build right subtree buildBST_helper(preIndex, n, pre, rootData, max); } // else // return NULL; } bool canRepresentBST(int arr[], int N) { // code here int min = INT_MIN, max = INT_MAX; int preIndex = 0; buildBST_helper(preIndex, N, arr, min, max); return preIndex == N; } // Driver Code int main() { int preorder1[] = { 2, 4, 3 }; /* 2 \ 4 / 3 */ int n1 = sizeof(preorder1) / sizeof(preorder1[0]); if (canRepresentBST(preorder1, n1)) cout << ""\npreorder1 can represent BST""; else cout << ""\npreorder1 can not represent BST :(""; int preorder2[] = { 5, 3, 4, 1, 6, 10 }; int n2 = sizeof(preorder2) / sizeof(preorder2[0]); /* 5 / \ 3 1 \ / \ 4 6 10 */ if (canRepresentBST(preorder2, n2)) cout << ""\npreorder2 can represent BST""; else cout << ""\npreorder2 can not represent BST :(""; int preorder3[] = { 5, 3, 4, 8, 6, 10 }; int n3 = sizeof(preorder3) / sizeof(preorder3[0]); /* 5 / \ 3 8 \ / \ 4 6 10 */ if (canRepresentBST(preorder3, n3)) cout << ""\npreorder3 can represent BST""; else cout << ""\npreorder3 can not represent BST :(""; return 0; } // This code is contributed by Sourashis Mondal",logn,linear "// C++ program to print minimum number that can be formed // from a given sequence of Is and Ds #include using namespace std; // Function to decode the given sequence to construct // minimum number without repeated digits void PrintMinNumberForPattern(string seq) { // result store output string string result; // create an empty stack of integers stack stk; // run n+1 times where n is length of input sequence for (int i = 0; i <= seq.length(); i++) { // push number i+1 into the stack stk.push(i + 1); // if all characters of the input sequence are // processed or current character is 'I' // (increasing) if (i == seq.length() || seq[i] == 'I') { // run till stack is empty while (!stk.empty()) { // remove top element from the stack and // add it to solution result += to_string(stk.top()); result += "" ""; stk.pop(); } } } cout << result << endl; } // main function int main() { PrintMinNumberForPattern(""IDID""); PrintMinNumberForPattern(""I""); PrintMinNumberForPattern(""DD""); PrintMinNumberForPattern(""II""); PrintMinNumberForPattern(""DIDI""); PrintMinNumberForPattern(""IIDDD""); PrintMinNumberForPattern(""DDIDDIID""); return 0; }",linear,linear "// C++ program of above approach #include using namespace std; // Returns minimum number made from given sequence without repeating digits string getMinNumberForPattern(string seq) { int n = seq.length(); if (n >= 9) return ""-1""; string result(n+1, ' '); int count = 1; // The loop runs for each input character as well as // one additional time for assigning rank to remaining characters for (int i = 0; i <= n; i++) { if (i == n || seq[i] == 'I') { for (int j = i - 1 ; j >= -1 ; j--) { result[j + 1] = '0' + count++; if(j >= 0 && seq[j] == 'I') break; } } } return result; } // main function int main() { string inputs[] = {""IDID"", ""I"", ""DD"", ""II"", ""DIDI"", ""IIDDD"", ""DDIDDIID""}; for (string input : inputs) { cout << getMinNumberForPattern(input) << ""\n""; } return 0; }",linear,linear "// c++ program to generate required sequence #include #include #include #include using namespace std; //:param s: a seq consisting only of 'D' and 'I' chars. D is //for decreasing and I for increasing :return: digits from //1-9 that fit the str. The number they repr should the min //such number vector didi_seq_gen(string s) { if (s.size() == 0) return {}; vector base_list = { ""1"" }; for (int i = 2; i < s.size() + 2; i++) base_list.push_back(to_string(i)); int last_D = -1; for (int i = 1; i < base_list.size(); i++) { if (s[i - 1] == 'D') { if (last_D < 0) last_D = i - 1; string v = base_list[i]; base_list.erase(base_list.begin() + i); base_list.insert(base_list.begin() + last_D, v); } else last_D = -1; } return base_list; } int main() { vector inputs = { ""IDID"", ""I"", ""DD"", ""II"", ""DIDI"", ""IIDDD"", ""DDIDDIID"" }; for (auto x : inputs) { vector ans = didi_seq_gen(x); for (auto i : ans) { cout << i; } cout << endl; } return 0; }",linear,linear "// C++ program to find the difference b/w left and // right smaller element of every element in array #include using namespace std; // Function to fill left smaller element for every // element of arr[0..n-1]. These values are filled // in SE[0..n-1] void leftSmaller(int arr[], int n, int SE[]) { // Create an empty stack stackS; // Traverse all array elements // compute nearest smaller elements of every element for (int i=0; i= arr[i]) S.pop(); // Store the smaller element of current element if (!S.empty()) SE[i] = S.top(); // If all elements in S were greater than arr[i] else SE[i] = 0; // Push this element S.push(arr[i]); } } // Function returns maximum difference b/w Left & // right smaller element int findMaxDiff(int arr[], int n) { int LS[n]; // To store left smaller elements // find left smaller element of every element leftSmaller(arr, n, LS); // find right smaller element of every element // first reverse the array and do the same process int RRS[n]; // To store right smaller elements in // reverse array reverse(arr, arr + n); leftSmaller(arr, n, RRS); // find maximum absolute difference b/w LS & RRS // In the reversed array right smaller for arr[i] is // stored at RRS[n-i-1] int result = -1; for (int i=0 ; i< n ; i++) result = max(result, abs(LS[i] - RRS[n-1-i])); // return maximum difference b/w LS & RRS return result; } // Driver program int main() { int arr[] = {2, 4, 8, 7, 7, 9, 3}; int n = sizeof(arr)/sizeof(arr[0]); cout << ""Maximum diff : "" << findMaxDiff(arr, n) << endl; return 0; }",linear,linear "// C++ Program to find Right smaller element of next // greater element #include using namespace std; // function find Next greater element void nextGreater(int arr[], int n, int next[], char order) { // create empty stack stack S; // Traverse all array elements in reverse order // order == 'G' we compute next greater elements of // every element // order == 'S' we compute right smaller element of // every element for (int i=n-1; i>=0; i--) { // Keep removing top element from S while the top // element is smaller than or equal to arr[i] (if Key is G) // element is greater than or equal to arr[i] (if order is S) while (!S.empty() && ((order=='G')? arr[S.top()] <= arr[i]: arr[S.top()] >= arr[i])) S.pop(); // store the next greater element of current element if (!S.empty()) next[i] = S.top(); // If all elements in S were smaller than arr[i] else next[i] = -1; // Push this element S.push(i); } } // Function to find Right smaller element of next greater // element void nextSmallerOfNextGreater(int arr[], int n) { int NG[n]; // stores indexes of next greater elements int RS[n]; // stores indexes of right smaller elements // Find next greater element // Here G indicate next greater element nextGreater(arr, n, NG, 'G'); // Find right smaller element // using same function nextGreater() // Here S indicate right smaller elements nextGreater(arr, n, RS, 'S'); // If NG[i] == -1 then there is no smaller element // on right side. We can find Right smaller of next // greater by arr[RS[NG[i]]] for (int i=0; i< n; i++) { if (NG[i] != -1 && RS[NG[i]] != -1) cout << arr[RS[NG[i]]] << "" ""; else cout<<""-1""<<"" ""; } } // Driver program int main() { int arr[] = {5, 1, 9, 2, 5, 1, 7}; int n = sizeof(arr)/sizeof(arr[0]); nextSmallerOfNextGreater(arr, n); return 0; }",linear,linear "// C++ program to calculate maximum sum with equal // stack sum. #include using namespace std; // Returns maximum possible equal sum of three stacks // with removal of top elements allowed int maxSum(int stack1[], int stack2[], int stack3[], int n1, int n2, int n3) { int sum1 = 0, sum2 = 0, sum3 = 0; // Finding the initial sum of stack1. for (int i = 0; i < n1; i++) sum1 += stack1[i]; // Finding the initial sum of stack2. for (int i = 0; i < n2; i++) sum2 += stack2[i]; // Finding the initial sum of stack3. for (int i = 0; i < n3; i++) sum3 += stack3[i]; // As given in question, first element is top // of stack.. int top1 = 0, top2 = 0, top3 = 0; while (1) { // If any stack is empty if (top1 == n1 || top2 == n2 || top3 == n3) return 0; // If sum of all three stack are equal. if (sum1 == sum2 && sum2 == sum3) return sum1; // Finding the stack with maximum sum and // removing its top element. if (sum1 >= sum2 && sum1 >= sum3) sum1 -= stack1[top1++]; else if (sum2 >= sum1 && sum2 >= sum3) sum2 -= stack2[top2++]; else if (sum3 >= sum2 && sum3 >= sum1) sum3 -= stack3[top3++]; } } // Driven Program int main() { int stack1[] = { 3, 2, 1, 1, 1 }; int stack2[] = { 4, 3, 2 }; int stack3[] = { 1, 1, 4, 1 }; int n1 = sizeof(stack1) / sizeof(stack1[0]); int n2 = sizeof(stack2) / sizeof(stack2[0]); int n3 = sizeof(stack3) / sizeof(stack3[0]); cout << maxSum(stack1, stack2, stack3, n1, n2, n3) << endl; return 0; }",constant,linear "// C++ program to count the number less than N, // whose all permutation is greater // than or equal to the number. #include using namespace std; // Return the count of the number having all // permutation greater than or equal to the number. int countNumber(int n) { int result = 0; // Pushing 1 to 9 because all number from 1 // to 9 have this property. stack s; for (int i = 1; i <= 9; i++) { if (i <= n) { s.push(i); result++; } // take a number from stack and add // a digit smaller than or equal to last digit // of it. while (!s.empty()) { int tp = s.top(); s.pop(); for (int j = tp % 10; j <= 9; j++) { int x = tp * 10 + j; if (x <= n) { s.push(x); result++; } } } } return result; } // Driven Code int main() { int n = 15; cout << countNumber(n) << endl; return 0; }",linear,linear "// C++ program for bubble sort // using stack #include using namespace std; // Function for bubble sort using Stack void bubbleSortStack(int a[], int n) { stack s1; // Push all elements of array in 1st stack for(int i = 0; i < n; i++) { s1.push(a[i]); } stack s2; for(int i = 0; i < n; i++) { if (i % 2 == 0) { while (!s1.empty()) { int t = s1.top(); s1.pop(); if (s2.empty()) { s2.push(t); } else { // Swapping if (s2.top() > t) { int temp = s2.top(); s2.pop(); s2.push(t); s2.push(temp); } else { s2.push(t); } } } // Tricky step a[n - 1 - i] = s2.top(); s2.pop(); } else { while (!s2.empty()) { int t = s2.top(); s2.pop(); if (s1.empty()) { s1.push(t); } else { if (s1.top() > t) { int temp = s1.top(); s1.pop(); s1.push(t); s1.push(temp); } else { s1.push(t); } } } // Tricky step a[n - 1 - i] = s1.top(); s1.pop(); } } cout << ""[""; for(int i = 0; i < n; i++) { cout << a[i] << "", ""; } cout << ""]""; } // Driver code int main() { int a[] = { 15, 12, 44, 2, 5, 10 }; int n = sizeof(a) / sizeof(a[0]); bubbleSortStack(a, n); return 0; } // This code is contributed by pawki",linear,quadratic "// C++ program to print all ancestors of a given key #include using namespace std; // Structure for a tree node struct Node { int data; struct Node* left, *right; }; // A utility function to create a new tree node struct Node* newNode(int data) { struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = node->right = NULL; return node; } // Iterative Function to print all ancestors of a // given key void printAncestors(struct Node* root, int key) { if (root == NULL) return; // Create a stack to hold ancestors stack st; // Traverse the complete tree in postorder way till // we find the key while (1) { // Traverse the left side. While traversing, push // the nodes into the stack so that their right // subtrees can be traversed later while (root && root->data != key) { st.push(root); // push current node root = root->left; // move to next node } // If the node whose ancestors are to be printed // is found, then break the while loop. if (root && root->data == key) break; // Check if right sub-tree exists for the node at top // If not then pop that node because we don't need // this node any more. if (st.top()->right == NULL) { root = st.top(); st.pop(); // If the popped node is right child of top, // then remove the top as well. Left child of // the top must have processed before. while (!st.empty() && st.top()->right == root) { root = st.top(); st.pop(); } } // if stack is not empty then simply set the root // as right child of top and start traversing right // sub-tree. root = st.empty() ? NULL : st.top()->right; } // If stack is not empty, print contents of stack // Here assumption is that the key is there in tree while (!st.empty()) { cout << st.top()->data << "" ""; st.pop(); } } // Driver program to test above functions int main() { // Let us construct a binary tree struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(7); root->left->left = newNode(3); root->left->right = newNode(5); root->right->left = newNode(8); root->right->right = newNode(9); root->left->left->left = newNode(4); root->left->right->right = newNode(6); root->right->right->left = newNode(10); int key = 6; printAncestors(root, key); return 0; }",linear,linear "// Given two arrays, check if one array is // stack permutation of other. #include using namespace std; // function to check if input queue is // permutable to output queue bool checkStackPermutation(int ip[], int op[], int n) { // Input queue queue input; for (int i=0;i output; for (int i=0;i tempStack; while (!input.empty()) { int ele = input.front(); input.pop(); if (ele == output.front()) { output.pop(); while (!tempStack.empty()) { if (tempStack.top() == output.front()) { tempStack.pop(); output.pop(); } else break; } } else tempStack.push(ele); } // If after processing, both input queue and // stack are empty then the input queue is // permutable otherwise not. return (input.empty()&&tempStack.empty()); } // Driver program to test above function int main() { // Input Queue int input[] = {1, 2, 3}; // Output Queue int output[] = {2, 1, 3}; int n = 3; if (checkStackPermutation(input, output, n)) cout << ""Yes""; else cout << ""Not Possible""; return 0; }",linear,linear "// Given two arrays, check if one array is // stack permutation of other. #include using namespace std; // function to check if input array is // permutable to output array bool checkStackPermutation(int ip[], int op[], int n) { // we will be pushing elements from input array to stack uptill top of our stack // matches with first element of output array stacks; // will maintain a variable j to iterate on output array int j=0; // will iterate one by one in input array for(int i=0;i using namespace std; class StackWithMax { // main stack stack mainStack; // stack to keep track of max element stack trackStack; public: void push(int x) { mainStack.push(x); if (mainStack.size() == 1) { trackStack.push(x); return; } // If current element is greater than // the top element of track stack, push // the current element to track stack // otherwise push the element at top of // track stack again into it. if (x > trackStack.top()) trackStack.push(x); else trackStack.push(trackStack.top()); } int getMax() { return trackStack.top(); } int pop() { mainStack.pop(); trackStack.pop(); } }; // Driver program to test above functions int main() { StackWithMax s; s.push(20); cout << s.getMax() << endl; s.push(10); cout << s.getMax() << endl; s.push(50); cout << s.getMax() << endl; return 0; }",linear,constant "// CPP program to reverse the number // using a stack #include using namespace std; // Stack to maintain order of digits stack st; // Function to push digits into stack void push_digits(int number) { while (number != 0) { st.push(number % 10); number = number / 10; } } // Function to reverse the number int reverse_number(int number) { // Function call to push number's // digits to stack push_digits(number); int reverse = 0; int i = 1; // Popping the digits and forming // the reversed number while (!st.empty()) { reverse = reverse + (st.top() * i); st.pop(); i = i * 10; } // Return the reversed number formed return reverse; } // Driver program to test above function int main() { int number = 39997; // Function call to reverse number cout << reverse_number(number); return 0; }",logn,logn "// C++ program to reverse first // k elements of a queue. #include using namespace std; /* Function to reverse the first K elements of the Queue */ void reverseQueueFirstKElements(int k, queue& Queue) { if (Queue.empty() == true || k > Queue.size()) return; if (k <= 0) return; stack Stack; /* Push the first K elements into a Stack*/ for (int i = 0; i < k; i++) { Stack.push(Queue.front()); Queue.pop(); } /* Enqueue the contents of stack at the back of the queue*/ while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } /* Remove the remaining elements and enqueue them at the end of the Queue*/ for (int i = 0; i < Queue.size() - k; i++) { Queue.push(Queue.front()); Queue.pop(); } } /* Utility Function to print the Queue */ void Print(queue& Queue) { while (!Queue.empty()) { cout << Queue.front() << "" ""; Queue.pop(); } } // Driver code int main() { queue Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); int k = 5; reverseQueueFirstKElements(k, Queue); Print(Queue); }",linear,linear "// CPP program to reverse a Queue #include using namespace std; // Utility function to print the queue void Print(queue& Queue) { while (!Queue.empty()) { cout << Queue.front() << "" ""; Queue.pop(); } } // Function to reverse the queue void reverseQueue(queue& Queue) { stack Stack; while (!Queue.empty()) { Stack.push(Queue.front()); Queue.pop(); } while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } } // Driver code int main() { queue Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); Print(Queue); }",linear,linear "// CPP program to reverse a Queue #include using namespace std; // Utility function to print the queue void Print(queue& Queue) { while (!Queue.empty()) { cout << Queue.front() << "" ""; Queue.pop(); } } // Function to reverse the queue void reverseQueue(queue& q) { // base case if (q.size() == 0) return; // storing front(first element) of queue int fr = q.front(); // removing front q.pop(); // asking recursion to reverse the // leftover queue reverseQueue(q); // placing first element // at its correct position q.push(fr); } // Driver code int main() { queue Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); Queue.push(60); Queue.push(70); Queue.push(80); Queue.push(90); Queue.push(100); reverseQueue(Queue); Print(Queue); } // This code is contributed by Nakshatra Chhillar",linear,linear "// C++ program to check if successive // pair of numbers in the stack are // consecutive or not #include using namespace std; // Function to check if elements are // pairwise consecutive in stack bool pairWiseConsecutive(stack s) { // Transfer elements of s to aux. stack aux; while (!s.empty()) { aux.push(s.top()); s.pop(); } // Traverse aux and see if // elements are pairwise // consecutive or not. We also // need to make sure that original // content is retained. bool result = true; while (aux.size() > 1) { // Fetch current top two // elements of aux and check // if they are consecutive. int x = aux.top(); aux.pop(); int y = aux.top(); aux.pop(); if (abs(x - y) != 1) result = false; // Push the elements to original // stack. s.push(x); s.push(y); } if (aux.size() == 1) s.push(aux.top()); return result; } // Driver program int main() { stack s; s.push(4); s.push(5); s.push(-2); s.push(-3); s.push(11); s.push(10); s.push(5); s.push(6); s.push(20); if (pairWiseConsecutive(s)) cout << ""Yes"" << endl; else cout << ""No"" << endl; cout << ""Stack content (from top)"" "" after function call\n""; while (s.empty() == false) { cout << s.top() << "" ""; s.pop(); } return 0; }",linear,linear "// C++ program to interleave the first half of the queue // with the second half #include using namespace std; // Function to interleave the queue void interLeaveQueue(queue& q) { // To check the even number of elements if (q.size() % 2 != 0) cout << ""Input even number of integers."" << endl; // Initialize an empty stack of int type stack s; int halfSize = q.size() / 2; // Push first half elements into the stack // queue:16 17 18 19 20, stack: 15(T) 14 13 12 11 for (int i = 0; i < halfSize; i++) { s.push(q.front()); q.pop(); } // enqueue back the stack elements // queue: 16 17 18 19 20 15 14 13 12 11 while (!s.empty()) { q.push(s.top()); s.pop(); } // dequeue the first half elements of queue // and enqueue them back // queue: 15 14 13 12 11 16 17 18 19 20 for (int i = 0; i < halfSize; i++) { q.push(q.front()); q.pop(); } // Again push the first half elements into the stack // queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15 for (int i = 0; i < halfSize; i++) { s.push(q.front()); q.pop(); } // interleave the elements of queue and stack // queue: 11 16 12 17 13 18 14 19 15 20 while (!s.empty()) { q.push(s.top()); s.pop(); q.push(q.front()); q.pop(); } } // Driver program to test above function int main() { queue q; q.push(11); q.push(12); q.push(13); q.push(14); q.push(15); q.push(16); q.push(17); q.push(18); q.push(19); q.push(20); interLeaveQueue(q); int length = q.size(); for (int i = 0; i < length; i++) { cout << q.front() << "" ""; q.pop(); } return 0; }",linear,linear "// CPP Program to implement growable array based stack // using tight strategy #include using namespace std; // constant amount at which stack is increased #define BOUND 4 // top of the stack int top = -1; // length of stack int length = 0; // function to create new stack int* create_new(int* a) { // allocate memory for new stack int* new_a = new int[length + BOUND]; // copying the content of old stack for (int i = 0; i < length; i++) new_a[i] = a[i]; // re-sizing the length length += BOUND; return new_a; } // function to push new element int* push(int* a, int element) { // if stack is full, create new one if (top == length - 1) a = create_new(a); // insert element at top of the stack a[++top] = element; return a; } // function to pop an element void pop(int* a) { if (top < 0) { cout << ""Stack is empty"" << endl; return; } top--; } // function to display void display(int* a) { // if top is less than 0, that means stack is empty if (top < 0) cout << ""Stack is Empty"" << endl; else { cout << ""Stack: ""; for (int i = 0; i <= top; i++) cout << a[i] << "" ""; cout << endl; } } // Driver Code int main() { // creating initial stack int* a = create_new(a); // pushing element to top of stack a = push(a, 1); a = push(a, 2); a = push(a, 3); a = push(a, 4); display(a); // pushing more element when stack is full a = push(a, 5); a = push(a, 6); display(a); a = push(a, 7); a = push(a, 8); display(a); // pushing more element so that stack can grow a = push(a, 9); display(a); return 0; }",linear,linear "// CPP code to answer the query in constant time #include using namespace std; /* BOP[] stands for ""Balanced open parentheses"" BCP[] stands for ""Balanced close parentheses"" */ // function for precomputation void constructBalanceArray(int BOP[], int BCP[], char* str, int n) { // Create a stack and push -1 as initial index to it. stack stk; // Initialize result int result = 0; // Traverse all characters of given string for (int i = 0; i < n; i++) { // If opening bracket, push index of it if (str[i] == '(') stk.push(i); else // If closing bracket, i.e., str[i] = ')' { // If closing bracket, i.e., str[i] = ')' // && stack is not empty then mark both // ""open & close"" bracket indexes as 1 . // Pop the previous opening bracket's index if (!stk.empty()) { BCP[i] = 1; BOP[stk.top()] = 1; stk.pop(); } // If stack is empty. else BCP[i] = 0; } } for (int i = 1; i < n; i++) { BCP[i] += BCP[i - 1]; BOP[i] += BOP[i - 1]; } } // Function return output of each query in O(1) int query(int BOP[], int BCP[], int s, int e) { if (BOP[s - 1] == BOP[s]) { return (BCP[e] - BOP[s]) * 2; } else { return (BCP[e] - BOP[s] + 1) * 2; } } // Driver program to test above function int main() { char str[] = ""())(())(())(""; int n = strlen(str); int BCP[n + 1] = { 0 }; int BOP[n + 1] = { 0 }; constructBalanceArray(BOP, BCP, str, n); int startIndex = 5, endIndex = 11; cout << ""Maximum Length Correct Bracket"" "" Subsequence between "" << startIndex << "" and "" << endIndex << "" = "" << query(BOP, BCP, startIndex, endIndex) << endl; startIndex = 4, endIndex = 5; cout << ""Maximum Length Correct Bracket"" "" Subsequence between "" << startIndex << "" and "" << endIndex << "" = "" << query(BOP, BCP, startIndex, endIndex) << endl; startIndex = 1, endIndex = 5; cout << ""Maximum Length Correct Bracket"" "" Subsequence between "" << startIndex << "" and "" << endIndex << "" = "" << query(BOP, BCP, startIndex, endIndex) << endl; return 0; }",linear,linear "// Recursive Program to remove consecutive // duplicates from string S. #include using namespace std; // A recursive function that removes // consecutive duplicates from string S void removeDuplicates(char* S) { // When string is empty, return if (S[0] == '\0') return; // if the adjacent characters are same if (S[0] == S[1]) { // Shift character by one to left int i = 0; while (S[i] != '\0') { S[i] = S[i + 1]; i++; } // Check on Updated String S removeDuplicates(S); } // If the adjacent characters are not same // Check from S+1 string address removeDuplicates(S + 1); } // Driver Program int main() { char S1[] = ""geeksforgeeks""; removeDuplicates(S1); cout << S1 << endl; char S2[] = ""aabcca""; removeDuplicates(S2); cout << S2 << endl; return 0; }",constant,quadratic "// C++ program to remove consecutive // duplicates from a given string. #include using namespace std; // A iterative function that removes // consecutive duplicates from string S string removeDuplicates(string s) { int n = s.length(); string str = """"; // We don't need to do anything for // empty string. if (n == 0) return str; // Traversing string for (int i = 0; i < n - 1; i++) { // checking if s[i] is not same as s[i+1] then add // it into str if (s[i] != s[i + 1]) { str += s[i]; } } // Since the last character will not be inserted in the // loop we add it at the end str.push_back(s[n - 1]); return str; } // Driver Program int main() { string s1 = ""geeksforgeeks""; cout << removeDuplicates(s1) << endl; string s2 = ""aabcca""; cout << removeDuplicates(s2) << endl; return 0; }",constant,linear "// CPP program to find smallest // number to find smallest number // with N as sum of digits and // divisible by 10^N. #include using namespace std; void digitsNum(int N) { // If N = 0 the string will be 0 if (N == 0) cout << ""0\n""; // If n is not perfectly divisible // by 9 output the remainder if (N % 9 != 0) cout << (N % 9); // Print 9 N/9 times for (int i = 1; i <= (N / 9); ++i) cout << ""9""; // Append N zero's to the number so // as to make it divisible by 10^N for (int i = 1; i <= N; ++i) cout << ""0""; cout << ""\n""; } // Driver Code int main() { int N = 5; cout << ""The number is : ""; digitsNum(N); return 0; }",constant,linear "// C++ program to find min sum of squares // of characters after k removals #include using namespace std; const int MAX_CHAR = 26; // Main Function to calculate min sum of // squares of characters after k removals int minStringValue(string str, int k) { int l = str.length(); // find length of string // if K is greater than length of string // so reduced string will become 0 if (k >= l) return 0; // Else find Frequency of each character and // store in an array int frequency[MAX_CHAR] = { 0 }; for (int i = 0; i < l; i++) frequency[str[i] - 'a']++; // Push each char frequency into a priority_queue priority_queue q; for (int i = 0; i < MAX_CHAR; i++) q.push(frequency[i]); // Removal of K characters while (k--) { // Get top element in priority_queue, // remove it. Decrement by 1 and again // push into priority_queue int temp = q.top(); q.pop(); temp = temp - 1; q.push(temp); } // After removal of K characters find sum // of squares of string Value int result = 0; // Initialize result while (!q.empty()) { int temp = q.top(); result += temp * temp; q.pop(); } return result; } // Driver Code int main() { string str = ""abbccc""; // Input 1 int k = 2; cout << minStringValue(str, k) << endl; str = ""aaab""; // Input 2 k = 2; cout << minStringValue(str, k); return 0; }",constant,nlogn "// C++ program to find min sum of squares // of characters after k removals #include using namespace std; const int MAX_CHAR = 26; // Main Function to calculate min sum of // squares of characters after k removals int minStringValue(string str, int k) { int alphabetCount[MAX_CHAR]= {0}; // Here the array stored frequency the number of // occurrences in string m[frequency]=number of alphabets // with frequency i.e, in our example abbccc m[1]=1(1 // a's occur),m[2]=1(2 b's occur),m[3]=1(3 c'soccur) int m[str.length()] = { 0 }; for (int i = 0; i < str.length(); i++) { alphabetCount[str[i] - 'a']++; } // Store the maximum int maximum = 0; for (int i = 0; i < MAX_CHAR; i++) { m[alphabetCount[i]]++; maximum = max(maximum, alphabetCount[i]); } while (k > 0) { int z = m[maximum]; if (z <= k) { // Remove one occurrence of alphabet from each // with frequency as maximum. // So we will have k-z more remove operations to // perform as z is number of characters and we // perform one removal from each of the alphabet // with that frequency. k = k - z; // As we removed one occurrence from each the // alphabets will no longer have the frequency // of maximum their frequency will be decreased // by one so add these number of alphabets to // group with frequency one less than maximum. // Remove them from maximum count. m[maximum] = 0; // Add those to frequency one less. m[maximum - 1] += z; // new maximum will be one less. maximum--; } else { // if all the elements of that frequency cannot // be removed we should partially remove them. m[maximum] -= k; maximum--; m[maximum] += k; k = 0; } } int ans = 0; for (int i = 0; i < str.length(); i++) { //(square of frequency)*(number of // characters corresponding to that frequency) ans += (i * i) * m[i]; } return ans; } // Driver Code int main() { string str = ""abbccc""; // Input 1 int k = 2; cout << minStringValue(str, k) << endl; str = ""aaab""; // Input 2 k = 2; cout << minStringValue(str, k); return 0; } // This code is contributed by Kasina Dheeraj.",linear,linear "// C++ program to find maximum and minimum // possible sums of two numbers that we can // get if replacing digit from 5 to 6 and vice // versa are allowed. #include using namespace std; // Find new value of x after replacing digit // ""from"" to ""to"" int replaceDig(int x, int from, int to) { int result = 0; int multiply = 1; while (x > 0) { int reminder = x % 10; // Required digit found, replace it if (reminder == from) result = result + to * multiply; else result = result + reminder * multiply; multiply *= 10; x = x / 10; } return result; } // Returns maximum and minimum possible sums of // x1 and x2 if digit replacements are allowed. void calculateMinMaxSum(int x1, int x2) { // We always get minimum sum if we replace // 6 with 5. int minSum = replaceDig(x1, 6, 5) + replaceDig(x2, 6, 5); // We always get maximum sum if we replace // 5 with 6. int maxSum = replaceDig(x1, 5, 6) + replaceDig(x2, 5, 6); cout << ""Minimum sum = "" << minSum; cout << ""nMaximum sum = "" << maxSum; } // Driver code int main() { int x1 = 5466, x2 = 4555; calculateMinMaxSum(x1, x2); return 0; }",constant,logn "// C++ program to check if a given string // is sum-string or not #include using namespace std; // this is function for finding sum of two // numbers as string string string_sum(string str1, string str2) { if (str1.size() < str2.size()) swap(str1, str2); int m = str1.size(); int n = str2.size(); string ans = """"; // sum the str2 with str1 int carry = 0; for (int i = 0; i < n; i++) { // Sum of current digits int ds = ((str1[m - 1 - i] - '0') + (str2[n - 1 - i] - '0') + carry) % 10; carry = ((str1[m - 1 - i] - '0') + (str2[n - 1 - i] - '0') + carry) / 10; ans = char(ds + '0') + ans; } for (int i = n; i < m; i++) { int ds = (str1[m - 1 - i] - '0' + carry) % 10; carry = (str1[m - 1 - i] - '0' + carry) / 10; ans = char(ds + '0') + ans; } if (carry) ans = char(carry + '0') + ans; return ans; } // Returns true if two substrings of given // lengths of str[beg..] can cause a positive // result. bool checkSumStrUtil(string str, int beg, int len1, int len2) { // Finding two substrings of given lengths // and their sum string s1 = str.substr(beg, len1); string s2 = str.substr(beg + len1, len2); string s3 = string_sum(s1, s2); int s3_len = s3.size(); // if number of digits s3 is greater than // the available string size if (s3_len > str.size() - len1 - len2 - beg) return false; // we got s3 as next number in main string if (s3 == str.substr(beg + len1 + len2, s3_len)) { // if we reach at the end of the string if (beg + len1 + len2 + s3_len == str.size()) return true; // otherwise call recursively for n2, s3 return checkSumStrUtil(str, beg + len1, len2, s3_len); } // we do not get s3 in main string return false; } // Returns true if str is sum string, else false. bool isSumStr(string str) { int n = str.size(); // choosing first two numbers and checking // whether it is sum-string or not. for (int i = 1; i < n; i++) for (int j = 1; i + j < n; j++) if (checkSumStrUtil(str, 0, i, j)) return true; return false; } // Driver code int main() { bool result; result = isSumStr(""1212243660""); cout << (result == 1 ? ""True\n"" : ""False\n""); result = isSumStr(""123456787""); cout << (result == 1 ? ""True\n"" : ""False\n""); return 0; }",linear,cubic "// C++ program to find maximum value #include using namespace std; // Function to calculate the value int calcMaxValue(string str) { // Store first character as integer // in result int res = str[0] -'0'; // Start traversing the string for (int i = 1; i < str.length(); i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str[i] == '0' || str[i] == '1' || res < 2 ) res += (str[i]-'0'); // Else multiply else res *= (str[i]-'0'); } // Return maximum value return res; } // Drivers code int main() { string str = ""01891""; cout << calcMaxValue(str); return 0; }",constant,linear "// CPP program to find the maximum segment // value after putting k breaks. #include using namespace std; // Function to Find Maximum Number int findMaxSegment(string &s, int k) { // Maximum segment length int seg_len = s.length() - k; // Find value of first segment of seg_len int res = 0; for (int i=0; i using namespace std; // Function to find that number divisible by // 4 or not bool check(string str) { // Get the length of the string int n = str.length(); // Empty string if (n == 0) return false; // stoi(string_variable) is used in C++ // to convert string to integer // If there is single digit if (n == 1) return ((stoi(str)) % 4 == 0); // getting last two characters using substring str = str.substr(n - 2, 2); // If number formed by last two digits is // divisible by 4. return ((stoi(str)) % 4 == 0); } // Driver code int main() { string str = ""76952""; // Function call check(str) ? cout << ""Yes"" : cout << ""No ""; return 0; } // This code is contributed by Abhijeet Kumar(abhijeet19403)",constant,constant "// C++ program to calculate number of substring // divisible by 6. #include #define MAX 100002 using namespace std; // Return the number of substring divisible by 6 // and starting at index i in s[] and previous sum // of digits modulo 3 is m. int f(int i, int m, char s[], int memoize[][3]) { // End of the string. if (i == strlen(s)) return 0; // If already calculated, return the // stored value. if (memoize[i][m] != -1) return memoize[i][m]; // Converting into integer. int x = s[i] - '0'; // Increment result by 1, if current digit // is divisible by 2 and sum of digits is // divisible by 3. // And recur for next index with new modulo. int ans = ((x+m)%3 == 0 && x%2 == 0) + f(i+1, (m+x)%3, s, memoize); return memoize[i][m] = ans; } // Returns substrings divisible by 6. int countDivBy6(char s[]) { int n = strlen(s); // For storing the value of all states. int memoize[n+1][3]; memset(memoize, -1, sizeof memoize); int ans = 0; for (int i = 0; i < strlen(s); i++) { // If string contain 0, increment count by 1. if (s[i] == '0') ans++; // Else calculate using recursive function. // Pass previous sum modulo 3 as 0. else ans += f(i, 0, s, memoize); } return ans; } // Driven Program int main() { char s[] = ""4806""; cout << countDivBy6(s) << endl; return 0; }",linear,linear "// C++ implementation to check whether decimal representation // of given binary number is divisible by 5 or not #include using namespace std; // function to return equivalent base 4 number // of the given binary number int equivalentBase4(string bin) { if (bin.compare(""00"") == 0) return 0; if (bin.compare(""01"") == 0) return 1; if (bin.compare(""10"") == 0) return 2; return 3; } // function to check whether the given binary // number is divisible by 5 or not string isDivisibleBy5(string bin) { int l = bin.size(); if (l % 2 != 0) // add '0' in the beginning to make // length an even number bin = '0' + bin; // to store sum of digits at odd and // even places respectively int odd_sum, even_sum = 0; // variable check for odd place and // even place digit int isOddDigit = 1; for (int i = 0; i using namespace std; #define MAX 1000 // Returns count of substrings divisible by 8 // but not by 3. int count(char s[], int len) { int cur = 0, dig = 0; int sum[MAX], dp[MAX][3]; memset(sum, 0, sizeof(sum)); memset(dp, 0, sizeof(dp)); dp[0][0] = 1; // Iterating the string. for (int i = 1; i <= len; i++) { dig = int(s[i-1])-48; cur += dig; cur %= 3; sum[i] = cur; // Prefix sum of number of substrings whose // sum of digits modulo 3 is 0, 1, 2. dp[i][0] = dp[i-1][0]; dp[i][1] = dp[i-1][1]; dp[i][2] = dp[i-1][2]; dp[i][sum[i]]++; } int ans = 0, dprev = 0, value = 0, dprev2 = 0; // Iterating the string. for (int i = 1; i <= len; i++) { dig = int(s[i-1])-48; // Since single digit 8 is divisible // by 8 and not by 3. if (dig == 8) ans++; // Taking two digit number. if (i-2 >= 0) { dprev = int(s[i-2])-48; // 10th position value = dprev*10 + dig; // Complete 2 digit // number if ((value%8 == 0) && (value%3 != 0)) ans++; } // Taking 3 digit number. if (i-3 >= 0) { dprev2 = int(s[i-3])-48; // 100th position dprev = int(s[i-2])-48; // 10th position // Complete 3 digit number. value = dprev2*100 + dprev*10 + dig; if (value%8 != 0) continue; // If number formed is divisible by 8 then // last 3 digits are also divisible by 8. // Then all the substring ending at this // index is divisible. ans += (i-2); // But those substring also contain number // which are not divisible by 3 so // remove them. ans -= (dp[i-3][sum[i]]); } } return ans; } // Driven Program int main() { char str[] = ""6564525600""; int len = strlen(str); cout << count(str, len) < using namespace std; // function to check divisibility bool isDivisible999(string num) { int n = num.length(); if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = ""00"" + num; if (n % 3 == 2) num = ""0"" + num; // add digits in group of three in gSum int gSum = 0; for (int i = 0; i 1000) { num = to_string(gSum); n = num.length(); gSum = isDivisible999(num); } return (gSum == 999); } // driver program int main() { string num = ""1998""; int n = num.length(); if (isDivisible999(num)) cout << ""Divisible""; else cout << ""Not divisible""; return 0; }",constant,linear "// C++ program to implement division with large // number #include using namespace std; // A function to perform division of large numbers string longDivision(string number, int divisor) { // As result can be very large store it in string string ans; // Find prefix of number that is larger // than divisor. int idx = 0; int temp = number[idx] - '0'; while (temp < divisor) temp = temp * 10 + (number[++idx] - '0'); // Repeatedly divide divisor with temp. After // every division, update temp to include one // more digit. while (number.size() > idx) { // Store result in answer i.e. temp / divisor ans += (temp / divisor) + '0'; // Take next digit of number temp = (temp % divisor) * 10 + number[++idx] - '0'; } // If divisor is greater than number if (ans.length() == 0) return ""0""; // else return ans return ans; } // Driver program to test longDivision() int main() { string number = ""1248163264128256512""; int divisor = 125; cout << longDivision(number, divisor); return 0; }",linear,np "// C++ program to find remainder of a large // number when divided by 7. #include using namespace std; /* Function which returns Remainder after dividing the number by 7 */ int remainderWith7(string num) { // This series is used to find remainder with 7 int series[] = {1, 3, 2, -1, -3, -2}; // Index of next element in series int series_index = 0; int result = 0; // Initialize result // Traverse num from end for (int i=num.size()-1; i>=0; i--) { /* Find current digit of nun */ int digit = num[i] - '0'; // Add next term to result result += digit * series[series_index]; // Move to next term in series series_index = (series_index + 1) % 6; // Make sure that result never goes beyond 7. result %= 7; } // Make sure that remainder is positive if (result < 0) result = (result + 7) % 7; return result; } /* Driver program */ int main() { string str = ""12345""; cout << ""Remainder with 7 is "" << remainderWith7(str); return 0; }",constant,linear "// A simple C++ program to // check for even or odd #include using namespace std; // Returns true if n is // even, else odd bool isEven(int n) { return (n % 2 == 0); } // Driver code int main() { int n = 101; isEven(n) ? cout << ""Even"" : cout << ""Odd""; return 0; }",constant,constant "// A simple C++ program to // check for even or odd #include using namespace std; // Returns true if n is // even, else odd bool isEven(int n) { // n & 1 is 1, then // odd, else even return (!(n & 1)); } // Driver code int main() { int n = 101; isEven(n)? cout << ""Even"" : cout << ""Odd""; return 0; }",constant,constant "// C++ implementation to find product of // digits of elements at k-th level #include using namespace std; // Function to find product of digits // of elements at k-th level int productAtKthLevel(string tree, int k) { int level = -1; int product = 1; // Initialize result int n = tree.length(); for (int i = 0; i < n; i++) { // increasing level number if (tree[i] == '(') level++; // decreasing level number else if (tree[i] == ')') level--; else { // check if current level is // the desired level or not if (level == k) product *= (tree[i] - '0'); } } // required product return product; } // Driver program int main() { string tree = ""(0(5(6()())(4()(9()())))(7(1()())(3()())))""; int k = 2; cout << productAtKthLevel(tree, k); return 0; }",constant,linear "// CPP implementation to find remainder // when a large number is divided by 11 #include using namespace std; // Function to return remainder int remainder(string str) { // len is variable to store the // length of number string. int len = str.length(); int num, rem = 0; // loop that find remainder for (int i = 0; i < len; i++) { num = rem * 10 + (str[i] - '0'); rem = num % 11; } return rem; } // Driver code int main() { string str = ""3435346456547566345436457867978""; cout << remainder(str); return 0; }",constant,linear "// C++ program to count number of ways to // remove an element so that XOR of remaining // string becomes 0. #include using namespace std; // Return number of ways in which XOR become ZERO // by remove 1 element int xorZero(string str) { int one_count = 0, zero_count = 0; int n = str.length(); // Counting number of 0 and 1 for (int i = 0; i < n; i++) if (str[i] == '1') one_count++; else zero_count++; // If count of ones is even // then return count of zero // else count of one if (one_count % 2 == 0) return zero_count; return one_count; } // Driver Code int main() { string str = ""11111""; cout << xorZero(str) << endl; return 0; }",constant,linear "// A simple C++ program to find max subarray XOR #include using namespace std; int maxSubarrayXOR(int arr[], int n) { int ans = INT_MIN; // Initialize result // Pick starting points of subarrays for (int i=0; i using namespace std; // Assumed int size #define INT_SIZE 32 // A Trie Node struct TrieNode { int value; // Only used in leaf nodes TrieNode *arr[2]; }; // Utility function to create a Trie node TrieNode *newNode() { TrieNode *temp = new TrieNode; temp->value = 0; temp->arr[0] = temp->arr[1] = NULL; return temp; } // Inserts pre_xor to trie with given root void insert(TrieNode *root, int pre_xor) { TrieNode *temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<arr[val] == NULL) temp->arr[val] = newNode(); temp = temp->arr[val]; } // Store value at leaf node temp->value = pre_xor; } // Finds the maximum XOR ending with last number in // prefix XOR 'pre_xor' and returns the XOR of this maximum // with pre_xor which is maximum XOR ending with last element // of pre_xor. int query(TrieNode *root, int pre_xor) { TrieNode *temp = root; for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<arr[1-val]!=NULL) temp = temp->arr[1-val]; // If there is no prefix with opposite // bit, then look for same bit. else if (temp->arr[val] != NULL) temp = temp->arr[val]; } return pre_xor^(temp->value); } // Returns maximum XOR value of a subarray in arr[0..n-1] int maxSubarrayXOR(int arr[], int n) { // Create a Trie and insert 0 into it TrieNode *root = newNode(); insert(root, 0); // Initialize answer and xor of current prefix int result = INT_MIN, pre_xor =0; // Traverse all input array element for (int i=0; i using namespace std; // Utility function to check character is vowel // or not bool isVowel(char ch) { return ( ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'); } // Function to calculate difficulty int calcDiff(string str) { int count_vowels = 0, count_conso = 0; int hard_words = 0, easy_words = 0; int consec_conso = 0; // Start traversing the string for (int i = 0; i < str.length(); i++) { // Check if current character is vowel // or consonant if (str[i] != ' ' && isVowel(tolower(str[i]))) { // Increment if vowel count_vowels++; consec_conso = 0; } // Increment counter for consonant // also maintain a separate counter for // counting consecutive consonants else if (str[i]!= ' ') { count_conso++; consec_conso++; } // If we get 4 consecutive consonants // then it is a hard word if (consec_conso == 4) { hard_words++; // Move to the next word while (i < str.length() && str[i]!= ' ') i++; // Reset all counts count_conso = 0; count_vowels = 0; consec_conso = 0; } else if ( i < str.length() && (str[i] == ' ' || i == str.length()-1)) { // Increment hard_words, if no. of consonants are // higher than no. of vowels, otherwise increment // count_vowels count_conso > count_vowels ? hard_words++ : easy_words++; // Reset all counts count_conso = 0; count_vowels = 0; consec_conso = 0; } } // Return difficulty of sentence return 5 * hard_words + 3 * easy_words; } // Drivers code int main() { string str = ""I am a geek""; string str2 = ""We are geeks""; cout << calcDiff(str) << endl; cout << calcDiff(str2) << endl; return 0; }",constant,linear "#include using namespace std; // Function to print common strings with minimum index sum void find(vector list1, vector list2) { vector res; // resultant list int max_possible_sum = list1.size() + list2.size() - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common strings in resultant list if (i < list1.size() && (sum - i) < list2.size() && list1[i] == list2[sum - i]) res.push_back(list1[i]); // if common string found then break as we are // considering index sums in increasing order. if (res.size() > 0) break; } // print the resultant list for (int i = 0; i < res.size(); i++) cout << res[i] << "" ""; } // Driver code int main() { // Creating list1 vector list1; list1.push_back(""GeeksforGeeks""); list1.push_back(""Udemy""); list1.push_back(""Coursera""); list1.push_back(""edX""); // Creating list2 vector list2; list2.push_back(""Codecademy""); list2.push_back(""Khan Academy""); list2.push_back(""GeeksforGeeks""); find(list1, list2); return 0; }",quadratic,linear "// Hashing based C++ program to find common elements // with minimum index sum. #include using namespace std; // Function to print common strings with minimum index sum void find(vector list1, vector list2) { // mapping strings to their indices unordered_map map; for (int i = 0; i < list1.size(); i++) map[list1[i]] = i; vector res; // resultant list int minsum = INT_MAX; for (int j = 0; j < list2.size(); j++) { if (map.count(list2[j])) { // If current sum is smaller than minsum int sum = j + map[list2[j]]; if (sum < minsum) { minsum = sum; res.clear(); res.push_back(list2[j]); } // if index sum is same then put this // string in resultant list as well else if (sum == minsum) res.push_back(list2[j]); } } // Print result for (int i = 0; i < res.size(); i++) cout << res[i] << "" ""; } // Driver code int main() { // Creating list1 vector list1; list1.push_back(""GeeksforGeeks""); list1.push_back(""Udemy""); list1.push_back(""Coursera""); list1.push_back(""edX""); // Creating list2 vector list2; list2.push_back(""Codecademy""); list2.push_back(""Khan Academy""); list2.push_back(""GeeksforGeeks""); find(list1, list2); return 0; }",quadratic,linear "// C++ program to count the uppercase, // lowercase, special characters // and numeric values #include using namespace std; // Function to count uppercase, lowercase, // special characters and numbers void Count(string str) { int upper = 0, lower = 0, number = 0, special = 0; for (int i = 0; i < str.length(); i++) { if (str[i] >= 'A' && str[i] <= 'Z') upper++; else if (str[i] >= 'a' && str[i] <= 'z') lower++; else if (str[i]>= '0' && str[i]<= '9') number++; else special++; } cout << ""Upper case letters: "" << upper << endl; cout << ""Lower case letters : "" << lower << endl; cout << ""Number : "" << number << endl; cout << ""Special characters : "" << special << endl; } // Driver function int main() { string str = ""#GeeKs01fOr@gEEks07""; Count(str); return 0; }",constant,linear "// C++ program to find // smallest window containing // all characters of a pattern. #include using namespace std; const int no_of_chars = 256; // Function to find smallest // window containing // all characters of 'pat' string findSubString(string str, string pat) { int len1 = str.length(); int len2 = pat.length(); // Check if string's length // is less than pattern's // length. If yes then no such // window can exist if (len1 < len2) { cout << ""No such window exists""; return """"; } int hash_pat[no_of_chars] = { 0 }; int hash_str[no_of_chars] = { 0 }; // Store occurrence ofs characters // of pattern for (int i = 0; i < len2; i++) hash_pat[pat[i]]++; int start = 0, start_index = -1, min_len = INT_MAX; // Start traversing the string // Count of characters int count = 0; for (int j = 0; j < len1; j++) { // Count occurrence of characters // of string hash_str[str[j]]++; // If string's char matches with // pattern's char // then increment count if (hash_str[str[j]] <= hash_pat[str[j]]) count++; // if all the characters are matched if (count == len2) { // Try to minimize the window while (hash_str[str[start]] > hash_pat[str[start]] || hash_pat[str[start]] == 0) { if (hash_str[str[start]] > hash_pat[str[start]]) hash_str[str[start]]--; start++; } // update window size int len_window = j - start + 1; if (min_len > len_window) { min_len = len_window; start_index = start; } } } // If no window found if (start_index == -1) { cout << ""No such window exists""; return """"; } // Return substring starting from start_index // and length min_len return str.substr(start_index, min_len); } // Driver code int main() { string str = ""this is a test string""; string pat = ""tist""; cout << findSubString(str, pat); return 0; }",constant,linear "#include using namespace std; // Function string Minimum_Window(string s, string t) { int m[256] = { 0 }; // Answer int ans = INT_MAX; // length of ans int start = 0; // starting index of ans int count = 0; // creating map for (int i = 0; i < t.length(); i++) { if (m[t[i]] == 0) count++; m[t[i]]++; } // References of Window int i = 0; int j = 0; // Traversing the window while (j < s.length()) { // Calculations m[s[j]]--; if (m[s[j]] == 0) count--; // Condition matching if (count == 0) { while (count == 0) { // Sorting ans if (ans > j - i + 1) { ans = min(ans, j - i + 1); start = i; } // Sliding I // Calculation for removing I m[s[i]]++; if (m[s[i]] > 0) count++; i++; } } j++; } if (ans != INT_MAX) return s.substr(start, ans); else return ""-1""; } int main() { string s = ""this is a test string""; string t = ""tist""; cout << Minimum_Window(s, t); return 0; }",constant,linear "// C++ program to count number of substrings with // exactly k distinct characters in a given string #include using namespace std; // Function to count number of substrings // with exactly k unique characters int countkDist(string str, int k) { int n = str.length(); // Initialize result int res = 0; // To store count of characters from 'a' to 'z' int cnt[26]; // Consider all substrings beginning with // str[i] for (int i = 0; i < n; i++) { int dist_count = 0; // Initializing array with 0 memset(cnt, 0, sizeof(cnt)); // Consider all substrings between str[i..j] for (int j=i; j k) break; } } return res; } // Driver Program int main() { string str = ""abcbaa""; int k = 3; cout << ""Total substrings with exactly "" << k <<"" distinct characters :"" << countkDist(str, k) << endl; return 0; }",constant,quadratic "#include #include #include using namespace std; // the number of subarrays with at most K distinct elements int most_k_chars(string& s, int k) { if (s.size() == 0) { return 0; } unordered_map map; int num = 0, left = 0; for (int i = 0; i < s.size(); i++) { map[s[i]]++; while (map.size() > k) { map[s[left]]--; if (map[s[left]] == 0) { map.erase(s[left]); } left++; } num += i - left + 1; } return num; } int exact_k_chars(string& s, int k) { return most_k_chars(s, k) - most_k_chars(s, k - 1); } // Driver Program int main() { string s1 = ""pqpqs""; int k = 2; cout << ""Total substrings with exactly "" << k << "" distinct characters : "" << exact_k_chars(s1, k) << endl; string s2 = ""aabab""; k = 2; cout << ""Total substrings with exactly "" << k << "" distinct characters : "" << exact_k_chars(s2, k) << endl; }",constant,linear "// C++ program to count number of substrings // with counts of distinct characters as k. #include using namespace std; const int MAX_CHAR = 26; // Returns true if all values // in freq[] are either 0 or k. bool check(int freq[], int k) { for (int i = 0; i < MAX_CHAR; i++) if (freq[i] && freq[i] != k) return false; return true; } // Returns count of substrings where frequency // of every present character is k int substrings(string s, int k) { int res = 0; // Initialize result // Pick a starting point for (int i = 0; s[i]; i++) { // Initialize all frequencies as 0 // for this starting point int freq[MAX_CHAR] = { 0 }; // One by one pick ending points for (int j = i; s[j]; j++) { // Increment frequency of current char int index = s[j] - 'a'; freq[index]++; // If frequency becomes more than // k, we can't have more substrings // starting with i if (freq[index] > k) break; // If frequency becomes k, then check // other frequencies as well. else if (freq[index] == k && check(freq, k) == true) res++; } } return res; } // Driver code int main() { string s = ""aabbcc""; int k = 2; cout << substrings(s, k) << endl; s = ""aabbc""; k = 2; cout << substrings(s, k) << endl; }",constant,quadratic "#include #include #include #include int min(int a, int b) { return a < b ? a : b; } using namespace std; bool have_same_frequency(map& freq, int k) { for (auto& pair : freq) { if (pair.second != k && pair.second != 0) { return false; } } return true; } int count_substrings(string s, int k) { int count = 0; int distinct = (set(s.begin(), s.end())).size(); for (int length = 1; length <= distinct; length++) { int window_length = length * k; map freq; int window_start = 0; int window_end = window_start + window_length - 1; for (int i = window_start; i <= min(window_end, s.length() - 1); i++) { freq[s[i]]++; } while (window_end < s.length()) { if (have_same_frequency(freq, k)) { count++; } freq[s[window_start]]--; window_start++; window_end++; if (window_length < s.length()) { freq[s[window_end]]++; } } } return count; } int main() { string s = ""aabbcc""; int k = 2; cout << count_substrings(s, k) << endl; s = ""aabbc""; k = 2; cout << count_substrings(s, k) << endl; return 0; }",linear,quadratic "// CPP program to construct a n length string // with k distinct characters such that no two // same characters are adjacent. #include using namespace std; // Function to find a string of length // n with k distinct characters. string findString(int n, int k) { // Initialize result with first k // Latin letters string res = """"; for (int i = 0; i < k; i++) res = res + (char)('a' + i); // Fill remaining n-k letters by // repeating k letters again and again. int count = 0; for (int i = 0; i < n - k; i++) { res = res + (char)('a' + count); count++; if (count == k) count = 0; } return res; } // Driver code int main() { int n = 5, k = 2; cout << findString(n, k); return 0; }",linear,linear "// CPP program to count number of substrings // of a string #include using namespace std; int countNonEmptySubstr(string str) { int n = str.length(); return n*(n+1)/2; } // driver code int main() { string s = ""abcde""; cout << countNonEmptySubstr(s); return 0; }",constant,constant "#include using namespace std; int MAX_CHAR = 26; string encodeString(char str[], int m) { // hashEven stores the count of even indexed character // for each string hashOdd stores the count of odd // indexed characters for each string int hashEven[MAX_CHAR]; int hashOdd[MAX_CHAR]; memset(hashEven,0,sizeof(hashEven)); memset(hashOdd,0,sizeof(hashOdd)); // creating hash for each string for (int i = 0; i < m; i++) { char c = str[i]; if ((i & 1) != 0) // If index of current character is odd hashOdd[c-'a']++; else hashEven[c-'a']++; } // For every character from 'a' to 'z', we store its // count at even position followed by a separator, // followed by count at odd position. string encoding = """"; for (int i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set to // store strings which are distinct according // to criteria given in question. int countDistinct(string input[], int n) { int countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. set s; for (int i = 0; i < n; i++) { // If this encoding appears first time, increment // count of distinct encodings. char char_array[input[i].length()]; strcpy(char_array, input[i].c_str()); if (s.find(encodeString(char_array, input[i].length())) == s.end()) { s.insert(encodeString(char_array,input[i].length())); countDist++; } } return countDist; } int main() { string input[] = {""abcd"", ""acbd"", ""adcb"", ""cdba"", ""bcda"", ""badc""}; int n = sizeof(input)/sizeof(input[0]); cout << countDistinct(input, n) << ""\n""; } // This code is contributed by Harshit Sharma.",constant,linear "// C++ program to find K'th character in // decrypted string #include using namespace std; // Function to find K'th character in Encoded String char encodedChar(string str,int k) { // expand string variable is used to // store final string after decompressing string str string expand = """"; string temp; // Current substring int freq = 0; // Count of current substring for (int i=0; str[i]!='\0'; ) { temp = """"; // Current substring freq = 0; // count frequency of current substring // read characters until you find a number // or end of string while (str[i]>='a' && str[i]<='z') { // push character in temp temp.push_back(str[i]); i++; } // read number for how many times string temp // will be repeated in decompressed string while (str[i]>='1' && str[i]<='9') { // generating frequency of temp freq = freq*10 + str[i] - '0'; i++; } // now append string temp into expand // equal to its frequency for (int j=1; j<=freq; j++) expand.append(temp); } // this condition is to handle the case // when string str is ended with alphabets // not with numeric value if (freq==0) expand.append(temp); return expand[k-1]; } // Driver program to test the string int main() { string str = ""ab4c12ed3""; int k = 21; cout << encodedChar(str, k) << endl; return 0; }",constant,linear "// C++ program to find number of characters at same // position as in English alphabets #include using namespace std; int findCount(string str) { int result = 0; // Traverse input string for (int i = 0 ; i < str.size(); i++) // Check that index of characters of string is // same as of English alphabets by using ASCII // values and the fact that all lower case // alphabetic characters come together in same // order in ASCII table. And same is true for // upper case. if (i == (str[i] - 'a') || i == (str[i] - 'A')) result++; return result; } // Driver code int main() { string str = ""AbgdeF""; cout << findCount(str); return 0; }",constant,linear "// C++ program to count words whose ith letter // is either (i-1)th, ith, or (i+1)th letter // of given word. #include using namespace std; // Return the count of words. int countWords(char str[], int len) { int count = 1; // If word contain single letter, return 1. if (len == 1) return count; // Checking for first letter. if (str[0] == str[1]) count *= 1; else count *= 2; // Traversing the string and multiplying // for combinations. for (int j=1; j #include using namespace std; void minMaxLengthWords(string input, string &minWord, string &maxWord) { // minWord and maxWord are received by reference // and not by value // will be used to store and return output int len = input.length(); int si = 0, ei = 0; int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input[ei] != ' ') ei++; else { // end of a word // find curr word length int curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.substr(min_start_index, min_length); maxWord = input.substr(max_start_index, max_length); } // Driver code int main() { string a = ""GeeksforGeeks A Computer Science portal for Geeks""; string minWord, maxWord; minMaxLengthWords(a, minWord, maxWord); // to take input in string use getline(cin, a); cout << ""Minimum length word: "" << minWord << endl << ""Maximum length word: "" << maxWord << endl; }",linear,linear "// Most efficient C++ program to count all // substrings with same first and last characters. #include using namespace std; const int MAX_CHAR = 26; // assuming lower case only int countSubstringWithEqualEnds(string s) { int result = 0; int n = s.length(); // Calculating frequency of each character // in the string. int count[MAX_CHAR] = {0}; for (int i=0; i using namespace std; // Structure to store information of a suffix struct suffix { int index; // To store original index int rank[2]; // To store ranks and next // rank pair }; // A comparison function used by sort() to compare // two suffixes. Compares two pairs, returns 1 if // first pair is smaller int cmp(struct suffix a, struct suffix b) { return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0); } // This is the main function that takes a string // 'txt' of size n as an argument, builds and return // the suffix array for the given string vector buildSuffixArray(string txt, int n) { // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array // of structures. The structure is needed to sort // the suffixes alphabetically and maintain their // old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At his point, all suffixes are sorted according // to first 2 characters. Let us sort suffixes // according to first 4 characters, then first // 8 and so on int ind[n]; // This array is needed to get the // index in suffixes[] from original // index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, assign // the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix // array vectorsuffixArr; for (int i = 0; i < n; i++) suffixArr.push_back(suffixes[i].index); // Return the suffix array return suffixArr; } /* To construct and return LCP */ vector kasai(string txt, vector suffixArr) { int n = suffixArr.size(); // To store LCP array vector lcp(n, 0); // An auxiliary array to store inverse of suffix array // elements. For example if suffixArr[0] is 5, the // invSuff[5] would store 0. This is used to get next // suffix string from suffix array. vector invSuff(n, 0); // Fill values in invSuff[] for (int i=0; i < n; i++) invSuff[suffixArr[i]] = i; // Initialize length of previous LCP int k = 0; // Process all suffixes one by one starting from // first suffix in txt[] for (int i=0; i0) k--; } // return the constructed lcp array return lcp; } // method to return count of total distinct substring int countDistinctSubstring(string txt) { int n = txt.length(); // calculating suffix array and lcp array vector suffixArr = buildSuffixArray(txt, n); vector lcp = kasai(txt, suffixArr); // n - suffixArr[i] will be the length of suffix // at ith position in suffix array initializing // count with length of first suffix of sorted // suffixes int result = n - suffixArr[0]; for (int i = 1; i < lcp.size(); i++) // subtract lcp from the length of suffix result += (n - suffixArr[i]) - lcp[i - 1]; result++; // For empty string return result; } // Driver code to test above methods int main() { string txt = ""ababa""; cout << countDistinctSubstring(txt); return 0; }",linear,nlogn "// A C++ program to find the count of distinct substring // of a string using trie data structure #include #define MAX_CHAR 26 using namespace std; // A Suffix Trie (A Trie of all suffixes) Node class SuffixTrieNode { public: SuffixTrieNode *children[MAX_CHAR]; SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = NULL; } // A recursive function to insert a suffix of the s // in subtree rooted with this node void insertSuffix(string suffix); }; // A Trie of all suffixes class SuffixTrie { SuffixTrieNode *root; int _countNodesInTrie(SuffixTrieNode *); public: // Constructor (Builds a trie of suffies of the given text) SuffixTrie(string s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.length(); i++) root->insertSuffix(s.substr(i)); } // method to count total nodes in suffix trie int countNodesInTrie() { return _countNodesInTrie(root); } }; // A recursive function to insert a suffix of the s in // subtree rooted with this node void SuffixTrieNode::insertSuffix(string s) { // If string has more characters if (s.length() > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = s.at(0) - 'a'; // If there is no edge for this character, // add a new edge if (children[cIndex] == NULL) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex]->insertSuffix(s.substr(1)); } } // A recursive function to count nodes in trie int SuffixTrie::_countNodesInTrie(SuffixTrieNode* node) { // If all characters of pattern have been processed, if (node == NULL) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node->children[i] != NULL) count += _countNodesInTrie(node->children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count); } // Returns count of distinct substrings of str int countDistinctSubstring(string str) { // Construct a Trie of all suffixes SuffixTrie sTrie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie(); } // Driver program to test above function int main() { string str = ""ababa""; cout << ""Count of distinct substrings is "" << countDistinctSubstring(str); return 0; }",constant,linear "// C++ program to count number of possible strings // with n characters. #include using namespace std; // Function to calculate number of strings int possibleStrings( int n, int r, int b, int g) { // Store factorial of numbers up to n // for further computation int fact[n+1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i; // Find the remaining values to be added int left = n - (r+g+b); int sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (int i = 0; i <= left; i++) { for (int j = 0; j<= left-i; j++) { int k = left - (i+j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i+r]*fact[j+b]*fact[k+g]); } } // Return total no. of strings/permutation return sum; } // Drivers code int main() { int n = 4, r = 2; int b = 0, g = 1; cout << possibleStrings(n, r, b, g); return 0; }",linear,quadratic "// C++ program to count number of strings // of n characters with #include using namespace std; // n is total number of characters. // bCount and cCount are counts of 'b' // and 'c' respectively. int countStrUtil(int dp[][2][3], int n, int bCount=1, int cCount=2) { // Base cases if (bCount < 0 || cCount < 0) return 0; if (n == 0) return 1; if (bCount == 0 && cCount == 0) return 1; // if we had saw this combination previously if (dp[n][bCount][cCount] != -1) return dp[n][bCount][cCount]; // Three cases, we choose, a or b or c // In all three cases n decreases by 1. int res = countStrUtil(dp, n-1, bCount, cCount); res += countStrUtil(dp, n-1, bCount-1, cCount); res += countStrUtil(dp, n-1, bCount, cCount-1); return (dp[n][bCount][cCount] = res); } // A wrapper over countStrUtil() int countStr(int n) { int dp[n+1][2][3]; memset(dp, -1, sizeof(dp)); return countStrUtil(dp, n); } // Driver code int main() { int n = 3; // Total number of characters cout << countStr(n); return 0; }",linear,linear "// A O(1) CPP program to find number of strings // that can be made under given constraints. #include using namespace std; int countStr(int n){ int count = 0; if(n>=1){ //aaa... count += 1; //b...aaa... count += n; //c...aaa... count += n; if(n>=2){ //bc...aaa... count += n*(n-1); //cc...aaa... count += n*(n-1)/2; if(n>=3){ //bcc...aaa... count += (n-2)*(n-1)*n/2; } } } return count; } // Driver code int main() { int n = 3; cout << countStr(n); return 0; }",constant,constant "// C++ program to find count of substring containing // exactly K ones #include using namespace std; // method returns total number of substring having K ones int countOfSubstringWithKOnes(string s, int K) { int N = s.length(); int res = 0; int countOfOne = 0; int freq[N + 1] = {0}; // initialize index having zero sum as 1 freq[0] = 1; // loop over binary characters of string for (int i = 0; i < N; i++) { // update countOfOne variable with value // of ith character countOfOne += (s[i] - '0'); // if value reaches more than K, then // update result if (countOfOne >= K) { // add frequency of indices, having // sum (current sum - K), to the result res += freq[countOfOne - K]; } // update frequency of one's count freq[countOfOne]++; } return res; } // Driver code to test above methods int main() { string s = ""10010""; int K = 1; cout << countOfSubstringWithKOnes(s, K) << endl; return 0; }",linear,linear "// C++ program to print all words that have // the same unique character set #include using namespace std; #define MAX_CHAR 26 // Generates a key from given string. The key // contains all unique characters of given string in // sorted order consisting of only distinct elements. string getKey(string &str) { bool visited[MAX_CHAR] = { false }; // store all unique characters of current // word in key for (int j = 0; j < str.length(); j++) visited[str[j] - 'a'] = true ; string key = """"; for (int j=0; j < MAX_CHAR; j++) if (visited[j]) key = key + (char)('a'+j); return key; } // Print all words together with same character sets. void wordsWithSameCharSet(string words[], int n) { // Stores indexes of all words that have same // set of unique characters. unordered_map > Hash; // Traverse all words for (int i=0; i using namespace std; int main() { string s1 = ""geeksforgeeks""; string s2 = ""practiceforgeeks""; // to store the count of // letters in the first string int a1[26] = {0}; // to store the count of // letters in the second string int a2[26] = {0}; int i , j; char ch; char ch1 = 'a'; int k = (int)ch1, m; // for each letter present, increment the count for(i = 0 ; i < s1.length() ; i++) { a1[(int)s1[i] - k]++; } for(i = 0 ; i < s2.length() ; i++) { a2[(int)s2[i] - k]++; } for(i = 0 ; i < 26 ; i++) { // the if condition guarantees that // the element is common, that is, // a1[i] and a2[i] are both non zero // means that the letter has occurred // at least once in both the strings if (a1[i] != 0 and a2[i] != 0) { // print the letter for a number // of times that is the minimum // of its count in s1 and s2 for(j = 0 ; j < min(a1[i] , a2[i]) ; j++) { m = k + i; ch = (char)(k + i); cout << ch; } } } return 0; }",constant,linear "// CPP Program to find all the common characters // in n strings #include using namespace std; const int MAX_CHAR = 26; void commonCharacters(string str[], int n) { // primary array for common characters // we assume all characters are seen before. bool prim[MAX_CHAR]; memset(prim, true, sizeof(prim)); // for each string for (int i = 0; i < n; i++) { // secondary array for common characters // Initially marked false bool sec[MAX_CHAR] = { false }; // for every character of ith string for (int j = 0; str[i][j]; j++) { // if character is present in all // strings before, mark it. if (prim[str[i][j] - 'a']) sec[str[i][j] - 'a'] = true; } // copy whole secondary array into primary memcpy(prim, sec, MAX_CHAR); } // displaying common characters for (int i = 0; i < 26; i++) if (prim[i]) printf(""%c "", i + 'a'); } // Driver's Code int main() { string str[] = { ""geeksforgeeks"", ""gemkstones"", ""acknowledges"", ""aguelikes"" }; int n = sizeof(str)/sizeof(str[0]); commonCharacters(str, n); return 0; }",constant,linear "// C++ implementation to find the uncommon // characters of the two strings #include using namespace std; // function to find the uncommon characters // of the two strings void findAndPrintUncommonChars(string str1, string str2) { // to store the answer string ans = """"; // to handle the case of duplicates vector used(26, false); // check first for str1 for (int i = 0; i < str1.size(); i++) { // keeping a flag variable bool found = false; for (int j = 0; j < str2.size(); j++) { // if found change the flag // and break from loop if (str1[i] == str2[j]) { found = true; break; } } // if duplicate character not found // then add it to ans if (!found and !used[str1[i] - 'a']) { used[str1[i] - 'a'] = true; ans += str1[i]; } } // now check for str2 for (int i = 0; i < str2.size(); i++) { // keeping a flag variable bool found = false; for (int j = 0; j < str1.size(); j++) { // if found change the flag // and break from loop if (str2[i] == str1[j]) { found = true; break; } } // if duplicate character not found // then add it to ans if (!found and !used[str2[i] - 'a']) { used[str2[i] - 'a'] = true; ans += str2[i]; } } // to match with output sort(ans.begin(), ans.end()); // if not found any character if (ans.size() == 0) cout << ""-1""; // else print the answer else cout << ans << "" ""; } // Driver program to test above int main() { string str1 = ""characters""; string str2 = ""alphabets""; findAndPrintUncommonChars(str1, str2); return 0; }",constant,quadratic "// C++ implementation to find the uncommon // characters of the two strings #include using namespace std; // size of the hash table const int MAX_CHAR = 26; // function to find the uncommon characters // of the two strings void findAndPrintUncommonChars(string str1, string str2) { // mark presence of each character as 0 // in the hash table 'present[]' int present[MAX_CHAR]; for (int i=0; i using namespace std; string UncommonChars(string a, string b) { int mp1[26] = {0}, mp2[26] = {0}; int n = a.size(), m = b.size(); for(auto &x: a){ mp1[x-'a'] = 1; } for(auto &x: b){ mp2[x-'a'] = 1; } string chars = """"; for(int i = 0; i < 26; ++i){ if(mp1[i]^mp2[i]) chars+=char(i+'a'); } if(chars == """") return ""-1""; else return chars; } int main(){ string a = ""geeksforgeeks""; string b = ""geeksquiz""; string result = UncommonChars(a,b); cout << result << endl; return 0; }",constant,linear "// C++ program Find concatenated string with // uncommon characters of given strings #include using namespace std; string concatenatedString(string s1, string s2) { string res = """"; // result // store all characters of s2 in map unordered_map m; for (int i = 0; i < s2.size(); i++) m[s2[i]] = 1; // Find characters of s1 that are not // present in s2 and append to result for (int i = 0; i < s1.size(); i++) { if (m.find(s1[i]) == m.end()) res += s1[i]; else m[s1[i]] = 2; } // Find characters of s2 that are not // present in s1. for (int i = 0; i < s2.size(); i++) if (m[s2[i]] == 1) res += s2[i]; return res; } /* Driver program to test above function */ int main() { string s1 = ""abcs""; string s2 = ""cxzca""; cout << concatenatedString(s1, s2); return 0; }",linear,linear "// C++ program to remove vowels from a String #include using namespace std; string remVowel(string str) { vector vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; for (int i = 0; i < str.length(); i++) { if (find(vowels.begin(), vowels.end(), str[i]) != vowels.end()) { str = str.replace(i, 1, """"); i -= 1; } } return str; } // Driver Code int main() { string str = ""GeeeksforGeeks - A Computer"" "" Science Portal for Geeks""; cout << remVowel(str) << endl; return 0; } // This code is contributed by // sanjeev2552 // and corrected by alreadytaken",constant,linear "// C++ program to remove vowels from a String #include using namespace std; string remVowel(string str) { regex r(""[aeiouAEIOU]""); return regex_replace(str, r, """"); } // Driver Code int main() { string str = ""GeeeksforGeeks - A Computer Science Portal for Geeks""; cout << (remVowel(str)); return 0; } // This code is contributed by Arnab Kundu",constant,linear "// C++ program for printing sentence // without repetitive vowels #include using namespace std; // function which returns True or False // for occurrence of a vowel bool is_vow(char c) { // this compares vowel with // character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u'); } // function to print resultant string void removeVowels(string str) { // print 1st character printf(""%c"", str[0]); // loop to check for each character for (int i = 1; str[i]; i++) // comparison of consecutive characters if ((!is_vow(str[i - 1])) || (!is_vow(str[i]))) printf(""%c"", str[i]); } // Driver Code int main() { char str[] = "" geeks for geeks""; removeVowels(str); } // This code is contributed by Abhinav96",linear,linear "// C++ program to count vowels in a string #include using namespace std; // Function to check the Vowel bool isVowel(char ch) { ch = toupper(ch); return (ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U'); } // Returns count of vowels in str int countVowels(string str) { int count = 0; for (int i=0; i using namespace std; // Function to check the Vowel bool isVowel(char ch) { ch = toupper(ch); return (ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U'); } // to count total number of vowel from 0 to n int countVovels(string str, int n) { if (n == 1) return isVowel(str[n-1]); return countVovels(str, n-1) + isVowel(str[n-1]); } // Main Calling Function int main() { // string object string str = ""abc de""; // Total numbers of Vowel cout << countVovels(str, str.length()) << endl; return 0; }",linear,linear "// Iterative CPP program to count total number // of consonants #include using namespace std; // Function to check for consonant bool isConsonant(char ch) { // To handle lower case ch = toupper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90; } int totalConsonants(string str) { int count = 0; for (int i = 0; i < str.length(); i++) // To check is character is Consonant if (isConsonant(str[i])) ++count; return count; } // Driver code int main() { string str = ""abc de""; cout << totalConsonants(str); return 0; }",constant,linear "// Recursive CPP program to count total number // of consonants #include using namespace std; // Function to check for consonant bool isConsonant(char ch) { // To handle lower case ch = toupper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90; } // to count total number of consonants from // 0 to n-1 int totalConsonants(string str, int n) { if (n == 1) return isConsonant(str[0]); return totalConsonants(str, n - 1) + isConsonant(str[n-1]); } // Driver code int main() { string str = ""abc de""; cout << totalConsonants(str, str.length()); return 0; }",linear,linear "// C++ program to find number of distinct // permutations of a string. #include using namespace std; const int MAX_CHAR = 26; // Utility function to find factorial of n. int factorial(int n) { int fact = 1; for (int i = 2; i <= n; i++) fact = fact * i; return fact; } // Returns count of distinct permutations // of str. int countDistinctPermutations(string str) { int length = str.length(); int freq[MAX_CHAR]; memset(freq, 0, sizeof(freq)); // finding frequency of all the lower case // alphabet and storing them in array of // integer for (int i = 0; i < length; i++) if (str[i] >= 'a') freq[str[i] - 'a']++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets int fact = 1; for (int i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return factorial(length) / fact; } // Driver code int main() { string str = ""fvvfhvgv""; printf(""%d"", countDistinctPermutations(str)); return 0; }",linear,linear "// C++ program to print all permutations with // duplicates allowed using rotate() in STL #include using namespace std; // Function to print permutations of string str, // out is used to store permutations one by one void permute(string str, string out) { // When size of str becomes 0, out has a // permutation (length of out is n) if (str.size() == 0) { cout << out << endl; return; } // One be one move all characters at // the beginning of out (or result) for (int i = 0; i < str.size(); i++) { // Remove first character from str and // add it to out permute(str.substr(1), out + str[0]); // Rotate string in a way second character // moves to the beginning. rotate(str.begin(), str.begin() + 1, str.end()); } } // Driver code int main() { string str = ""ABC""; permute(str, """"); return 0; }",linear,np "// C++ program to print all permutations with // duplicates allowed using next_permutation #include using namespace std; // Function to print permutations of string str // using next_permutation void permute(string str) { // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep printing next permutation while there // is next permutation do { cout << str << endl; } while (next_permutation(str.begin(), str.end())); } // Driver code int main() { string str = ""CBA""; permute(str); return 0; }",constant,np "// C++ program to check if it is // possible to split string or not #include using namespace std; const int MAX_CHAR = 26; // function to check if we can split // string or not bool checkCorrectOrNot(string s) { // Counter array initialized with 0 int count1[MAX_CHAR] = {0}; int count2[MAX_CHAR] = {0}; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i=0,j=n-1; i using namespace std; const int MAX_CHAR = 26; // function to check if we can split // string or not bool checkCorrectOrNot(string s) { // Counter array initialized with 0 int count[MAX_CHAR] = {0}; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i=0,j=n-1; i using namespace std; // function to find the minimum index character void printMinIndexChar(string str, string patt) { // to store the index of character having // minimum index int minIndex = INT_MAX; // lengths of the two strings int m = str.size(); int n = patt.size(); // traverse 'patt' for (int i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (int j = 0; j < m; j++) { // if patt[i] is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt[i] == str[j] && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != INT_MAX) cout << ""Minimum Index Character = "" << str[minIndex]; // if no character of 'patt' is present in 'str' else cout << ""No character present""; } // Driver program to test above int main() { string str = ""geeksforgeeks""; string patt = ""set""; printMinIndexChar(str, patt); return 0; }",constant,quadratic "// C++ implementation to find the character in first // string that is present at minimum index in second // string #include using namespace std; // function to find the minimum index character void printMinIndexChar(string str, string patt) { // unordered_map 'um' implemented as hash table unordered_map um; // to store the index of character having // minimum index int minIndex = INT_MAX; // lengths of the two strings int m = str.size(); int n = patt.size(); // store the first index of each character of 'str' for (int i = 0; i < m; i++) { if (um.find(str[i]) == um.end()) um[str[i]] = i; } // traverse the string 'patt' for (int j = 0; j < n; j++) { // if patt[i] is found in 'um', check if // it has the minimum index or not accordingly // update 'minIndex' if (um.find(patt[j]) != um.end() && um[patt[j]] < minIndex) minIndex = um[patt[j]]; } // print the minimum index character if (minIndex != INT_MAX) cout << ""Minimum Index Character = "" << str[minIndex]; // if no character of 'patt' is present in 'str' else cout << ""No character present""; } // Driver program to test above int main() { string str = ""geeksforgeeks""; string patt = ""set""; printMinIndexChar(str, patt); return 0; }",linear,linear "// C++ implementation of program to find the maximum length // that can be removed #include using namespace std; // Function to find the length of longest sub-string that // can me make removed // arr --> pair type of array whose first field store // character in string and second field stores // corresponding index of that character int longestNull(string str) { vector > arr; // store {'@',-1} in arr , here this value will // work as base index arr.push_back({'@', -1}); int maxlen = 0; // Initialize result // one by one iterate characters of string for (int i = 0; i < str.length(); ++i) { // make pair of char and index , then store // them into arr arr.push_back({str[i], i}); // now if last three elements of arr[] are making // sub-string ""100"" or not while (arr.size()>=3 && arr[arr.size()-3].first=='1' && arr[arr.size()-2].first=='0' && arr[arr.size()-1].first=='0') { // if above condition is true then delete // sub-string ""100"" from arr[] arr.pop_back(); arr.pop_back(); arr.pop_back(); } // index of current last element in arr[] int tmp = arr.back().second; // This is important, here 'i' is the index of // current character inserted into arr[] // and 'tmp' is the index of last element in arr[] // after continuous deletion of sub-string // ""100"" from arr[] till we make it null, difference // of these to 'i-tmp' gives the length of current // sub-string that can be make null by continuous // deletion of sub-string ""100"" maxlen = max(maxlen, i - tmp); } return maxlen; } // Driver program to run the case int main() { cout << longestNull(""1011100000100""); return 0; }",linear,linear "// CPP program to count the number of pairs #include using namespace std; #define MAX 256 // Function to count the number of equal pairs int countPairs(string s) { // Hash table int cnt[MAX] = { 0 }; // Traverse the string and count occurrence for (int i = 0; i < s.length(); i++) cnt[s[i]]++; // Stores the answer int ans = 0; // Traverse and check the occurrence of every character for (int i = 0; i < MAX; i++) ans += cnt[i] * cnt[i]; return ans; } // Driver Code int main() { string s = ""geeksforgeeks""; cout << countPairs(s); return 0; }",linear,linear "// CPP Program to count strings with adjacent // characters. #include using namespace std; int countStrs(int n) { long int dp[n + 1][27]; // Initializing arr[n+1][27] to 0 memset(dp, 0, sizeof(dp)); // Initialing 1st row all 1 from 0 to 25 for (int i = 0; i <= 25; i++) dp[1][i] = 1; // Begin evaluating from i=2 since 1st row is set for (int i = 2; i <= n; i++) { for (int j = 0; j <= 25; j++) // j=0 is 'A' which can make strings // of length i using strings of length // i-1 and starting with 'B' if (j == 0) dp[i][j] = dp[i - 1][j + 1]; else dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]); } // Our result is sum of last row. long int sum = 0; for (int i = 0; i <= 25; i++) sum = (sum + dp[n][i]); return sum; } // Driver's Code int main() { int n = 3; cout << ""Total strings are : "" << countStrs(n); return 0; }",linear,linear "// C++ program to print Number of Words, // Vowels and Frequency of Each Character #include using namespace std; void words(string str) { int wcount = 0, ucount = 0, vcount = 0; for (int i = 0; i < str.length(); i++) { char c = str[i]; switch (c) { case ' ': case '.': wcount++; // more delimiters can be given } switch (c) { case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': vcount++; } if (c >= 65 and c <= 90) ucount++; } cout << ""Number of words = "" << wcount << endl; cout << ""Number of vowels = "" << vcount << endl; cout << ""Number of upper case characters = "" << ucount << endl; } // Function to calculate the frequency // of each character in the string void frequency(string str) { // Creates an empty TreeMap map hmap; // Traverse through the given array for (int i = 0; i < str.length(); i++) hmap[str[i]]++; // Print result for (auto i : hmap) { cout << ""Character = "" << i.first; cout << "" Frequency = "" << i.second << endl; } } // Driver Code int main(int argc, char const *argv[]) { string str = ""Geeks for Geeks.""; words(str); frequency(str); return 0; } // This code is contributed by // sanjeev2552",constant,linear "// C++ program to Find longest subsequence where // every character appears at-least k times #include using namespace std; const int MAX_CHARS = 26; void longestSubseqWithK(string str, int k) { int n = str.size(); // Count frequencies of all characters int freq[MAX_CHARS] = {0}; for (int i = 0 ; i < n; i++) freq[str[i] - 'a']++; // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0 ; i < n ; i++) if (freq[str[i] - 'a'] >= k) cout << str[i]; } // Driver code int main() { string str = ""geeksforgeeks""; int k = 2; longestSubseqWithK(str, k); return 0; }",linear,linear "// C++ program to Find longest subsequence where every // character appears at-least k times #include using namespace std; void longestSubseqWithK(string str, int k) { int n = str.size(); map mp; // Count frequencies of all characters for (int i = 0; i < n; i++) { char t = str[i]; mp[t]++; } // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0; i < n; i++) { char t = str[i]; if (mp[t] >= k) { cout << t; } } } // Driver code int main() { string str = ""geeksforgeeks""; int k = 2; longestSubseqWithK(str, k); return 0; } // This code is contributed by rakeshsahni",linear,nlogn "// Recursive C++ program to check // if a string is subsequence // of another string #include #include using namespace std; // Returns true if str1[] is a // subsequence of str2[]. m is // length of str1 and n is length of str2 bool isSubSequence(char str1[], char str2[], int m, int n) { // Base Cases if (m == 0) return true; if (n == 0) return false; // If last characters of two // strings are matching if (str1[m - 1] == str2[n - 1]) return isSubSequence(str1, str2, m - 1, n - 1); // If last characters are // not matching return isSubSequence(str1, str2, m, n - 1); } // Driver program to check whether str1 is subsequence of str2 or not. int main() { char str1[] = ""gksrek""; char str2[] = ""geeksforgeeks""; int m = strlen(str1); int n = strlen(str2); isSubSequence(str1, str2, m, n) ? cout << ""Yes "" : cout << ""No""; return 0; }",linear,linear "/*Iterative C++ program to check If a string is subsequence of another string*/ #include using namespace std; /*Returns true if s1 is subsequence of s2*/ bool issubsequence(string& s1, string& s2) { int n = s1.length(), m = s2.length(); int i = 0, j = 0; while (i < n && j < m) { if (s1[i] == s2[j]) i++; j++; } /*If i reaches end of s1,that mean we found all characters of s1 in s2, so s1 is subsequence of s2, else not*/ return i == n; } int main() { string s1 = ""gksrek""; string s2 = ""geeksforgeeks""; if (issubsequence(s1, s2)) cout << ""gksrek is subsequence of geekforgeeks"" << endl; else cout << ""gksrek is not a subsequence of geekforgeeks"" << endl; return 0; }",constant,linear "// C++ program to count subsequences of the // form a^i b^j c^k #include using namespace std; // Returns count of subsequences of the form // a^i b^j c^k int countSubsequences(string s) { // Initialize counts of different subsequences // caused by different combination of 'a' int aCount = 0; // Initialize counts of different subsequences // caused by different combination of 'a' and // different combination of 'b' int bCount = 0; // Initialize counts of different subsequences // caused by different combination of 'a', 'b' // and 'c'. int cCount = 0; // Traverse all characters of given string for (unsigned int i = 0; i < s.size(); i++) { /* If current character is 'a', then there are the following possibilities : a) Current character begins a new subsequence. b) Current character is part of aCount subsequences. c) Current character is not part of aCount subsequences. */ if (s[i] == 'a') aCount = (1 + 2 * aCount); /* If current character is 'b', then there are following possibilities : a) Current character begins a new subsequence of b's with aCount subsequences. b) Current character is part of bCount subsequences. c) Current character is not part of bCount subsequences. */ else if (s[i] == 'b') bCount = (aCount + 2 * bCount); /* If current character is 'c', then there are following possibilities : a) Current character begins a new subsequence of c's with bCount subsequences. b) Current character is part of cCount subsequences. c) Current character is not part of cCount subsequences. */ else if (s[i] == 'c') cCount = (bCount + 2 * cCount); } return cCount; } // Driver code int main() { string s = ""abbc""; cout << countSubsequences(s) << endl; return 0; }",constant,linear "// C++ program to count subsequences of a // string divisible by n. #include using namespace std; // Returns count of subsequences of str // divisible by n. int countDivisibleSubseq(string str, int n) { int len = str.length(); // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. int dp[len][n]; memset(dp, 0, sizeof(dp)); // Filling value for first digit in str dp[0][(str[0]-'0')%n]++; for (int i=1; i using namespace std; #define MAX 100 // Print the count of ""GFG"" subsequence in the string void countSubsequence(char s[], int n) { int cntG = 0, cntF = 0, result = 0, C=0; // Traversing the given string for (int i = 0; i < n; i++) { switch (s[i]) { // If the character is 'G', increment // the count of 'G', increase the result // and update the array. case 'G': cntG++; result+=C; break; // If the character is 'F', increment // the count of 'F' and update the array. case 'F': cntF++; C+=cntG; break; // Ignore other character. default: continue; } } cout << result << endl; } // Driven Program int main() { char s[] = ""GFGFG""; int n = strlen(s); countSubsequence(s, n); return 0; }",constant,linear "// C++ program to print distinct // subsequences of a given string #include using namespace std; // Create an empty set to store the subsequences unordered_set sn; // Function for generating the subsequences void subsequences(char s[], char op[], int i, int j) { // Base Case if (s[i] == '\0') { op[j] = '\0'; // Insert each generated // subsequence into the set sn.insert(op); return; } // Recursive Case else { // When a particular character is taken op[j] = s[i]; subsequences(s, op, i + 1, j + 1); // When a particular character isn't taken subsequences(s, op, i + 1, j); return; } } // Driver Code int main() { char str[] = ""ggg""; int m = sizeof(str) / sizeof(char); int n = pow(2, m) + 1; // Output array for storing // the generating subsequences // in each call char op[m+1]; //extra one for having \0 at the end // Function Call subsequences(str, op, 0, 0); // Output will be the number // of elements in the set cout << sn.size(); sn.clear(); return 0; // This code is contributed by Kishan Mishra }",linear,np "// C++ program to count number of distinct // subsequences of a given string. #include using namespace std; const int MAX_CHAR = 256; // Returns count of distinct subsequences of str. int countSub(string str) { // Create an array to store index // of last vector last(MAX_CHAR, -1); // Length of input string int n = str.length(); // dp[i] is going to store count of distinct // subsequences of length i. int dp[n + 1]; // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for (int i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[str[i - 1]] != -1) dp[i] = dp[i] - dp[last[str[i - 1]]]; // Mark occurrence of current character last[str[i - 1]] = (i - 1); } return dp[n]; } // Driver code int main() { cout << countSub(""gfg""); return 0; }",linear,linear "// C++ program for above approach #include using namespace std; // Returns count of distinct // subsequences of str. int countSub(string s) { map Map; // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { Map[s[i]] = -1; } int allCount = 0; int levelCount = 0; // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { char c = s[i]; // Check if i equal to 0 if (i == 0) { allCount = 1; Map = 1; levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if (Map < 0) { allCount = allCount + levelCount; } else { allCount = allCount + levelCount - Map; } Map = levelCount; } // Return answer return allCount; } // Driver code int main() { string list[] = { ""abab"", ""gfg"" }; for(string s : list) { int cnt = countSub(s); int withEmptyString = cnt + 1; cout << ""With empty string count for "" << s << "" is "" << withEmptyString << endl; cout << ""Without empty string count for "" << s << "" is "" << cnt << endl; } return 0; } // This code is contributed by divyeshrabadiya07",constant,linear "// C++ program to find LCS with permutations allowed #include using namespace std; // Function to calculate longest string // str1 --> first string // str2 --> second string // count1[] --> hash array to calculate frequency // of characters in str1 // count[2] --> hash array to calculate frequency // of characters in str2 // result --> resultant longest string whose // permutations are sub-sequence of given two strings void longestString(string str1, string str2) { int count1[26] = {0}, count2[26]= {0}; // calculate frequency of characters for (int i=0; i using namespace std; #define MAX 1005 // Returns length of shortest common subsequence int shortestSeq(char *S, char *T) { int m = strlen(S), n = strlen(T); // declaring 2D array of m + 1 rows and // n + 1 columns dynamically int dp[m+1][n+1]; // T string is empty for (int i = 0; i <= m; i++) dp[i][0] = 1; // S string is empty for (int i = 0; i <= n; i++) dp[0][i] = MAX; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { char ch = S[i-1]; int k; for (k = j-1; k >= 0; k--) if (T[k] == ch) break; // char not present in T if (k == -1) dp[i][j] = 1; else dp[i][j] = min(dp[i-1][j], dp[i-1][k] + 1); } } int ans = dp[m][n]; if (ans >= MAX) ans = -1; return ans; } // Driver program to test the above function int main() { char S[] = ""babab""; char T[] = ""babba""; int m = strlen(S), n = strlen(T); cout << ""Length of shortest subsequence is : "" << shortestSeq(S, T) << endl; }",quadratic,cubic "// C++ program to sort a string according to the // order defined by a pattern string #include using namespace std; const int MAX_CHAR = 26; // Sort str according to the order defined by pattern. void sortByPattern(string& str, string pat) { // Create a count array store count of characters in str. int count[MAX_CHAR] = { 0 }; // Count number of occurrences of each character // in str. for (int i = 0; i < str.length(); i++) count[str[i] - 'a']++; // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. int index = 0; for (int i = 0; i < pat.length(); i++) for (int j = 0; j < count[pat[i] - 'a']; j++) str[index++] = pat[i]; } // Driver code int main() { string pat = ""bca""; string str = ""abc""; sortByPattern(str, pat); cout << str; return 0; }",constant,linear "#include using namespace std; // Declaring a vector globally that stores which character // is occurring first vector position(26, -1); //Comparator function bool cmp(char& char1, char& char2) { return position[char1 - 'a'] < position[char2 - 'a']; } int main() { // Pattern string pat = ""wcyuogmlrdfphitxjakqvzbnes""; for (int i = 0; i < pat.length(); i++) { if (position[pat[i] - 'a'] == -1) position[pat[i] - 'a'] = i; } // String to be sorted string str = ""jcdokai""; // Passing a comparator to sort function sort(str.begin(), str.end(), cmp); cout << str; }",constant,nlogn "// C++ program to find largest word in Dictionary // by deleting some characters of given string #include using namespace std; // Returns true if str1[] is a subsequence of str2[]. // m is length of str1 and n is length of str2 bool isSubSequence(string str1, string str2) { int m = str1.length(), n = str2.length(); int j = 0; // For index of str1 (or subsequence // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (int i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; // If all characters of str1 were found in str2 return (j == m); } // Returns the longest string in dictionary which is a // subsequence of str. string findLongestString(vector dict, string str) { string result = """"; int length = 0; // Traverse through all words of dictionary for (string word : dict) { // If current word is subsequence of str and is // largest such word so far. if (length < word.length() && isSubSequence(word, str)) { result = word; length = word.length(); } } // Return longest string return result; } // Driver program to test above function int main() { vector dict = { ""ale"", ""apple"", ""monkey"", ""plea"" }; string str = ""abpcplea""; cout << findLongestString(dict, str) << endl; return 0; }",constant,quadratic "// C++ program to check if a string is perfect // reversible or nor #include using namespace std; // This function basically checks if string is // palindrome or not bool isReversible(string str) { int i = 0, j = str.length()-1; // iterate from left and right while (i < j) { if (str[i] != str[j]) return false; i++; j--; } return true; } // Driver program to run the case int main() { string str=""aba""; if (isReversible(str)) cout << ""YES""; else cout << ""NO""; return 0; }",constant,linear "// C++ program to reverse an equation #include using namespace std; // Function to reverse order of words string reverseEquation(string s) { // Resultant string string result; int j = 0; for (int i = 0; i < s.length(); i++) { // A space marks the end of the word if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '*') { // insert the word at the beginning // of the result string result.insert(result.begin(), s.begin() + j, s.begin() + i); j = i + 1; // insert the symbol result.insert(result.begin(), s[i]); } } // insert the last word in the string // to the result string result.insert(result.begin(), s.begin() + j, s.end()); return result; } // driver code int main() { string s = ""a+b*c-d/e""; cout << reverseEquation(s) << endl; return 0; }",linear,linear "// C program for Left Rotation and Right // Rotation of a String #include using namespace std; // In-place rotates s towards left by d void leftrotate(string &s, int d) { reverse(s.begin(), s.begin()+d); reverse(s.begin()+d, s.end()); reverse(s.begin(), s.end()); } // In-place rotates s towards right by d void rightrotate(string &s, int d) { leftrotate(s, s.length()-d); } // Driver code int main() { string str1 = ""GeeksforGeeks""; leftrotate(str1, 2); cout << str1 << endl; string str2 = ""GeeksforGeeks""; rightrotate(str2, 2); cout << str2 << endl; return 0; }",constant,linear "// C++ program for Left Rotation and Right // Rotation of a String #include using namespace std; // Rotating the string using extended string string leftrotate(string str1, int n) { // creating extended string and index for new rotated // string string temp = str1 + str1; int l1 = str1.size(); string Lfirst = temp.substr(n, l1); // now returning string return Lfirst; } // Rotating the string using extended string string rightrotate(string str1, int n) { return leftrotate(str1, str1.size() - n); } // Driver code int main() { string str1 = leftrotate(""GeeksforGeeks"", 2); cout << str1 << endl; string str2 = rightrotate(""GeeksforGeeks"", 2); cout << str2 << endl; return 0; }",linear,linear "// A simple C++ program to generate all rotations // of a given string #include using namespace std; // Print all the rotated string. void printRotatedString(char str[]) { int len = strlen(str); // Generate all rotations one by one and print char temp[len]; for (int i = 0; i < len; i++) { int j = i; // Current index in str int k = 0; // Current index in temp // Copying the second part from the point // of rotation. while (str[j] != '\0') { temp[k] = str[j]; k++; j++; } // Copying the first part from the point // of rotation. j = 0; while (j < i) { temp[k] = str[j]; j++; k++; } printf(""%s\n"", temp); } } // Driven Program int main() { char str[] = ""geeks""; printRotatedString(str); return 0; }",linear,quadratic "// An efficient C++ program to print all // rotations of a string. #include using namespace std; // Print all the rotated string. void printRotatedString(char str[]) { int n = strlen(str); // Concatenate str with itself char temp[2*n + 1]; strcpy(temp, str); strcat(temp, str); // Print all substrings of size n. // Note that size of temp is 2n for (int i = 0; i < n; i++) { for (int j=0; j != n; j++) printf(""%c"",temp[i + j]); printf(""\n""); } } // Driven Program int main() { char str[] = ""geeks""; printRotatedString(str); return 0; }",linear,quadratic "// C++ program to determine minimum number // of rotations required to yield same // string. #include using namespace std; // Returns count of rotations to get the // same string back. int findRotations(string str) { // tmp is the concatenated string. string tmp = str + str; int n = str.length(); for (int i = 1; i <= n; i++) { // substring from i index of original // string size. string substring = tmp.substr(i, str.size()); // if substring matches with original string // then we will come out of the loop. if (str == substring) return i; } return n; } // Driver code int main() { string str = ""abc""; cout << findRotations(str) << endl; return 0; }",linear,quadratic "// C++ program to determine minimum number // of rotations required to yield same // string. #include using namespace std; // Returns count of rotations to get the // same string back. int findRotations(string str) { int ans = 0; //to store the answer int n = str.length(); //length of the string //All the length where we can partition for(int i=1;i using namespace std; // Driver program int main() { string String = ""aaaa""; string check = """"; for(int r = 1; r < String.length() + 1; r++) { // checking the input after each rotation check = String.substr(0, r) + String.substr(r, String.length()-r); // following if statement checks if input is // equals to check , if yes it will print r and // break out of the loop if(check == String){ cout< using namespace std; bool isRotation(string a, string b) { int n = a.length(); int m = b.length(); if (n != m) return false; // create lps[] that // will hold the longest // prefix suffix values // for pattern int lps[n]; // length of the previous // longest prefix suffix int len = 0; int i = 1; // lps[0] is always 0 lps[0] = 0; // the loop calculates // lps[i] for i = 1 to n-1 while (i < n) { if (a[i] == b[len]) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // Match from that rotating // point for (int k = lps[n - 1]; k < m; ++k) { if (b[k] != a[i++]) return false; } return true; } // Driver code int main() { string s1 = ""ABACD""; string s2 = ""CDABA""; cout << (isRotation(s1, s2) ? ""1"" : ""0""); } // This code is contributed by Chitranayal",linear,linear "// C++ program to check if a string is two time // rotation of another string. #include using namespace std; // Function to check if string2 is obtained by // string 1 bool isRotated(string str1, string str2) { if (str1.length() != str2.length()) return false; if(str1.length()<2){ return str1.compare(str2) == 0; } string clock_rot = """"; string anticlock_rot = """"; int len = str2.length(); // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.substr(len-2, 2) + str2.substr(0, len-2) ; // Initialize string as clock wise rotation clock_rot = clock_rot + str2.substr(2) + str2.substr(0, 2) ; // check if any of them is equal to string1 return (str1.compare(clock_rot) == 0 || str1.compare(anticlock_rot) == 0); } // Driver code int main() { string str1 = ""geeks""; string str2 = ""eksge""; isRotated(str1, str2) ? cout << ""Yes"" : cout << ""No""; return 0; }",linear,linear "// C++ program to count all rotation divisible // by 4. #include using namespace std; // Returns count of all rotations divisible // by 4 int countRotations(string n) { int len = n.length(); // For single digit number if (len == 1) { int oneDigit = n.at(0)-'0'; if (oneDigit%4 == 0) return 1; return 0; } // At-least 2 digit number (considering all // pairs) int twoDigit, count = 0; for (int i=0; i<(len-1); i++) { twoDigit = (n.at(i)-'0')*10 + (n.at(i+1)-'0'); if (twoDigit%4 == 0) count++; } // Considering the number formed by the pair of // last digit and 1st digit twoDigit = (n.at(len-1)-'0')*10 + (n.at(0)-'0'); if (twoDigit%4 == 0) count++; return count; } //Driver program int main() { string n = ""4834""; cout << ""Rotations: "" << countRotations(n) << endl; return 0; }",constant,linear "// C++ program to check if all rows of a matrix // are rotations of each other #include using namespace std; const int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1] // are rotations of each other. bool isPermutedMatrix( int mat[MAX][MAX], int n) { // Creating a string that contains elements of first // row. string str_cat = """"; for (int i = 0 ; i < n ; i++) str_cat = str_cat + ""-"" + to_string(mat[0][i]); // Concatenating the string with itself so that // substring search operations can be performed on // this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i=1; i using namespace std; string wordReverse(string str) { int i = str.length() - 1; int start, end = i + 1; string result = """"; while (i >= 0) { if (str[i] == ' ') { start = i + 1; while (start != end) result += str[start++]; result += ' '; end = i; } i--; } start = 0; while (start != end) result += str[start++]; return result; } // Driver code int main() { string str = ""I AM A GEEK""; cout << wordReverse(str); return 0; } // This code is contributed // by Imam",linear,linear "#include #include #include using namespace std; string reverse_words(string s) { int left = 0, i = 0, n = s.length(); while (s[i] == ' '){ i++; } left = i; while (i < n) { if (i + 1 == n || s[i] == ' ') { int j = i - 1; if (i + 1 == n) j++; reverse(s.begin()+left, s.begin()+j+1); left = i + 1; } if (left < n && s[left] == ' ' && i > left) left = i; i++; } // reversing the string reverse(s.begin(), s.end()); return s; } int main() { string str = ""I AM A GEEK""; str = reverse_words(str); cout << str; return 0; // This code is contributed // by Gatea David }",constant,linear "// C++ program to reverse a string using stack #include using namespace std; void recursiveReverse(string &str) { stack st; for (int i=0; i using namespace std; // Function to reverse a string void reverseStr(string& str) { int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } // Driver program int main() { string str = ""geeksforgeeks""; reverseStr(str); cout << str; return 0; }",constant,linear "// A Simple Iterative C++ program to reverse // a string #include using namespace std; // Function to reverse a string void reverseStr(string& str) { int n = str.length(); // Swap character starting from two // corners for (int i=0, j=n-1; i using namespace std; void recursiveReverse(string &str, int i = 0) { int n = str.length(); if (i == n / 2) return; swap(str[i], str[n - i - 1]); recursiveReverse(str, i + 1); } // Driver program int main() { string str = ""geeksforgeeks""; recursiveReverse(str); cout << str; return 0; }",linear,linear "// C++ program to reverse string using // reverse() method #include using namespace std; int main() { // Given String string str = ""geeksforgeeks""; // reverse function in C++ STL reverse(str.begin(), str.end()); // Printing the reversed string cout << str; return 0; } // contributed by akashish__",constant,linear "//C++ program to reverse string without //affecting it's special character #include using namespace std; void reverse(string s){ //creating character array of size // equal to length of string char temp[s.length()]; int x=0; for (int i = 0; i < s.length(); i++) { if(s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i]<='Z'){ //storing elements in array temp[x]=s[i]; x++; } } //reversing the character array reverse(temp,temp+x); x=0; for (int i = 0; i < s.length(); i++) { if(s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i]<='Z'){ //updating the original string s[i]=temp[x]; x++; } } cout<<""reversed string is: ""< using namespace std; // Returns true if x is an alphabetic character, false // otherwise bool isAlphabet(char x) { return ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')); } void reverse(char str[]) { // Initialize left and right pointers int r = strlen(str) - 1, l = 0; // Traverse string from both ends until 'l' and 'r' while (l < r) { // Ignore special characters if (!isAlphabet(str[l])) l++; else if (!isAlphabet(str[r])) r--; else // Both str[l] and str[r] are not special { swap(str[l], str[r]); l++; r--; } } } // Driver code int main() { char str[] = ""a!!!b.c.d,e'f,ghi""; cout << ""Input string: "" << str << endl; reverse(str); cout << ""Output string: "" << str << endl; return 0; } // This code is contributed by Sania Kumari Gupta",constant,linear "// C++ program to reverse a string preserving // spaces. #include using namespace std; // Function to reverse the string // and preserve the space position string reverses(string str) { // Mark spaces in result int n = str.size(); string result(n, '\0'); for (int i = 0; i < n; i++) if (str[i] == ' ') result[i] = ' '; // Traverse input string from beginning // and put characters in result from end int j = n - 1; for (int i = 0; i < str.length(); i++) { // Ignore spaces in input string if (str[i] != ' ') { // ignore spaces in result. while(result[j] == ' ') j--; result[j] = str[i]; j--; } } return result; } // Driver code int main() { string str = ""internship at geeks for geeks""; cout << reverses(str) << endl; return 0; }",linear,linear "// C++ program to implement // the above approach #include using namespace std; void preserveSpace(string &str) { int n = str.length(); // Initialize two pointers as two corners int start = 0; int end = n - 1; // Move both pointers toward each other while (start < end) { // If character at start or end is space, // ignore it if (str[start] == ' ') { start++; continue; } else if (str[end] == ' ') { end--; continue; } // If both are not spaces, do swap else { swap(str[start], str[end]); start++; end--; } } } // Driver code int main() { string str = ""internship at geeks for geeks""; preserveSpace(str); cout << str; return 0; }",constant,linear "// C++ Program to reverse a string without // using temp variable #include using namespace std; // Function to reverse string and return reversed string string reversingString(string str, int start, int end) { // Iterate loop upto start not equal to end while (start < end) { // XOR for swapping the variable str[start] ^= str[end]; str[end] ^= str[start]; str[start] ^= str[end]; ++start; --end; } return str; } // Driver Code int main() { string s = ""GeeksforGeeks""; cout << reversingString(s, 0, 12); return 0; }",constant,linear "// Reversing a string using reverse() #include using namespace std; int main() { string str = ""geeksforgeeks""; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0; }",constant,linear "// CPP Program for removing characters // from reversed string where vowels are // present in original string #include using namespace std; // Function for replacing the string void replaceOriginal(string s, int n) { // initialize a string of length n string r(n, ' '); // Traverse through all characters of string for (int i = 0; i < n; i++) { // assign the value to string r // from last index of string s r[i] = s[n - 1 - i]; // if s[i] is a consonant then // print r[i] if (s[i] != 'a' && s[i] != 'e' && s[i] != 'i' && s[i] != 'o' && s[i] != 'u') { cout << r[i]; } } cout << endl; } // Driver function int main() { string s = ""geeksforgeeks""; int n = s.length(); replaceOriginal(s, n); return 0; }",linear,linear "// C++ program to reverse order of vowels #include using namespace std; // utility function to check for vowel bool isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } // Function to reverse order of vowels string reverseVowel(string str) { int j=0; // Storing the vowels separately string vowel; for (int i=0; str[i]!='\0'; i++) if (isVowel(str[i])) vowel[j++] = str[i]; // Placing the vowels in the reverse // order in the string for (int i=0; str[i]!='\0'; i++) if (isVowel(str[i])) str[i] = vowel[--j] ; return str; } // Driver function int main() { string str = ""hello world""; cout << reverseVowel(str); return 0; }",linear,linear "// C++ program to reverse order of vowels #include using namespace std; // utility function to check for vowel bool isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } // Function to reverse order of vowels string reverseVowel(string str) { // Start two indexes from two corners // and move toward each other int i = 0; int j = str.length()-1; while (i < j) { if (!isVowel(str[i])) { i++; continue; } if (!isVowel(str[j])) { j--; continue; } // swapping swap(str[i], str[j]); i++; j--; } return str; } // Driver function int main() { string str = ""hello world""; cout << reverseVowel(str); return 0; }",constant,linear "// C++ program to reverse string // according to the number of words #include using namespace std; // Reverse the letters of the word void reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // This function forms the required string void reverseletter(char str[], int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') continue; // Checking the number of words // present in string to reverse while (str[wend] != ' ' && wend <= end) wend++; wend--; // Reverse the letter // of the words reverse(str, wstart, wend); } } // Driver Code int main() { char str[1000] = ""Ashish Yadav Abhishek Rajput Sunil Pundir""; reverseletter(str, 0, strlen(str) - 1); cout << str; return 0; } // This code is contributed by SHUBHAMSINGH10",constant,linear "// C++ program to reverse each word // in a linked list #include using namespace std; // Linked list Node structure struct Node { string c; struct Node* next; }; // Function to create newNode // in a linked list struct Node* newNode(string c) { Node* temp = new Node; temp->c = c; temp->next = NULL; return temp; }; // reverse each node data void reverse_word(string& str) { reverse(str.begin(), str.end()); } void reverse(struct Node* head) { struct Node* ptr = head; // iterate each node and call reverse_word // for each node data while (ptr != NULL) { reverse_word(ptr->c); ptr = ptr->next; } } // printing linked list void printList(struct Node* head) { while (head != NULL) { cout << head->c << "" ""; head = head->next; } } // Driver program int main() { Node* head = newNode(""Geeksforgeeks""); head->next = newNode(""a""); head->next->next = newNode(""computer""); head->next->next->next = newNode(""science""); head->next->next->next->next = newNode(""portal""); head->next->next->next->next->next = newNode(""for""); head->next->next->next->next->next->next = newNode(""geeks""); cout << ""List before reverse: \n""; printList(head); reverse(head); cout << ""\n\nList after reverse: \n""; printList(head); return 0; }",constant,linear "// C++ code to check if cyclic order is possible among strings // under given constraints #include using namespace std; #define M 26 // Utility method for a depth first search among vertices void dfs(vector g[], int u, vector &visit) { visit[u] = true; for (int i = 0; i < g[u].size(); ++i) if(!visit[g[u][i]]) dfs(g, g[u][i], visit); } // Returns true if all vertices are strongly connected // i.e. can be made as loop bool isConnected(vector g[], vector &mark, int s) { // Initialize all vertices as not visited vector visit(M, false); // perform a dfs from s dfs(g, s, visit); // now loop through all characters for (int i = 0; i < M; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visit[i]) return false; } // If we reach that means graph is connected return true; } // return true if an order among strings is possible bool possibleOrderAmongString(string arr[], int N) { // Create an empty graph vector g[M]; // Initialize all vertices as not marked vector mark(M, false); // Initialize indegree and outdegree of every // vertex as 0. vector in(M, 0), out(M, 0); // Process all strings one by one for (int i = 0; i < N; i++) { // Find first and last characters int f = arr[i].front() - 'a'; int l = arr[i].back() - 'a'; // Mark the characters mark[f] = mark[l] = true; // increase indegree and outdegree count in[l]++; out[f]++; // Add an edge in graph g[f].push_back(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for (int i = 0; i < M; i++) if (in[i] != out[i]) return false; return isConnected(g, mark, arr[0].front() - 'a'); } // Driver code to test above methods int main() { // string arr[] = {""abc"", ""efg"", ""cde"", ""ghi"", ""ija""}; string arr[] = {""ab"", ""bc"", ""cd"", ""de"", ""ed"", ""da""}; int N = sizeof(arr) / sizeof(arr[0]); if (possibleOrderAmongString(arr, N) == false) cout << ""Ordering not possible\n""; else cout << ""Ordering is possible\n""; return 0; }",linear,linear "// C++ program to sort an array of strings // using Trie #include using namespace std; const int MAX_CHAR = 26; struct Trie { // index is set when node is a leaf // node, otherwise -1; int index; Trie* child[MAX_CHAR]; /*to make new trie*/ Trie() { for (int i = 0; i < MAX_CHAR; i++) child[i] = NULL; index = -1; } }; /* function to insert in trie */ void insert(Trie* root, string str, int index) { Trie* node = root; for (int i = 0; i < str.size(); i++) { /* taking ascii value to find index of child node */ char ind = str[i] - 'a'; /* making new path if not already */ if (!node->child[ind]) node->child[ind] = new Trie(); // go to next node node = node->child[ind]; } // Mark leaf (end of word) and store // index of word in arr[] node->index = index; } /* function for preorder traversal */ bool preorder(Trie* node, string arr[]) { if (node == NULL) return false; for (int i = 0; i < MAX_CHAR; i++) { if (node->child[i] != NULL) { /* if leaf node then print key*/ if (node->child[i]->index != -1) cout << arr[node->child[i]->index] << endl; preorder(node->child[i], arr); } } } void printSorted(string arr[], int n) { Trie* root = new Trie(); // insert all keys of dictionary into trie for (int i = 0; i < n; i++) insert(root, arr[i], i); // print keys in lexicographic order preorder(root, arr); } // Driver code int main() { string arr[] = { ""abc"", ""xy"", ""bcd"" }; int n = sizeof(arr) / sizeof(arr[0]); printSorted(arr, n); return 0; }",linear,linear "// C++ program to sort a string of characters #include using namespace std; // function to print string in sorted order void sortString(string &str) { sort(str.begin(), str.end()); cout << str; } // Driver program to test above function int main() { string s = ""geeksforgeeks""; sortString(s); return 0; }",constant,nlogn "// C++ program to sort a string of characters #include using namespace std; const int MAX_CHAR = 26; // function to print string in sorted order void sortString(string &str) { // Hash array to keep count of characters. // Initially count of all characters is // initialized to zero. int charCount[MAX_CHAR] = {0}; // Traverse string and increment // count of characters for (int i=0; i using namespace std; void descOrder(string &s) { sort(s.begin(), s.end(), greater()); } int main() { string s = ""geeksforgeeks""; descOrder(s); // function call for(int i = 0; i < s.size(); i++) cout << s[i]; return 0; }",constant,constant "// C++ program to sort a string of characters // in descending order #include using namespace std; const int MAX_CHAR = 26; // function to print string in sorted order void sortString(string& str) { // Hash array to keep count of characters. // Initially count of all characters is // initialized to zero. int charCount[MAX_CHAR] = { 0 }; // Traverse string and increment // count of characters for (int i = 0; i < str.length(); i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i] - 'a']++; // Traverse the hash array and print // characters for (int i = MAX_CHAR - 1; i >= 0; i--) for (int j = 0; j < charCount[i]; j++) cout << (char)('a' + i); } // Driver program to test above function int main() { string s = ""alkasingh""; sortString(s); return 0; }",constant,linear "// C++ implementation to print array of strings in sorted // order without copying one string into another #include using namespace std; // function to print strings in sorted order void printInSortedOrder(string arr[], int n) { int index[n]; int i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i=0; i 0) min = j; } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { int temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i=0; i using namespace std; // function to sort the given string without // using any sorting technique string sortString(string str, int n) { // to store the final sorted string string new_str = """"; // for each character 'i' for (int i = 'a'; i <= 'z'; i++) // if character 'i' is present at a particular // index then add character 'i' to 'new_str' for (int j = 0; j < n; j++) if (str[j] == i) new_str += str[j]; // required final sorted string return new_str; } // Driver program to test above int main() { string str = ""geeksforgeeks""; int n = str.size(); cout << sortString(str, n); return 0; }",constant,linear "// C++ implementation to sort the given // string without using any sorting technique #include using namespace std; string sortString(string str, int n) { int i; //A character array to store the no.of occurrences of each character //between 'a' to 'z' char arr[26]={0}; //to store the final sorted string string new_str = """"; //To store each occurrence of character by relative indexing for (i = 0; i < n; i++) ++arr[str[i]-'a']; //To traverse the character array and append it to new_str for(i=0;i<26;i++) while(arr[i]--) new_str += i+'a'; return new_str; } // Driver program to test above int main() { string str = ""geeksforgeeks""; int n = str.size(); cout << sortString(str, n); return 0; } // This code is contributed by Aravind Alapati",constant,linear "// C++ program for above implementation #include using namespace std; const int MAX_CHAR = 26; // Function to return string in lexicographic // order followed by integers sum string arrangeString(string str) { int char_count[MAX_CHAR] = {0}; int sum = 0; // Traverse the string for (int i = 0; i < str.length(); i++) { // Count occurrence of uppercase alphabets if (str[i]>='A' && str[i] <='Z') char_count[str[i]-'A']++; //Store sum of integers else sum = sum + (str[i]-'0'); } string res = """"; // Traverse for all characters A to Z for (int i = 0; i < MAX_CHAR; i++) { char ch = (char)('A'+i); // Append the current character // in the string no. of times it // occurs in the given string while (char_count[i]--) res = res + ch; } // Append the sum of integers if (sum > 0) res = res + to_string(sum); // return resultant string return res; } // Driver program int main() { string str = ""ACCBA10D2EW30""; cout << arrangeString(str); return 0; }",linear,linear "// C++ program to print all permutations // of a string in sorted order. #include using namespace std; // Calculating factorial of a number int factorial(int n) { int f = 1; for (int i = 1; i <= n; i++) f = f * i; return f; } // Method to find total number of permutations int calculateTotal(string temp, int n) { int f = factorial(n); // Building Map to store frequencies of // all characters. map hm; for (int i = 0; i < temp.length(); i++) { hm[temp[i]]++; } // Traversing map and // finding duplicate elements. for (auto e : hm) { int x = e.second; if (x > 1) { int temp5 = factorial(x); f /= temp5; } return f; } } static void nextPermutation(string &temp) { // Start traversing from the end and // find position 'i-1' of the first character // which is greater than its successor. int i; for (i = temp.length() - 1; i > 0; i--) if (temp[i] > temp[i - 1]) break; // Finding smallest character after 'i-1' and // greater than temp[i-1] int min = i; int j, x = temp[i - 1]; for (j = i + 1; j < temp.length(); j++) if ((temp[j] < temp[min]) and (temp[j] > x)) min = j; // Swapping the above found characters. swap(temp[i - 1], temp[min]); // Sort all digits from position next to 'i-1' // to end of the string. sort(temp.begin() + i, temp.end()); // Print the String cout << temp << endl; } void printAllPermutations(string s) { // Sorting String string temp(s); sort(temp.begin(), temp.end()); // Print first permutation cout << temp << endl; // Finding the total permutations int total = calculateTotal(temp, temp.length()); for (int i = 1; i < total; i++) { nextPermutation(temp); } } // Driver Code int main() { string s = ""AAB""; printAllPermutations(s); } // This code is contributed by // sanjeev2552",linear,quadratic "// C++ program to get minimum cost to sort // strings by reversal operation #include using namespace std; // Returns minimum cost for sorting arr[] // using reverse operation. This function // returns -1 if it is not possible to sort. int minCost(string arr[], int cost[], int N) { // dp[i][j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. int dp[N][2]; // initializing dp array for first string dp[0][0] = 0; dp[0][1] = cost[0]; // getting array of reversed strings string revStr[N]; for (int i = 0; i < N; i++) { revStr[i] = arr[i]; reverse(revStr[i].begin(), revStr[i].end()); } string curStr; int curCost; // looping for all strings for (int i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (int j = 0; j < 2; j++) { dp[i][j] = INT_MAX; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr >= arr[i - 1]) dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost); if (curStr >= revStr[i - 1]) dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost); } } // getting minimum from both entries of last index int res = min(dp[N-1][0], dp[N-1][1]); return (res == INT_MAX)? -1 : res; } // Driver code to test above methods int main() { string arr[] = {""aa"", ""ba"", ""ac""}; int cost[] = {1, 3, 1}; int N = sizeof(arr) / sizeof(arr[0]); int res = minCost(arr, cost, N); if (res == -1) cout << ""Sorting not possible\n""; else cout << ""Minimum cost to sort strings is "" << res; }",linear,linear "// CPP program to print all number containing // 1, 2 and 3 in any order. #include using namespace std; // convert the number to string and find // if it contains 1, 2 & 3. bool findContainsOneTwoThree(int number) { string str = to_string(number); int countOnes = 0, countTwo = 0, countThree = 0; for (int i = 0; i < str.length(); i++) { if (str[i] == '1') countOnes++; else if (str[i] == '2') countTwo++; else if (str[i] == '3') countThree++; } return (countOnes && countTwo && countThree); } // prints all the number containing 1, 2, 3 string printNumbers(int numbers[], int n) { vector oneTwoThree; for (int i = 0; i < n; i++) { // check if the number contains 1, // 2 & 3 in any order if (findContainsOneTwoThree(numbers[i])) oneTwoThree.push_back(numbers[i]); } // sort all the numbers sort(oneTwoThree.begin(), oneTwoThree.end()); string result = """"; for (auto number : oneTwoThree) { int value = number; if (result.length() > 0) result += "", ""; result += to_string(value); } return (result.length() > 0) ? result : ""-1""; } // Driver Code int main() { int numbers[] = { 123, 1232, 456, 234, 32145 }; int n = sizeof(numbers) / sizeof(numbers[0]); string result = printNumbers(numbers, n); cout << result; return 0; } // This code is contributed // by Sirjan13",linear,nlogn "// C++ program to implement binary search // in a sparse array. #include using namespace std; /* Binary Search in an array with blanks */ int binarySearch(string *arr, int low, int high, string x) { if (low > high) return -1; int mid = (low + high) / 2; /*Modified Part*/ if (arr[mid] == """") { int left = mid - 1; int right = mid + 1; /*Search for both side for a non empty string*/ while (1) { /* No non-empty string on both sides */ if (left < low && right > high) return -1; if (left >= low && arr[left] != """") { mid = left; break; } else if (right <= high && arr[right] != """") { mid = right; break; } left--; right++; } } /* Normal Binary Search */ if (arr[mid] == x) return mid; else if (arr[mid] > x) return binarySearch(arr, low, mid - 1, x); else return binarySearch(arr, mid + 1, high, x); } int sparseSearch(string arr[], string x, int n) { return binarySearch(arr, 0, n - 1, x); } int main() { ios_base::sync_with_stdio(false); string arr[] = {""for"", ""geeks"", """", """", """", """", ""ide"", ""practice"", """", """", """", ""quiz""}; string x = ""geeks""; int n = sizeof(arr) / sizeof(arr[0]); int index = sparseSearch(arr, x, n); if (index != -1) cout << x << "" found at index "" << index << ""\n""; else cout << x << "" not found\n""; return 0; }",logn,logn "// C++ program to toggle cases of a given // string. #include #include using namespace std; // function to toggle cases of a string void toggle(string& str) { int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (islower(c)) str[i] = toupper(c); else if (isupper(c)) str[i] = tolower(c); } } // Driver Code int main() { string str = ""GeekS""; toggle(str); cout << str; return 0; }",constant,linear "// C++ program to convert a string from // lower to upper case. #include const int x = 32; // Converts a string to uppercase char *toUpperCase(char *a) { for (int i=0; a[i]!='\0'; i++) a[i] = a[i] & ~x; return a; } // Driver Code int main() { char str[] = ""SanjaYKannA""; //Here it's recommended to use character array //as it's stored in read-write area. //If a pointer is used it's stored //in read-only memory as a string literal. printf(""%s"", toUpperCase(str)); return 0; }",constant,linear "// C++ program to convert a string from // upper to lower case. #include const int x = 32; // Converts a string to lowercase char * toLowerCase(char *a) { for (int i=0; a[i]!='\0'; i++) a[i] = a[i] | x; return a; } // Driver Code int main() { char str[] = ""SanjaYKannA""; printf(""%s"", toLowerCase(str)); return 0; }",constant,linear "// CPP Program to find maximum // lowercase alphabets present // between two uppercase alphabets #include using namespace std; #define MAX_CHAR 26 // Function which computes the // maximum number of distinct // lowercase alphabets between // two uppercase alphabets int maxLower(string str) { int n = str.length(); // Ignoring lowercase characters in the // beginning. int i = 0; for (; i < n; i++) { if (str[i] >= 'A' && str[i] <= 'Z') { i++; break; } } // We start from next of first capital letter // and traverse through remaining character. int maxCount = 0; int count[MAX_CHAR] = { 0 }; for (; i < n; i++) { // If character is in uppercase, if (str[i] >= 'A' && str[i] <= 'Z') { // Count all distinct lower case // characters int currCount = 0; for (int j = 0; j < MAX_CHAR; j++) if (count[j] > 0) currCount++; // Update maximum count maxCount = max(maxCount, currCount); // Reset count array memset(count, 0, sizeof(count)); } // If character is in lowercase if (str[i] >= 'a' && str[i] <= 'z') count[str[i] - 'a']++; } return maxCount; } // Driver function int main() { string str = ""zACaAbbaazzC""; cout << maxLower(str); return 0; }",constant,linear "// CPP Program to find maximum // lowercase alphabets present // between two uppercase alphabets #include using namespace std; // Function which computes the // maximum number of distinct // lowercase alphabets between // two uppercase alphabets int maxLower(string str) { int n = str.length(); // Ignoring lowercase characters in the // beginning. int i = 0; for (; i < n; i++) { if (str[i] >= 'A' && str[i] <= 'Z') { i++; break; } } // We start from next of first capital letter // and traverse through remaining character. int maxCount = 0; unordered_set s; for (; i < n; i++) { // If character is in uppercase, if (str[i] >= 'A' && str[i] <= 'Z') { // Update maximum count if lowercase // character before this is more. maxCount = max(maxCount, (int)s.size()); // clear the set s.clear(); } // If character is in lowercase if (str[i] >= 'a' && str[i] <= 'z') s.insert(str[i]); } return maxCount; } // Driver function int main() { string str = ""zACaAbbaazzC""; cout << maxLower(str); return 0; }",linear,linear "// C++ program to convert a // sentence to gOOGLE cASE. #include using namespace std; string convert(string str) { // Empty strings string w = """", z = """"; // Convert input string to upper case transform(str.begin(), str.end(), str.begin(), ::toupper); str += "" ""; for(int i = 0; i < str.length(); i++) { // Check if character is not a space // and adding it to string w char ch = str[i]; if (ch != ' ') { w = w + ch; } else { // Converting first character // to lower case and subsequent // initial letter of another // word to lower case z = z + char(tolower(w[0])) + w.substr(1) + "" ""; w = """"; } } return z; } // Driver code int main() { string str = ""I got intern at geeksforgeeks""; cout << convert(str) << endl; return 0; } // This code is contributed by rutvik_56",linear,linear "// CPP program to convert given // sentence to camel case. #include using namespace std; // Function to remove spaces and // convert into camel case string convert(string s) { int n = s.length(); s[0] = tolower(s[0]); for (int i = 1; i < n; i++) { // check for spaces in the sentence if (s[i] == ' ' && i < n) { // conversion into upper case s[i + 1] = tolower(s[i + 1]); i++; } // If not space, copy character else s[i] = toupper(s[i]); } // return string to main return s; } // Driver Code int main() { string str = ""I get intern at geeksforgeeks""; cout << convert(str); return 0; }",constant,linear "// C++ program to print all words in the CamelCase // dictionary that matches with a given pattern #include using namespace std; // Alphabet size (# of upper-Case characters) #define ALPHABET_SIZE 26 // A Trie node struct TrieNode { TrieNode* children[ALPHABET_SIZE]; // isLeaf is true if the node represents // end of a word bool isLeaf; // vector to store list of complete words // in leaf node list word; }; // Returns new Trie node (initialized to NULLs) TrieNode* getNewTrieNode(void) { TrieNode* pNode = new TrieNode; if (pNode) { pNode->isLeaf = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; } return pNode; } // Function to insert word into the Trie void insert(TrieNode* root, string word) { int index; TrieNode* pCrawl = root; for (int level = 0; level < word.length(); level++) { // consider only uppercase characters if (islower(word[level])) continue; // get current character position index = int(word[level]) - 'A'; if (!pCrawl->children[index]) pCrawl->children[index] = getNewTrieNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isLeaf = true; // push word into vector associated with leaf node (pCrawl->word).push_back(word); } // Function to print all children of Trie node root void printAllWords(TrieNode* root) { // if current node is leaf if (root->isLeaf) { for(string str : root->word) cout << str << endl; } // recurse for all children of root node for (int i = 0; i < ALPHABET_SIZE; i++) { TrieNode* child = root->children[i]; if (child) printAllWords(child); } } // search for pattern in Trie and print all words // matching that pattern bool search(TrieNode* root, string pattern) { int index; TrieNode* pCrawl = root; for (int level = 0; level < pattern.length(); level++) { index = int(pattern[level]) - 'A'; // Invalid pattern if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } // print all words matching that pattern printAllWords(pCrawl); return true; } // Main function to print all words in the CamelCase // dictionary that matches with a given pattern void findAllWords(vector dict, string pattern) { // construct Trie root node TrieNode* root = getNewTrieNode(); // Construct Trie from given dict for (string word : dict) insert(root, word); // search for pattern in Trie if (!search(root, pattern)) cout << ""No match found""; } // Driver function int main() { // dictionary of words where each word follows // CamelCase notation vector dict = { ""Hi"", ""Hello"", ""HelloWorld"", ""HiTech"", ""HiGeek"", ""HiTechWorld"", ""HiTechCity"", ""HiTechLab"" }; // pattern consisting of uppercase characters only string pattern = ""HT""; findAllWords(dict, pattern); return 0; }",linear,quadratic "// CPP program to convert given sentence /// to camel case. #include using namespace std; // Function to remove spaces and convert // into camel case string convert(string s) { int n = s.length(); int res_ind = 0; for (int i = 0; i < n; i++) { // check for spaces in the sentence if (s[i] == ' ') { // conversion into upper case s[i + 1] = toupper(s[i + 1]); continue; } // If not space, copy character else s[res_ind++] = s[i]; } // return string to main return s.substr(0, res_ind); } // Driver program int main() { string str = ""I get intern at geeksforgeeks""; cout << convert(str); return 0; }",constant,linear "// CPP code to print all permutations // with respect to cases #include using namespace std; // Function to generate permutations void permute(string ip, string op) { // base case if (ip.size() == 0) { cout << op << "" ""; return; } // pick lower and uppercase char ch = tolower(ip[0]); char ch2 = toupper(ip[0]); ip = ip.substr(1); permute(ip, op + ch); permute(ip, op + ch2); } // Driver code int main() { string ip = ""aB""; permute(ip, """"); return 0; }",linear,np "// CPP code to print all permutations // with respect to cases #include using namespace std; // Function to generate permutations void permute(string input) { int n = input.length(); // Number of permutations is 2^n int max = 1 << n; // Converting string to lower case transform(input.begin(), input.end(), input.begin(), ::tolower); // Using all subsequences and permuting them for (int i = 0; i < max; i++) { // If j-th bit is set, we convert it to upper case string combination = input; for (int j = 0; j < n; j++) if (((i >> j) & 1) == 1) combination[j] = toupper(input.at(j)); // Printing current combination cout << combination << "" ""; } } // Driver code int main() { permute(""ABC""); return 0; }",linear,quadratic "// C++ program to get toggle case of a string #include using namespace std; // tOGGLE cASE = swaps CAPS to lower // case and lower case to CAPS char *toggleCase(char *a) { for(int i = 0; a[i] != '\0'; i++) { // Bitwise EXOR with 32 a[i] ^= 32; } return a; } // Driver Code int main() { char str[] = ""CheRrY""; cout << ""Toggle case: "" << toggleCase(str) << endl; cout << ""Original string: "" << toggleCase(str) << endl; return 0; } // This code is contributed by noob2000",constant,linear "// C++ program to generate short url from integer id and // integer id back from short url. #include #include #include using namespace std; // Function to generate a short url from integer ID string idToShortURL(long int n) { // Map to store 62 possible characters char map[] = ""abcdefghijklmnopqrstuvwxyzABCDEF"" ""GHIJKLMNOPQRSTUVWXYZ0123456789""; string shorturl; // Convert given integer id to a base 62 number while (n) { // use above map to store actual character // in short url shorturl.push_back(map[n%62]); n = n/62; } // Reverse shortURL to complete base conversion reverse(shorturl.begin(), shorturl.end()); return shorturl; } // Function to get integer ID back from a short url long int shortURLtoID(string shortURL) { long int id = 0; // initialize result // A simple base conversion logic for (int i=0; i < shortURL.length(); i++) { if ('a' <= shortURL[i] && shortURL[i] <= 'z') id = id*62 + shortURL[i] - 'a'; if ('A' <= shortURL[i] && shortURL[i] <= 'Z') id = id*62 + shortURL[i] - 'A' + 26; if ('0' <= shortURL[i] && shortURL[i] <= '9') id = id*62 + shortURL[i] - '0' + 52; } return id; } // Driver program to test above function int main() { int n = 12345; string shorturl = idToShortURL(n); cout << ""Generated short url is "" << shorturl << endl; cout << ""Id from url is "" << shortURLtoID(shorturl); return 0; }",constant,linear "// C++ program to print all permutations // with repetition of characters #include #include using namespace std; /* Following function is used by the library qsort() function to sort an array of chars */ int compare (const void * a, const void * b); /* The main function that recursively prints all repeated permutations of the given string. It uses data[] to store all permutations one by one */ void allLexicographicRecur (char *str, char* data, int last, int index) { int i, len = strlen(str); // One by one fix all characters at // the given index and recur for // the/ subsequent indexes for ( i = 0; i < len; i++ ) { // Fix the ith character at index // and if this is not the last // index then recursively call // for higher indexes data[index] = str[i] ; // If this is the last index then // print the string stored in // data[] if (index == last) cout << data << endl; else // Recur for higher indexes allLexicographicRecur (str, data, last, index+1); } } /* This function sorts input string, allocate memory for data (needed for allLexicographicRecur()) and calls allLexicographicRecur() for printing all permutations */ void allLexicographic(char *str) { int len = strlen (str) ; // Create a temp array that will // be used by allLexicographicRecur() char *data = (char *) malloc (sizeof(char) * (len + 1)) ; data[len] = '\0'; // Sort the input string so that // we get all output strings in // lexicographically sorted order qsort(str, len, sizeof(char), compare); // Now print all permutations allLexicographicRecur (str, data, len-1, 0); // Free data to avoid memory leak free(data); } // Needed for library function qsort() int compare (const void * a, const void * b) { return ( *(char *)a - *(char *)b ); } // Driver code int main() { char str[] = ""ABC""; cout << ""All permutations with repetition of ""<< str <<"" are: ""< using namespace std; // Returns true if str can be converted to a string // with k repeated substrings after replacing k // characters. bool checkString(string str, long k) { // Length of string must be a multiple of k int n = str.length(); if (n%k != 0) return false; // Map to store strings of length k and their counts unordered_map mp; for (int i=0; isecond == (n/k - 1)) || mp.begin()->second == 1) return true; return false; } // Driver code int main() { checkString(""abababcd"", 2)? cout << ""Yes"" : cout << ""No""; return 0; }",linear,linear "// C++ program to find smallest possible length // of a string of only three characters #include using namespace std; // Program to find length of reduced string // in a string made of three characters. #define MAX_LEN 110 // To store results of subproblems int DP[MAX_LEN][MAX_LEN][MAX_LEN]; // A memoized function find result recursively. // a, b and c are counts of 'a's, 'b's and // 'c's in str int length(int a, int b, int c) { // If this subproblem is already evaluated if(a < 0 or b < 0 or c < 0) if (DP[a][b] != -1) return DP[a][b]; // If there is only one type of character if (a == 0 && b == 0) return (DP[a][b] = c); if (a == 0 && c == 0) return (DP[a][b] = b); if (b == 0 && c == 0) return (DP[a][b] = a); // If only two types of characters are present if (a == 0) return (DP[a][b] = length(a + 1, b - 1, c - 1)); if (b == 0) return (DP[a][b] = length(a - 1, b + 1, c - 1)); if (c == 0) return (DP[a][b] = length(a - 1, b - 1, c + 1)); // If all types of characters are present. // Try combining all pairs. return (DP[a][b] = min(length(a - 1, b - 1, c + 1), min(length(a - 1, b + 1, c - 1), length(a + 1, b - 1, c - 1)))); } // Returns smallest possible length with given // operation allowed. int stringReduction(string str) { int n = str.length(); // Counting occurrences of three different // characters 'a', 'b' and 'c' in str int count[3] = {0}; for (int i=0; i using namespace std; // Returns smallest possible length with given // operation allowed. int stringReduction(string str) { int n = str.length(); // Counint occurrences of three different // characters 'a', 'b' and 'c' in str int count[3] = {0}; for (int i=0; i using namespace std; const int MAX_CHAR = 26; // function to find if its possible to // distribute balls or not bool distributingBalls(int k, int n, string str) { // count array to count how many times // each color has occurred int a[MAX_CHAR] = {0}; for (int i = 0; i < n; i++){ // increasing count of each color // every time it appears a[str[i] - 'a']++; } for (int i = 0; i < MAX_CHAR; i++) // to check if any color appears // more than K times if it does // we will print NO if (a[i] > k) return false; return true; } // Driver code int main() { long long int n = 6, k = 3; string str = ""aacaab""; if (distributingBalls(k, n, str)) cout << ""YES""; else cout << ""NO""; return 0; }",constant,linear "// C++ program to find the maximum consecutive // repeating character in given string #include using namespace std; // function to find out the maximum repeating // character in given string char maxRepeating(string str) { int len = str.length(); int count = 0; // Find the maximum repeating character // starting from str[i] char res = str[0]; for (int i=0; i count) { count = cur_count; res = str[i]; } } return res; } // Driver code int main() { string str = ""aaaabbaaccde""; cout << maxRepeating(str); return 0; }",constant,quadratic "// C++ program to find the maximum consecutive // repeating character in given string #include using namespace std; // Returns the maximum repeating character in a // given string char maxRepeating(string str) { int n = str.length(); int count = 0; char res = str[0]; int cur_count = 1; // Traverse string except last character for (int i=0; i count) { count = cur_count; res = str[i]; } cur_count = 1; } } return res; } // Driver code int main() { string str = ""aaaabbaaccde""; cout << maxRepeating(str); return 0; }",constant,linear "// C++ program for a Queue based approach // to find first non-repeating character #include using namespace std; const int MAX_CHAR = 26; // function to find first non repeating // character of sa stream void firstnonrepeating(char str[]) { queue q; int charCount[MAX_CHAR] = { 0 }; // traverse whole stream for (int i = 0; str[i]; i++) { // push each character in queue q.push(str[i]); // increment the frequency count charCount[str[i] - 'a']++; // check for the non repeating character while (!q.empty()) { if (charCount[q.front() - 'a'] > 1) q.pop(); else { cout << q.front() << "" ""; break; } } if (q.empty()) cout << -1 << "" ""; } cout << endl; } // Driver function int main() { char str[] = ""aabc""; firstnonrepeating(str); return 0; }",linear,linear "// C++ program to find k'th non-repeating character // in a string #include using namespace std; const int MAX_CHAR = 256; // Returns index of k'th non-repeating character in // given string str[] int kthNonRepeating(string str, int k) { int n = str.length(); // count[x] is going to store count of // character 'x' in str. If x is not present, // then it is going to store 0. int count[MAX_CHAR]; // index[x] is going to store index of character // 'x' in str. If x is not present or x is // repeating, then it is going to store a value // (for example, length of string) that cannot be // a valid index in str[] int index[MAX_CHAR]; // Initialize counts of all characters and indexes // of non-repeating characters. for (int i = 0; i < MAX_CHAR; i++) { count[i] = 0; index[i] = n; // A value more than any index // in str[] } // Traverse the input string for (int i = 0; i < n; i++) { // Find current character and increment its // count char x = str[i]; ++count[x]; // If this is first occurrence, then set value // in index as index of it. if (count[x] == 1) index[x] = i; // If character repeats, then remove it from // index[] if (count[x] == 2) index[x] = n; } // Sort index[] in increasing order. This step // takes O(1) time as size of index is 256 only sort(index, index+MAX_CHAR); // After sorting, if index[k-1] is value, then // return it, else return -1. return (index[k-1] != n)? index[k-1] : -1; } // Driver code int main() { string str = ""geeksforgeeks""; int k = 3; int res = kthNonRepeating(str, k); (res == -1)? cout << ""There are less than k non-"" ""repeating characters"" : cout << ""k'th non-repeating character"" "" is ""<< str[res]; return 0; }",linear,nlogn "#include using namespace std; #define MAX_CHAR 256 int kthNonRepeating(string input, int k) { int inputLength = input.length(); /* * indexArr will store index of non-repeating * characters, inputLength for characters not in input * and inputLength+1 for repeated characters. */ int indexArr[MAX_CHAR]; // initialize all values in indexArr as inputLength. for (int i = 0; i < MAX_CHAR; i++) { indexArr[i] = inputLength; } for (int i = 0; i < inputLength; i++) { char c = input[i]; if (indexArr == inputLength) { indexArr = i; } else { indexArr = inputLength + 2; } } sort(indexArr, indexArr + MAX_CHAR); return (indexArr[k - 1] != inputLength) ? indexArr[k - 1] : -1; } int main() { string input = ""geeksforgeeks""; int k = 3; int res = kthNonRepeating(input, k); if (res == -1) cout << ""There are less than k non-repeating "" ""characters""; else cout << ""k'th non-repeating character is "" << input[res]; return 0; } // This code is contributed by gauravrajput1",linear,nlogn "// CPP program to find the first // repeated character in a string #include using namespace std; // Returns first repeating character in str. char firstRepeating(string &str) { // Creates an empty hashset unordered_set h; // Traverse the input array from left to right for (int i=0; i using namespace std; // Function to find the word string secMostRepeated(vector seq) { // Store all the words with its occurrence unordered_map occ; for (int i = 0; i < seq.size(); i++) occ[seq[i]]++; // find the second largest occurrence int first_max = INT_MIN, sec_max = INT_MIN; for (auto it = occ.begin(); it != occ.end(); it++) { if (it->second > first_max) { sec_max = first_max; first_max = it->second; } else if (it->second > sec_max && it->second != first_max) sec_max = it->second; } // Return string with occurrence equals // to sec_max for (auto it = occ.begin(); it != occ.end(); it++) if (it->second == sec_max) return it->first; } // Driver program int main() { vector seq = { ""ccc"", ""aaa"", ""ccc"", ""ddd"", ""aaa"", ""aaa"" }; cout << secMostRepeated(seq); return 0; }",linear,linear "// CPP code to find most frequent word in // an array of strings #include using namespace std; void mostFrequentWord(string arr[], int n) { // freq to store the freq of the most occurring variable int freq = 0; // res to store the most occurring string in the array of // strings string res; // running nested for loops to find the most occurring // word in the array of strings for (int i = 0; i < n; i++) { int count = 0; for (int j = i + 1; j < n; j++) { if (arr[j] == arr[i]) { count++; } } // updating our max freq of occured string in the // array of strings if (count >= freq) { res = arr[i]; freq = count; } } cout << ""The word that occurs most is : "" << res << endl; cout << ""No of times: "" << freq << endl; } // Driver code int main() { // given set of keys string arr[] = { ""geeks"", ""for"", ""geeks"", ""a"", ""portal"", ""to"", ""learn"", ""can"", ""be"", ""computer"", ""science"", ""zoom"", ""yup"", ""fire"", ""in"", ""be"", ""data"", ""geeks"" }; int n = sizeof(arr) / sizeof(arr[0]); mostFrequentWord(arr, n); return 0; }",constant,constant "#include using namespace std; class Solution { public: // Function to find most frequent word // in an array of strings. string mostFrequentWord(string arr[], int n) { unordered_map freq; unordered_map occurrence; int max = 0; string result; int k = 1; for (int i = 0; i < n; i++) { if (occurrence.count(arr[i]) > 0) { continue; } occurrence[arr[i]] = k++; } for (int i = 0; i < n; i++) { freq[arr[i]]++; if (max <= freq[arr[i]]) { if (max < freq[arr[i]]) { max = freq[arr[i]]; result = arr[i]; } else { if (occurrence[result] < occurrence[arr[i]]) { max = freq[arr[i]]; result = arr[i]; } } } } return result; } }; int main() { string arr[] = { ""geeks"", ""for"", ""geeks"", ""a"", ""portal"", ""to"", ""learn"", ""can"", ""be"", ""computer"", ""science"", ""zoom"", ""yup"", ""fire"", ""in"", ""be"", ""data"", ""geeks"" }; int n = sizeof(arr) / sizeof(arr[0]); Solution obj; cout << obj.mostFrequentWord(arr, n) << endl; return 0; }",linear,linear "// c++ implementation // Function returns word with highest frequency #include using namespace std; // Function returns word with highest frequency string findWord(vector arr) { // Create HashMap to store word and it's frequency unordered_map hs; // Iterate through array of words for (int i = 0; i < arr.size(); i++) { hs[arr[i]]++; } string key = """"; int value = 0; for (auto me : hs) { // Check for word having highest frequency if (me.second > value) { value = me.second; key = me.first; } } // Return word having highest frequency return key; } int main() { vector arr{ ""geeks"", ""for"", ""geeks"", ""a"", ""portal"", ""to"", ""learn"", ""can"", ""be"", ""computer"", ""science"", ""zoom"", ""yup"", ""fire"", ""in"", ""be"", ""data"", ""geeks"" }; string sol = findWord(arr); // Print word having highest frequency cout << sol << endl; } // This code is contributed by Aarti_Rathi",linear,linear "// CPP code to find most frequent word in // an array of strings #include using namespace std; /*structing the trie*/ struct Trie { string key; int cnt; unordered_map map; }; /* Function to return a new Trie node */ Trie* getNewTrieNode() { Trie* node = new Trie; node->cnt = 0; return node; } /* function to insert a string */ void insert(Trie*& root, string& str, int& maxCount, string& mostFrequentString) { // start from root node Trie* temp = root; for (int i = 0; i < str.length(); i++) { char x = str[i]; /*a new node if path doesn't exists*/ if (temp->map.find(x) == temp->map.end()) temp->map[x] = getNewTrieNode(); // go to next node temp = temp->map[x]; } // store key and its count in leaf nodes temp->key = str; temp->cnt += 1; if (maxCount < temp->cnt) { maxCount = temp->cnt; mostFrequentString = str; } } void mostFrequentWord(string arr[], int n) { // Insert all words in a Trie Trie* root = getNewTrieNode(); int cnt = 0; string key = """"; for (int i = 0; i < n; i++) insert(root, arr[i], cnt, key); cout << ""The word that occurs most is : "" << key << endl; cout << ""No of times: "" << cnt << endl; } // Driver code int main() { // given set of keys string arr[] = { ""geeks"", ""for"", ""geeks"", ""a"", ""portal"", ""to"", ""learn"", ""can"", ""be"", ""computer"", ""science"", ""zoom"", ""yup"", ""fire"", ""in"", ""be"", ""data"", ""geeks"" }; int n = sizeof(arr) / sizeof(arr[0]); mostFrequentWord(arr, n); return 0; }",linear,linear "// Efficiently check First repeated character // in C++ program #include using namespace std; // Returns -1 if all characters of str are // unique. // Assumptions : (1) str contains only characters // from 'a' to 'z' // (2) integers are stored using 32 // bits int FirstRepeated(string str) { // An integer to store presence/absence // of 26 characters using its 32 bits. int checker = 0; for (int i = 0; i < str.length(); ++i) { int val = (str[i]-'a'); // If bit corresponding to current // character is already set if ((checker & (1 << val)) > 0) return i; // set bit in checker checker |= (1 << val); } return -1; } // Driver code int main() { string s = ""abcfdeacf""; int i=FirstRepeated(s); if (i!=-1) cout <<""Char = ""<< s[i] << "" and Index = ""< using namespace std; // Print whether index i and j have same // element or not. void query(char s[], int i, int j) { int n = strlen(s); // Finding relative position of index i,j. i %= n; j %= n; // Checking is element are same at index i, j. (s[i] == s[j]) ? (cout << ""Yes"" << endl) : (cout << ""No"" << endl); } // Driven Program int main() { char X[] = ""geeksforgeeks""; query(X, 0, 8); query(X, 8, 13); query(X, 6, 15); return 0; }",constant,constant "// C++ program to output the maximum occurring character // in a string #include #define ASCII_SIZE 256 using namespace std; char getMaxOccurringChar(char* str) { // Create array to keep the count of individual // characters and initialize the array as 0 int count[ASCII_SIZE] = { 0 }; // Construct character count array from the input // string. int len = strlen(str); int max = 0; // Initialize max count char result; // Initialize result // Traversing through the string and maintaining // the count of each character for (int i = 0; i < len; i++) { count[str[i]]++; if (max < count[str[i]]) { max = count[str[i]]; result = str[i]; } } return result; } // Driver program to test the above function int main() { char str[] = ""sample string""; cout << ""Max occurring character is "" << getMaxOccurringChar(str); }",constant,linear "// C++ program to count occurrences of a given // character #include #include using namespace std; // Function that return count of the given // character in the string int count(string s, char c) { // Count variable int res = 0; for (int i=0;i using namespace std; // Driver code int main() { string str = ""geeksforgeeks""; char c = 'e'; // Count returns number of occurrences of // c between two given positions provided // as two iterators. cout << count(str.begin(), str.end(), c); return 0; }",constant,linear "// C++ program to print the string in given pattern #include using namespace std; // Function to print the string void printStringAlternate(string str) { unordered_map occ; // Start traversing the string for (int i = 0; i < str.length(); i++) { // Convert uppercase to lowercase char temp = tolower(str[i]); // Increment occurrence count occ[temp]++; // If count is odd then print the character if (occ[temp] & 1) cout << str[i]; } cout << endl; } // Drivers code int main() { string str = ""Geeks for geeks""; string str2 = ""It is a long day Dear""; printStringAlternate(str); printStringAlternate(str2); return 0; }",linear,linear "// Program to find all occurrences of the word in // a matrix #include using namespace std; #define ROW 3 #define COL 5 // check whether given cell (row, col) is a valid // cell or not. bool isvalid(int row, int col, int prevRow, int prevCol) { // return true if row number and column number // is in range return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && !(row== prevRow && col == prevCol); } // These arrays are used to get row and column // numbers of 8 neighboursof a given cell int rowNum[] = {-1, -1, -1, 0, 0, 1, 1, 1}; int colNum[] = {-1, 0, 1, -1, 1, -1, 0, 1}; // A utility function to do DFS for a 2D boolean // matrix. It only considers the 8 neighbours as // adjacent vertices void DFS(char mat[][COL], int row, int col, int prevRow, int prevCol, char* word, string path, int index, int n) { // return if current character doesn't match with // the next character in the word if (index > n || mat[row][col] != word[index]) return; //append current character position to path path += string(1, word[index]) + ""("" + to_string(row) + "", "" + to_string(col) + "") ""; // current character matches with the last character // in the word if (index == n) { cout << path << endl; return; } // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isvalid(row + rowNum[k], col + colNum[k], prevRow, prevCol)) DFS(mat, row + rowNum[k], col + colNum[k], row, col, word, path, index+1, n); } // The main function to find all occurrences of the // word in a matrix void findWords(char mat[][COL], char* word, int n) { // traverse through the all cells of given matrix for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // occurrence of first character in matrix if (mat[i][j] == word[0]) // check and print if path exists DFS(mat, i, j, -1, -1, word, """", 0, n); } // Driver program to test above function int main() { char mat[ROW][COL]= { {'B', 'N', 'E', 'Y', 'S'}, {'H', 'E', 'D', 'E', 'S'}, {'S', 'G', 'N', 'D', 'E'} }; char word[] =""DES""; findWords(mat, word, strlen(word) - 1); return 0; }",quadratic,quadratic "// C++ program to arrange given string #include using namespace std; // Function which arrange the given string void arrangeString(string str, int x, int y) { int count_0 = 0; int count_1 = 0; int len = str.length(); // Counting number of 0's and 1's in the // given string. for (int i = 0; i < len; i++) { if (str[i] == '0') count_0++; else count_1++; } // Printing first all 0's x-times // and decrement count of 0's x-times // and do the similar task with '1' while (count_0 > 0 || count_1 > 0) { for (int j = 0; j < x && count_0 > 0; j++) { if (count_0 > 0) { cout << ""0""; count_0--; } } for (int j = 0; j < y && count_1 > 0; j++) { if (count_1 > 0) { cout << ""1""; count_1--; } } } } // Driver Code int main() { string str = ""01101101101101101000000""; int x = 1; int y = 2; arrangeString(str, x, y); return 0; }",constant,quadratic "// Finds maximum occurring digit without using any array/string #include using namespace std; // Simple function to count occurrences of digit d in x int countOccurrences(long int x, int d) { int count = 0; // Initialize count of digit d while (x) { // Increment count if current digit is same as d if (x%10 == d) count++; x = x/10; } return count; } // Returns the max occurring digit in x int maxOccurring(long int x) { // Handle negative number if (x < 0) x = -x; int result = 0; // Initialize result which is a digit int max_count = 1; // Initialize count of result // Traverse through all digits for (int d=0; d<=9; d++) { // Count occurrences of current digit int count = countOccurrences(x, d); // Update max_count and result if needed if (count >= max_count) { max_count = count; result = d; } } return result; } // Driver program int main() { long int x = 1223355; cout << ""Max occurring digit is "" << maxOccurring(x); return 0; }",constant,constant "// C++ program to bring all spaces in front of // string using swapping technique #include using namespace std; // Function to find spaces and move to beginning void moveSpaceInFront(char str[]) { // Traverse from end and swap spaces int i = strlen(str)-1; for (int j = i; j >= 0; j--) if (str[j] != ' ') swap(str[i--], str[j]); } // Driver code int main() { char str[] = ""Hey there, it's GeeksforGeeks""; moveSpaceInFront(str); cout << str; return 0; }",constant,linear "// CPP program to bring all spaces in front of // string using swapping technique #include using namespace std; // Function to find spaces and move to beginning void moveSpaceInFront(char str[]) { // Keep copying non-space characters int i = strlen(str); for (int j=i; j >= 0; j--) if (str[j] != ' ') str[i--] = str[j]; // Move spaces to be beginning while (i >= 0) str[i--] = ' '; } // Driver code int main() { char str[] = ""Hey there, it's GeeksforGeeks""; moveSpaceInFront(str); cout << str; return 0; }",constant,linear "// C++ program to put spaces between words starting // with capital letters. #include using namespace std; // Function to amend the sentence void amendSentence(string str) { // Traverse the string for(int i=0; i < str.length(); i++) { // Convert to lowercase if its // an uppercase character if (str[i]>='A' && str[i]<='Z') { str[i]=str[i]+32; // Print space before it // if its an uppercase character if (i != 0) cout << "" ""; // Print the character cout << str[i]; } // if lowercase character // then just print else cout << str[i]; } } // Driver code int main() { string str =""BruceWayneIsBatman""; amendSentence(str); return 0; }",constant,linear "// C++ program to remove spaces using stringstream #include using namespace std; // Function to remove spaces string removeSpaces(string str) { stringstream ss; string temp; // Storing the whole string // into string stream ss << str; // Making the string empty str = """"; // Running loop till end of stream while (!ss.eof()) { // Extracting word by word from stream ss >> temp; // Concatenating in the string to be // returned str = str + temp; } return str; } // Driver function int main() { // Sample Inputs string s = ""This is a test""; cout << removeSpaces(s) << endl; s = ""geeks for geeks""; cout << removeSpaces(s) << endl; s = ""geeks quiz is awesome!""; cout << removeSpaces(s) << endl; s = ""I love to code""; cout << removeSpaces(s) << endl; return 0; }",linear,linear "// C++ program to remove spaces using stringstream // and getline() #include using namespace std; // Function to remove spaces string removeSpaces(string str) { // Storing the whole string // into string stream stringstream ss(str); string temp; // Making the string empty str = """"; // Running loop till end of stream // and getting every word while (getline(ss, temp, ' ')) { // Concatenating in the string // to be returned str = str + temp; } return str; } // Driver function int main() { // Sample Inputs string s = ""This is a test""; cout << removeSpaces(s) << endl; s = ""geeks for geeks""; cout << removeSpaces(s) << endl; s = ""geeks quiz is awesome!""; cout << removeSpaces(s) << endl; s = ""I love to code""; cout << removeSpaces(s) << endl; return 0; } // Code contributed by saychakr13",linear,linear "// C++ program to implement custom trim() function #include using namespace std; // Function to in-place trim all spaces in the // string such that all words should contain only // a single space between them. void removeSpaces(string &str) { // n is length of the original string int n = str.length(); // i points to next position to be filled in // output string/ j points to next character // in the original string int i = 0, j = -1; // flag that sets to true is space is found bool spaceFound = false; // Handles leading spaces while (++j < n && str[j] == ' '); // read all characters of original string while (j < n) { // if current characters is non-space if (str[j] != ' ') { // remove preceding spaces before dot, // comma & question mark if ((str[j] == '.' || str[j] == ',' || str[j] == '?') && i - 1 >= 0 && str[i - 1] == ' ') str[i - 1] = str[j++]; else // copy current character at index i // and increment both i and j str[i++] = str[j++]; // set space flag to false when any // non-space character is found spaceFound = false; } // if current character is a space else if (str[j++] == ' ') { // If space is encountered for the first // time after a word, put one space in the // output and set space flag to true if (!spaceFound) { str[i++] = ' '; spaceFound = true; } } } // Remove trailing spaces if (i <= 1) str.erase(str.begin() + i, str.end()); else str.erase(str.begin() + i - 1, str.end()); } // Driver Code int main() { string str = "" Hello Geeks . Welcome to"" "" GeeksforGeeks . ""; removeSpaces(str); cout << str; return 0; }",constant,linear "#include using namespace std; void replaceSpaces(string input) { string rep = ""%20""; for(int i=0 ; i // Maximum length of string after modifications. const int MAX = 1000; // Replaces spaces with %20 in-place and returns // new length of modified string. It returns -1 // if modified string cannot be stored in str[] int replaceSpaces(char str[]) { // count spaces and find current length int space_count = 0, i; for (i = 0; str[i]; i++) if (str[i] == ' ') space_count++; // Remove trailing spaces while (str[i-1] == ' ') { space_count--; i--; } // Find new length. int new_length = i + space_count * 2 + 1; // New length must be smaller than length // of string provided. if (new_length > MAX) return -1; // Start filling character from end int index = new_length - 1; // Fill string termination. str[index--] = '\0'; // Fill rest of the string from end for (int j=i-1; j>=0; j--) { // inserts %20 in place of space if (str[j] == ' ') { str[index] = '0'; str[index - 1] = '2'; str[index - 2] = '%'; index = index - 3; } else { str[index] = str[j]; index--; } } return new_length; } // Driver code int main() { char str[MAX] = ""Mr John Smith ""; // Prints the replaced string int new_length = replaceSpaces(str); for (int i=0; i using namespace std; // Function to find string which has first // character of each word. string firstLetterWord(string str) { string result = """"; // Traverse the string. bool v = true; for (int i=0; i using namespace std; string processWords(char *input) { /* we are splitting the input based on spaces (s)+ : this regular expression will handle scenarios where we have words separated by multiple spaces */ char *p; vector s; p = strtok(input, "" ""); while (p != NULL) { s.push_back(p); p = strtok(NULL, "" ""); } string charBuffer; for (string values : s) /* charAt(0) will pick only the first character from the string and append to buffer */ charBuffer += values[0]; return charBuffer; } // Driver code int main() { char input[] = ""geeks for geeks""; cout << processWords(input); return 0; } // This code is contributed by // sanjeev2552",linear,quadratic "// C++ program to print all strings that can be // made by placing spaces #include using namespace std; void printSubsequences(string str) { int n = str.length(); unsigned int opsize = pow(2, n - 1); for (int counter = 0; counter < opsize; counter++) { for (int j = 0; j < n; j++) { cout << str[j]; if (counter & (1 << j)) cout << "" ""; } cout << endl; } } // Driver code int main() { string str = ""ABC""; printSubsequences(str); return 0; }",constant,quadratic "// C++ program to check whether two strings are anagrams // of each other #include using namespace std; /* function to check whether two strings are anagram of each other */ bool areAnagram(string str1, string str2) { // Get lengths of both strings int n1 = str1.length(); int n2 = str2.length(); // If length of both strings is not same, then they // cannot be anagram if (n1 != n2) return false; // Sort both the strings sort(str1.begin(), str1.end()); sort(str2.begin(), str2.end()); // Compare sorted strings for (int i = 0; i < n1; i++) if (str1[i] != str2[i]) return false; return true; } // Driver code int main() { string str1 = ""gram""; string str2 = ""arm""; // Function Call if (areAnagram(str1, str2)) cout << ""The two strings are anagram of each other""; else cout << ""The two strings are not anagram of each "" ""other""; return 0; }",constant,nlogn "// C++ program to check if two strings // are anagrams of each other #include using namespace std; #define NO_OF_CHARS 256 /* function to check whether two strings are anagram of each other */ bool areAnagram(char* str1, char* str2) { // Create 2 count arrays and initialize all values as 0 int count1[NO_OF_CHARS] = { 0 }; int count2[NO_OF_CHARS] = { 0 }; int i; // For each character in input strings, increment count // in the corresponding count array for (i = 0; str1[i] && str2[i]; i++) { count1[str1[i]]++; count2[str2[i]]++; } // If both strings are of different length. Removing // this condition will make the program fail for strings // like ""aaca"" and ""aca"" if (str1[i] || str2[i]) return false; // Compare count arrays for (i = 0; i < NO_OF_CHARS; i++) if (count1[i] != count2[i]) return false; return true; } /* Driver code*/ int main() { char str1[] = ""gram""; char str2[] = ""arm""; // Function Call if (areAnagram(str1, str2)) cout << ""The two strings are anagram of each other""; else cout << ""The two strings are not anagram of each "" ""other""; return 0; } // This is code is contributed by rathbhupendra",constant,linear "// C++ program to check if two strings // are anagrams of each other #include using namespace std; #define NO_OF_CHARS 256 bool areAnagram(char* str1, char* str2) { // Create a count array and initialize all values as 0 int count[NO_OF_CHARS] = { 0 }; int i; // For each character in input strings, increment count // in the corresponding count array for (i = 0; str1[i] && str2[i]; i++) { count[str1[i]]++; count[str2[i]]--; } // If both strings are of different length. Removing // this condition will make the program fail for strings // like ""aaca"" and ""aca"" if (str1[i] || str2[i]) return false; // See if there is any non-zero value in count array for (i = 0; i < NO_OF_CHARS; i++) if (count[i]) return false; return true; } // Driver code int main() { char str1[] = ""gram""; char str2[] = ""arm""; // Function call if (areAnagram(str1, str2)) cout << ""The two strings are anagram of each other""; else cout << ""The two strings are not anagram of each "" ""other""; return 0; }",constant,linear "// C++ implementation of the approach // Function that returns true if a and b // are anagarams of each other #include using namespace std; bool isAnagram(string a, string b) { // Check if length of both strings is same or not if (a.length() != b.length()) { return false; } // Create a HashMap containing Character as Key and // Integer as Value. We will be storing character as // Key and count of character as Value. unordered_map Map; // Loop over all character of String a and put in // HashMap. for (int i = 0; i < a.length(); i++) { Map[a[i]]++; } // Now loop over String b for (int i = 0; i < b.length(); i++) { // Check if current character already exists in // HashMap/map if (Map.find(b[i]) != Map.end()) { // If contains reduce count of that // character by 1 to indicate that current // character has been already counted as // idea here is to check if in last count of // all characters in last is zero which // means all characters in String a are // present in String b. Map[b[i]] -= 1; } else { return false; } } // Loop over all keys and check if all keys are 0. // If so it means it is anagram. for (auto items : Map) { if (items.second != 0) { return false; } } // Returning True as all keys are zero return true; } // Driver code int main() { string str1 = ""gram""; string str2 = ""arm""; // Function call if (isAnagram(str1, str2)) cout << ""The two strings are anagram of each other"" << endl; else cout << ""The two strings are not anagram of each "" ""other"" << endl; } // This code is contributed by shinjanpatra",constant,linear "// C++ program to search all anagrams of a pattern in a text #include #define MAX 256 using namespace std; // This function returns true if contents of arr1[] and // arr2[] are same, otherwise false. bool compare(char arr1[], char arr2[]) { for (int i = 0; i < MAX; i++) if (arr1[i] != arr2[i]) return false; return true; } // This function search for all permutations of pat[] in // txt[] void search(char* pat, char* txt) { int M = strlen(pat), N = strlen(txt); // countP[]: Store count of all characters of pattern // countTW[]: Store count of current window of text char countP[MAX] = { 0 }, countTW[MAX] = { 0 }; for (int i = 0; i < M; i++) { (countP[pat[i]])++; (countTW[txt[i]])++; } // Traverse through remaining characters of pattern for (int i = M; i < N; i++) { // Compare counts of current window of text with // counts of pattern[] if (compare(countP, countTW)) cout << ""Found at Index "" << (i - M) << endl; // Add current character to current window (countTW[txt[i]])++; // Remove the first character of previous window countTW[txt[i - M]]--; } // Check for the last window in text if (compare(countP, countTW)) cout << ""Found at Index "" << (N - M) << endl; } /* Driver program to test above function */ int main() { char txt[] = ""BACDGABCDA""; char pat[] = ""ABCD""; search(pat, txt); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",linear,linear "// C++ program to find minimum number of characters // to be removed to make two strings anagram. #include using namespace std; const int CHARS = 26; // function to calculate minimum numbers of characters // to be removed to make two strings anagram int remAnagram(string str1, string str2) { // make hash array for both string and calculate // frequency of each character int count1[CHARS] = {0}, count2[CHARS] = {0}; // count frequency of each character in first string for (int i=0; str1[i]!='\0'; i++) count1[str1[i]-'a']++; // count frequency of each character in second string for (int i=0; str2[i]!='\0'; i++) count2[str2[i]-'a']++; // traverse count arrays to find number of characters // to be removed int result = 0; for (int i=0; i<26; i++) result += abs(count1[i] - count2[i]); return result; } // Driver program to run the case int main() { string str1 = ""bcadeh"", str2 = ""hea""; cout << remAnagram(str1, str2); return 0; }",constant,linear "// C++ implementation to count number of deletions // required from two strings to create an anagram #include using namespace std; const int CHARS = 26; int countDeletions(string str1, string str2) { int arr[CHARS] = {0}; for (int i = 0; i < str1.length(); i++) arr[str1[i] - 'a']++; for (int i = 0; i < str2.length(); i++) arr[str2[i] - 'a']--; long long int ans = 0; for(int i = 0; i < CHARS; i++) ans +=abs(arr[i]); return ans; } int main() { string str1 = ""bcadeh"", str2 = ""hea""; cout << countDeletions(str1, str2); return 0; }",constant,linear "// C++ program to check if two strings are k anagram // or not. #include using namespace std; const int MAX_CHAR = 26; // Function to check that string is k-anagram or not bool arekAnagrams(string str1, string str2, int k) { // If both strings are not of equal // length then return false int n = str1.length(); if (str2.length() != n) return false; int count1[MAX_CHAR] = {0}; int count2[MAX_CHAR] = {0}; // Store the occurrence of all characters // in a hash_array for (int i = 0; i < n; i++) count1[str1[i]-'a']++; for (int i = 0; i < n; i++) count2[str2[i]-'a']++; int count = 0; // Count number of characters that are // different in both strings for (int i = 0; i < MAX_CHAR; i++) if (count1[i] > count2[i]) count = count + abs(count1[i]-count2[i]); // Return true if count is less than or // equal to k return (count <= k); } // Driver code int main() { string str1 = ""anagram""; string str2 = ""grammar""; int k = 2; if (arekAnagrams(str1, str2, k)) cout << ""Yes""; else cout<< ""No""; return 0; }",constant,linear "// Optimized C++ program to check if two strings // are k anagram or not. #include using namespace std; const int MAX_CHAR = 26; // Function to check if str1 and str2 are k-anagram // or not bool areKAnagrams(string str1, string str2, int k) { // If both strings are not of equal // length then return false int n = str1.length(); if (str2.length() != n) return false; int hash_str1[MAX_CHAR] = {0}; // Store the occurrence of all characters // in a hash_array for (int i = 0; i < n ; i++) hash_str1[str1[i]-'a']++; // Store the occurrence of all characters // in a hash_array int count = 0; for (int i = 0; i < n ; i++) { if (hash_str1[str2[i]-'a'] > 0) hash_str1[str2[i]-'a']--; else count++; if (count > k) return false; } // Return true if count is less than or // equal to k return true; } // Driver code int main() { string str1 = ""fodr""; string str2 = ""gork""; int k = 2; if (areKAnagrams(str1, str2, k) == true) cout << ""Yes""; else cout << ""No""; return 0; }",constant,linear "// CPP program for the above approach #include using namespace std; // Function to check k // anagram of two strings bool kAnagrams(string str1, string str2, int k) { int flag = 0; // First Condition: If both the // strings have different length , // then they cannot form anagram if (str1.length() != str2.length()) return false; int n = str1.length(); // Converting str1 to Character Array arr1 char arr1[n]; // Converting str2 to Character Array arr2 char arr2[n]; strcpy(arr1, str1.c_str()); strcpy(arr2, str2.c_str()); // Sort arr1 in increasing order sort(arr1, arr1 + n); // Sort arr2 in increasing order sort(arr2, arr2 + n); vector list; // Iterate till str1.length() for (int i = 0; i < str1.length(); i++) { // Condition if arr1[i] is // not equal to arr2[i] // then add it to list if (arr1[i] != arr2[i]) { list.push_back(arr2[i]); } } // Condition to check if // strings for K-anagram or not if (list.size() <= k) flag = 1; if (flag == 1) return true; else return false; } // Driver Code int main() { string str1 = ""anagram"", str2 = ""grammar""; int k = 3; // Function Call kAnagrams(str1, str2, k); if (kAnagrams(str1, str2, k) == true) cout << ""Yes""; else cout << ""No""; // This code is contributed by bolliranadheer }",constant,linear "// C++ program to check if binary // representations of two numbers are anagrams. #include using namespace std; // Check each bit in a number is set or not // and return the total count of the set bits. int countSetBits(int n) { int count = 0; while (n) { count += n & 1; n >>= 1; } return count; } bool areAnagrams(int A, int B) { return countSetBits(A) == countSetBits(B); } // Driver code int main() { int a = 8, b = 4; cout << areAnagrams(a, b) << endl; return 0; } // This code is contributed by phasing17",constant,constant "// C++ program for finding all anagram // pairs in the given array #include #include #include #include using namespace std; // Utility function for // printing anagram list void printAnagram(unordered_map >& store) { for (auto it:store) { vector temp_vec(it.second); int size = temp_vec.size(); for (int i = 0; i < size; i++) cout << temp_vec[i] << "" ""; cout << ""\n""; } } // Utility function for storing // the vector of strings into HashMap void storeInMap(vector& vec) { unordered_map > store; for (int i = 0; i < vec.size(); i++) { string tempString(vec[i]); // sort the string sort(tempString.begin(),tempString.end()); // make hash of a sorted string store[tempString].push_back(vec[i]); } // print utility function for printing // all the anagrams printAnagram(store); } // Driver code int main() { // initialize vector of strings vector arr; arr.push_back(""geeksquiz""); arr.push_back(""geeksforgeeks""); arr.push_back(""abcd""); arr.push_back(""forgeeksgeeks""); arr.push_back(""zuiqkeegs""); arr.push_back(""cat""); arr.push_back(""act""); arr.push_back(""tca""); // utility function for storing // strings into hashmap storeInMap(arr); return 0; }",linear,quadratic "// C++ program to count total anagram // substring of a string #include using namespace std; // Total number of lowercase characters #define MAX_CHAR 26 // Utility method to return integer index // of character 'c' int toNum(char c) { return (c - 'a'); } // Returns count of total number of anagram // substrings of string str int countOfAnagramSubstring(string str) { int N = str.length(); // To store counts of substrings with given // set of frequencies. map, int> mp; // loop for starting index of substring for (int i=0; i freq(MAX_CHAR, 0); // loop for length of substring for (int j=i; jsecond; result += ((freq) * (freq-1))/2; } return result; } // Driver code to test above methods int main() { string str = ""xyyx""; cout << countOfAnagramSubstring(str) << endl; return 0; }",linear,quadratic "// C++ Program to find minimum number // of manipulations required to make // two strings identical #include using namespace std; // Counts the no of manipulations // required int countManipulations(string s1, string s2) { int count = 0; // store the count of character int char_count[26]; for (int i = 0; i < 26; i++) { char_count[i] = 0; } // iterate though the first String // and update count for (int i = 0; i < s1.length(); i++) char_count[s1[i] - 'a']++; // iterate through the second string // update char_count. // if character is not found in // char_count then increase count for (int i = 0; i < s2.length(); i++) { char_count[s2[i] - 'a']--; } for(int i = 0; i < 26; ++i) { if(char_count[i] != 0) { count+=abs(char_count[i]); } } return count / 2; } // Driver code int main() { string s1 = ""ddcf""; string s2 = ""cedk""; cout< #include using namespace std; // A utility function to check if a string str is palindrome bool isPalindrome(string str) { // Start from leftmost and rightmost corners of str int l = 0; int h = str.length() - 1; // Keep comparing characters while they are same while (h > l) if (str[l++] != str[h--]) return false; // If we reach here, then all characters were matching return true; } // Function to check if a given string is a rotation of a // palindrome. bool isRotationOfPalindrome(string str) { // If string itself is palindrome if (isPalindrome(str)) return true; // Now try all rotations one by one int n = str.length(); for (int i = 0; i < n - 1; i++) { string str1 = str.substr(i + 1, n - i - 1); string str2 = str.substr(0, i + 1); // Check if this rotation is palindrome if (isPalindrome(str1.append(str2))) return true; } return false; } // Driver program to test above function int main() { cout << isRotationOfPalindrome(""aab"") << endl; cout << isRotationOfPalindrome(""abcde"") << endl; cout << isRotationOfPalindrome(""aaaad"") << endl; return 0; }",linear,quadratic "#include using namespace std; // A function to check if n is palindrome int isPalindrome(int n) { // Find reverse of n int rev = 0; for (int i = n; i > 0; i /= 10) rev = rev*10 + i%10; // If n and rev are same, then n is palindrome return (n==rev); } // prints palindrome between min and max void countPal(int min, int max) { for (int i = min; i <= max; i++) if (isPalindrome(i)) cout << i << "" ""; } // Driver program to test above function int main() { countPal(100, 2000); return 0; }",constant,logn "// A Dynamic Programming based program to find // minimum number insertions needed to make a // string palindrome #include using namespace std; // A DP function to find minimum // number of insertions int findMinInsertionsDP(char str[], int n) { // Create a table of size n*n. table[i][j] // will store minimum number of insertions // needed to convert str[i..j] to a palindrome. int table[n][n], l, h, gap; // Initialize all table entries as 0 memset(table, 0, sizeof(table)); // Fill the table for (gap = 1; gap < n; ++gap) for (l = 0, h = gap; h < n; ++l, ++h) table[l][h] = (str[l] == str[h])? table[l + 1][h - 1] : (min(table[l][h - 1], table[l + 1][h]) + 1); // Return minimum number of insertions // for str[0..n-1] return table[0][n - 1]; } // Driver Code int main() { char str[] = ""geeks""; cout << findMinInsertionsDP(str, strlen(str)); return 0; } // This is code is contributed by rathbhupendra",quadratic,quadratic "// An LCS based program to find minimum number // insertions needed to make a string palindrome #include using namespace std; // Returns length of LCS for X[0..m-1], Y[0..n-1]. int lcs( string X, string Y, int m, int n ) { int L[m+1][n+1]; int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return L[m][n]; } void reverseStr(string& str) { int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } // LCS based function to find minimum number of // insertions int findMinInsertionsLCS(string str, int n) { // Creata another string to store reverse of 'str' string rev = """"; rev = str; reverseStr(rev); // The output is length of string minus length of lcs of // str and it reverse return (n - lcs(str, rev, n, n)); } // Driver code int main() { string str = ""geeks""; cout << findMinInsertionsLCS(str, str.length()); return 0; } // This code is contributed by rathbhupendra",quadratic,quadratic "// An LCS based program to find minimum number // insertions needed to make a string palindrome #include using namespace std; // Returns length of LCS for X[0..m-1], Y[0..n-1]. int lcs(string X, string Y, int m, int n) { vector prev(n + 1, 0), curr(n + 1, 0); int i, j; for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) prev[j] = 0; else if (X[i - 1] == Y[j - 1]) curr[j] = prev[j - 1] + 1; else curr[j] = max(prev[j], curr[j - 1]); } prev = curr; } /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ return prev[n]; } void reverseStr(string& str) { int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } // LCS based function to find minimum number of // insertions int findMinInsertionsLCS(string str, int n) { // Creata another string to store reverse of 'str' string rev = """"; rev = str; reverseStr(rev); // The output is length of string minus length of lcs of // str and it reverse return (n - lcs(str, rev, n, n)); } // Driver code int main() { string str = ""geeks""; cout << findMinInsertionsLCS(str, str.length()); return 0; } // This code is contributed by Sanskar",linear,quadratic "// A O(n^2) time and O(1) space program to // find the longest palindromic substring // easy to understand as compared to previous version. #include using namespace std; int maxLength; // variables to store and string res; // update maxLength and res // A utility function to get the longest palindrome // starting and expanding out from given center indices void cSubUtil(string& s, int l, int r) { // check if the indices lie in the range of string // and also if it is palindrome while (l >= 0 && r < s.length() && s[l] == s[r]) { // expand the boundary l--; r++; } // if it's length is greater than maxLength update // maxLength and res if (r - l - 1 >= maxLength) { res = s.substr(l + 1, r - l - 1); maxLength = r - l - 1; } return; } // A function which takes a string prints the LPS and // returns the length of LPS int longestPalSubstr(string str) { res = """"; maxLength = 1; // for every index in the string check palindromes // starting from that index for (int i = 0; i < str.length(); i++) { // check for odd length palindromes cSubUtil(str, i, i); // check for even length palindromes cSubUtil(str, i, i + 1); } cout << ""Longest palindrome substring is: ""; cout << res << ""\n""; return maxLength; } // Driver program to test above functions int main() { string str = ""forgeeksskeegfor""; cout << ""\nLength is: "" << longestPalSubstr(str) << endl; return 0; }",constant,quadratic "// c++ program to Count number of ways we // can get palindrome string from a given // string #include using namespace std; // function to find the substring of the // string string substring(string s,int a,int b) { string s1=""""; // extract the specified position of // the string for(int i = a; i < b; i++) s1 = s1 + s[i]; return s1; } // can get palindrome string from a // given string vector allPalindromeSubstring(string s) { vector v ; // moving the pivot from starting till // end of the string for (float pivot = 0; pivot < s.length(); pivot += .5) { // set radius to the first nearest // element on left and right float palindromeRadius = pivot - (int)pivot; // if the position needs to be // compared has an element and the // characters at left and right // matches while ((pivot + palindromeRadius) < s.length() && (pivot - palindromeRadius) >= 0 && s[((int)(pivot - palindromeRadius))] == s[((int)(pivot + palindromeRadius))]) { v.push_back(substring(s,(int)(pivot - palindromeRadius), (int)(pivot + palindromeRadius + 1))); // increasing the radius by 1 to point // to the next elements in left and right palindromeRadius++; } } return v; } // Driver code int main() { vector v = allPalindromeSubstring(""hellolle""); cout << v.size() << endl; for(int i = 0; i < v.size(); i++) cout << v[i] << "",""; cout << endl; v = allPalindromeSubstring(""geeksforgeeks""); cout << v.size() << endl; for(int i = 0; i < v.size(); i++) cout << v[i] << "",""; } // This code is contributed by Arnab Kundu.",linear,cubic "// C++ program to print all palindromic partitions // of a given string. #include using namespace std; // Returns true if str is palindrome, else false bool checkPalindrome(string str) { int len = str.length(); len--; for (int i=0; i > partitions) { for (int i = 0; i < partitions.size(); ++i) { for(int j = 0; j < partitions[i].size(); ++j) cout << partitions[i][j] << "" ""; cout << endl; } return; } // Goes through all indexes and recursively add remaining // partitions if current string is palindrome. void addStrings(vector > &v, string &s, vector &temp, int index) { int len = s.length(); string str; vector current = temp; if (index == 0) temp.clear(); for (int i = index; i < len; ++i) { str = str + s[i]; if (checkPalindrome(str)) { temp.push_back(str); if (i+1 < len) addStrings(v,s,temp,i+1); else v.push_back(temp); temp = current; } } return; } // Generates all palindromic partitions of 's' and // stores the result in 'v'. void partition(string s, vector >&v) { vector temp; addStrings(v, s, temp, 0); printSolution(v); return; } // Driver code int main() { string s = ""geeks""; vector > partitions; partition(s, partitions); return 0; }",linear,quadratic "// Counts Palindromic Subsequence in a given String #include #include using namespace std; // Function return the total palindromic subsequence int countPS(string str) { int N = str.length(); // create a 2D array to store the count of palindromic // subsequence int cps[N + 1][N + 1]; memset(cps, 0, sizeof(cps)); // palindromic subsequence of length 1 for (int i = 0; i < N; i++) cps[i][i] = 1; // check subsequence of length L is palindrome or not for (int L = 2; L <= N; L++) { for (int i = 0; i <= N-L; i++) { int k = L + i - 1; if (str[i] == str[k]) cps[i][k] = cps[i][k - 1] + cps[i + 1][k] + 1; else cps[i][k] = cps[i][k - 1] + cps[i + 1][k] - cps[i + 1][k - 1]; } } // return total palindromic subsequence return cps[0][N - 1]; } // Driver program int main() { string str = ""abcb""; cout << ""Total palindromic subsequence are : "" << countPS(str) << endl; return 0; }",quadratic,quadratic "// C++ program to counts Palindromic Subsequence // in a given String using recursion #include using namespace std; int n, dp[1000][1000]; string str = ""abcb""; // Function return the total // palindromic subsequence int countPS(int i, int j) { if (i > j) return 0; if (dp[i][j] != -1) return dp[i][j]; if (i == j) return dp[i][j] = 1; else if (str[i] == str[j]) return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) + 1; else return dp[i][j] = countPS(i + 1, j) + countPS(i, j - 1) - countPS(i + 1, j - 1); } // Driver code int main() { memset(dp, -1, sizeof(dp)); n = str.size(); cout << ""Total palindromic subsequence are : "" << countPS(0, n - 1) << endl; return 0; } // this code is contributed by Kushdeep Mittal",quadratic,quadratic "// C++ program for getting minimum character to be // added at front to make string palindrome #include using namespace std; // function for checking string is palindrome or not bool ispalindrome(string s) { int l = s.length(); int j; for(int i = 0, j = l - 1; i <= j; i++, j--) { if(s[i] != s[j]) return false; } return true; } // Driver code int main() { string s = ""BABABAA""; int cnt = 0; int flag = 0; while(s.length()>0) { // if string becomes palindrome then break if(ispalindrome(s)) { flag = 1; break; } else { cnt++; // erase the last element of the string s.erase(s.begin() + s.length() - 1); } } // print the number of insertion at front if(flag) cout << cnt; }",constant,quadratic "// C++ program for getting minimum character to be // added at front to make string palindrome #include using namespace std; // returns vector lps for given string str vector computeLPSArray(string str) { int M = str.length(); vector lps(M); int len = 0; lps[0] = 0; // lps[0] is always 0 // the loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (str[i] == str[len]) { len++; lps[i] = len; i++; } else // (str[i] != str[len]) { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len-1]; // Also, note that we do not increment // i here } else // if (len == 0) { lps[i] = 0; i++; } } } return lps; } // Method returns minimum character to be added at // front to make string palindrome int getMinCharToAddedToMakeStringPalin(string str) { string revStr = str; reverse(revStr.begin(), revStr.end()); // Get concatenation of string, special character // and reverse string string concat = str + ""$"" + revStr; // Get LPS array of this concatenated string vector lps = computeLPSArray(concat); // By subtracting last entry of lps vector from // string length, we will get our result return (str.length() - lps.back()); } // Driver program to test above functions int main() { string str = ""AACECAAAA""; cout << getMinCharToAddedToMakeStringPalin(str); return 0; }",linear,linear "/* A C++ program to answer queries to check whether the substrings are palindrome or not efficiently */ #include using namespace std; #define p 101 #define MOD 1000000007 // Structure to represent a query. A query consists // of (L, R) and we have to answer whether the substring // from index-L to R is a palindrome or not struct Query { int L, R; }; // A function to check if a string str is palindrome // in the range L to R bool isPalindrome(string str, int L, int R) { // Keep comparing characters while they are same while (R > L) if (str[L++] != str[R--]) return (false); return (true); } // A Function to find pow (base, exponent) % MOD // in log (exponent) time unsigned long long int modPow( unsigned long long int base, unsigned long long int exponent) { if (exponent == 0) return 1; if (exponent == 1) return base; unsigned long long int temp = modPow(base, exponent / 2); if (exponent % 2 == 0) return (temp % MOD * temp % MOD) % MOD; else return (((temp % MOD * temp % MOD) % MOD) * base % MOD) % MOD; } // A Function to calculate Modulo Multiplicative Inverse of 'n' unsigned long long int findMMI(unsigned long long int n) { return modPow(n, MOD - 2); } // A Function to calculate the prefix hash void computePrefixHash( string str, int n, unsigned long long int prefix[], unsigned long long int power[]) { prefix[0] = 0; prefix[1] = str[0]; for (int i = 2; i <= n; i++) prefix[i] = (prefix[i - 1] % MOD + (str[i - 1] % MOD * power[i - 1] % MOD) % MOD) % MOD; return; } // A Function to calculate the suffix hash // Suffix hash is nothing but the prefix hash of // the reversed string void computeSuffixHash( string str, int n, unsigned long long int suffix[], unsigned long long int power[]) { suffix[0] = 0; suffix[1] = str[n - 1]; for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) suffix[j] = (suffix[j - 1] % MOD + (str[i] % MOD * power[j - 1] % MOD) % MOD) % MOD; return; } // A Function to answer the Queries void queryResults(string str, Query q[], int m, int n, unsigned long long int prefix[], unsigned long long int suffix[], unsigned long long int power[]) { for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] unsigned long long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] unsigned long long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then // the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) printf(""The Substring [%d %d] is a "" ""palindrome\n"", L, R); else printf(""The Substring [%d %d] is not a "" ""palindrome\n"", L, R); } else printf(""The Substring [%d %d] is not a "" ""palindrome\n"", L, R); } return; } // A Dynamic Programming Based Approach to compute the // powers of 101 void computePowers(unsigned long long int power[], int n) { // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) power[i] = (power[i - 1] % MOD * p % MOD) % MOD; return; } /* Driver program to test above function */ int main() { string str = ""abaaabaaaba""; int n = str.length(); // A Table to store the powers of 101 unsigned long long int power[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values unsigned long long int prefix[n + 1], suffix[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query q[] = { { 0, 10 }, { 5, 8 }, { 2, 5 }, { 5, 9 } }; int m = sizeof(q) / sizeof(q[0]); queryResults(str, q, m, n, prefix, suffix, power); return (0); }",linear,quadratic "// C++ program to get largest palindrome changing // atmost K digits #include using namespace std; // Returns maximum possible // palindrome using k changes string maximumPalinUsingKChanges(string str, int k) { string palin = str; // Initialize l and r by leftmost and // rightmost ends int l = 0; int r = str.length() - 1; // first try to make string palindrome while (l < r) { // Replace left and right character by // maximum of both if (str[l] != str[r]) { palin[l] = palin[r] = max(str[l], str[r]); k--; } l++; r--; } // If k is negative then we can't make // string palindrome if (k < 0) return ""Not possible""; l = 0; r = str.length() - 1; while (l <= r) { // At mid character, if K>0 then change // it to 9 if (l == r) { if (k > 0) palin[l] = '9'; } // If character at lth (same as rth) is // less than 9 if (palin[l] < '9') { /* If none of them is changed in the previous loop then subtract 2 from K and convert both to 9 */ if (k >= 2 && palin[l] == str[l] && palin[r] == str[r]) { k -= 2; palin[l] = palin[r] = '9'; } /* If one of them is changed in the previous loop then subtract 1 from K (1 more is subtracted already) and make them 9 */ else if (k >= 1 && (palin[l] != str[l] || palin[r] != str[r])) { k--; palin[l] = palin[r] = '9'; } } l++; r--; } return palin; } // Driver code to test above methods int main() { string str = ""43435""; int k = 3; cout << maximumPalinUsingKChanges(str, k); return 0; }",linear,linear "// A recursive C++ program to // check whether a given number // is palindrome or not #include using namespace std; // A recursive function that // check a str[s..e] is // palindrome or not. bool isPalRec(char str[], int s, int e) { // If there is only one character if (s == e) return true; // If first and last // characters do not match if (str[s] != str[e]) return false; // If there are more than // two characters, check if // middle substring is also // palindrome or not. if (s < e + 1) return isPalRec(str, s + 1, e - 1); return true; } bool isPalindrome(char str[]) { int n = strlen(str); // An empty string is // considered as palindrome if (n == 0) return true; return isPalRec(str, 0, n - 1); } // Driver Code int main() { char str[] = ""geeg""; if (isPalindrome(str)) cout << ""Yes""; else cout << ""No""; return 0; } // This code is contributed by shivanisinghss2110",linear,linear "#include using namespace std; bool isPalindrome(string s, int i){ if(i > s.size()/2){ return true ; } return s[i] == s[s.size()-i-1] && isPalindrome(s, i+1) ; } int main() { string str = ""geeg"" ; if (isPalindrome(str, 0)) cout << ""Yes""; else cout << ""No""; return 0; }",linear,linear "// C++ implementation to find maximum length // substring which is not palindrome #include using namespace std; // utility function to check whether // a string is palindrome or not bool isPalindrome(string str) { // Check for palindrome. int n = str.size(); for (int i=0; i < n/2; i++) if (str.at(i) != str.at(n-i-1)) return false; // palindrome string return true; } // function to find maximum length // substring which is not palindrome int maxLengthNonPalinSubstring(string str) { int n = str.size(); char ch = str.at(0); // to check whether all characters // of the string are same or not int i = 1; for (i=1; i using namespace std; /* method returns minimum step for deleting the string, where in one step a palindrome is removed */ int helper(string str, int si, int ei, vector >& dp) { // if the string is empty // need no operation if (si > ei) return 0; // string length one // need one operation if (ei - si + 1 == 1) return 1; // if already calculated if (dp[si][ei] != -1) return dp[si][ei]; // to consider three options int op1 = 1e9, op2 = 1e9, op3 = 1e9; // delete first char and call // on the smaller subproblem op1 = 1 + helper(str, si + 1, ei, dp); // first two characters are same if (str[si] == str[si + 1]) op2 = 1 + helper(str, si + 2, ei, dp); // found another index where the // character is same as si-th character for (int i = si + 2; i <= ei; i++) { if (str[si] == str[i]) op3 = min(op3, helper(str, si + 1, i - 1, dp) + helper(str, i + 1, ei, dp)); } // return the minimum b/w three options return dp[si][ei] = min({ op1, op2, op3 }); } int minStepToDeleteString(string s) { int n = s.size(); // dp table to remove repeatations vector > dp(n, vector(n, -1)); // passing starting and ending index return helper(s, 0, n - 1, dp); } // Driver Code int main() { string str = ""2553432""; cout << minStepToDeleteString(str) << endl; return 0; } // this code is contributed by rajdeep999",quadratic,quadratic "// C++ program to query number of palindromic // substrings of a string in a range #include using namespace std; #define M 50 // Utility method to construct the dp array void constructDP(int dp[M][M], string str) { int l = str.length(); // declare 2D array isPalin, isPalin[i][j] will // be 1 if str(i..j) is palindrome int isPalin[l + 1][l + 1]; // initialize dp and isPalin array by zeros for (int i = 0; i <= l; i++) { for (int j = 0; j <= l; j++) { isPalin[i][j] = dp[i][j] = 0; } } // loop for starting index of range for (int i = l - 1; i >= 0; i--) { // initialize value for one character strings as 1 isPalin[i][i] = 1; dp[i][i] = 1; // loop for ending index of range for (int j = i + 1; j < l; j++) { /* isPalin[i][j] will be 1 if ith and jth characters are equal and mid substring str(i+1..j-1) is also a palindrome */ isPalin[i][j] = (str[i] == str[j] && (i + 1 > j - 1 || isPalin[i + 1][j - 1])); /* dp[i][j] will be addition of number of palindromes from i to j-1 and i+1 to j subtracting palindromes from i+1 to j-1 (as counted twice) plus 1 if str(i..j) is also a palindrome */ dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] + isPalin[i][j]; } } } // method returns count of palindromic substring in range (l, r) int countOfPalindromeInRange(int dp[M][M], int l, int r) { return dp[l][r]; } // Driver code to test above methods int main() { string str = ""xyaabax""; int dp[M][M]; constructDP(dp, str); int l = 3; int r = 5; cout << countOfPalindromeInRange(dp, l, r); return 0; }",quadratic,quadratic "// CPP program to find minimum number // of insertions to make a string // palindrome #include using namespace std; // Function will return number of // characters to be added int minInsertion(string str) { // To store string length int n = str.length(); // To store number of characters // occurring odd number of times int res = 0; // To store count of each // character int count[26] = { 0 }; // To store occurrence of each // character for (int i = 0; i < n; i++) count[str[i] - 'a']++; // To count characters with odd // occurrence for (int i = 0; i < 26; i++) if (count[i] % 2 == 1) res++; // As one character can be odd return // res - 1 but if string is already // palindrome return 0 return (res == 0) ? 0 : res - 1; } // Driver program int main() { string str = ""geeksforgeeks""; cout << minInsertion(str); return 0; }",constant,linear "// C++ program to find n=th even length string. #include using namespace std; // Function to find nth even length Palindrome string evenlength(string n) { // string r to store resultant // palindrome. Initialize same as s string res = n; // In this loop string r stores // reverse of string s after the // string s in consecutive manner . for (int j = n.length() - 1; j >= 0; --j) res += n[j]; return res; } // Driver code int main() { string n = ""10""; // Function call cout << evenlength(n); return 0; }",linear,linear "//code to make 'ab' free string #include using namespace std; // code to make 'ab' free string int abFree(string s) { int n = s.length(); char char_array[n + 1]; // convert string into char array strcpy(char_array, s.c_str()); // Traverse from end. Keep track of count // b's. For every 'a' encountered, add b_count // to result and double b_count. int b_count = 0; int res = 0; for (int i = 0; i < n; i++) { if (char_array[n - i - 1] == 'a') { res = (res + b_count); b_count = (b_count * 2); } else { b_count += 1; } } return res; } // Driver code int main() { string s = ""abbaa""; cout< using namespace std; // Function to find the length of longest sub-string that // can me make removed // arr --> pair type of array whose first field store // character in string and second field stores // corresponding index of that character int longestNull(string str) { vector > arr; // store {'@',-1} in arr , here this value will // work as base index arr.push_back({'@', -1}); int maxlen = 0; // Initialize result // one by one iterate characters of string for (int i = 0; i < str.length(); ++i) { // make pair of char and index , then store // them into arr arr.push_back({str[i], i}); // now if last three elements of arr[] are making // sub-string ""100"" or not while (arr.size()>=3 && arr[arr.size()-3].first=='1' && arr[arr.size()-2].first=='0' && arr[arr.size()-1].first=='0') { // if above condition is true then delete // sub-string ""100"" from arr[] arr.pop_back(); arr.pop_back(); arr.pop_back(); } // index of current last element in arr[] int tmp = arr.back().second; // This is important, here 'i' is the index of // current character inserted into arr[] // and 'tmp' is the index of last element in arr[] // after continuous deletion of sub-string // ""100"" from arr[] till we make it null, difference // of these to 'i-tmp' gives the length of current // sub-string that can be make null by continuous // deletion of sub-string ""100"" maxlen = max(maxlen, i - tmp); } return maxlen; } // Driver program to run the case int main() { cout << longestNull(""1011100000100""); return 0; }",linear,linear "// C++ program to find minimum number of flip to make binary // string alternate #include using namespace std; // Utility method to flip a character char flip(char ch) { return (ch == '0') ? '1' : '0'; } // Utility method to get minimum flips when alternate // string starts with expected char int getFlipWithStartingCharcter(string str, char expected) { int flipCount = 0; for (int i = 0; i < str.length(); i++) { // if current character is not expected, increase // flip count if (str[i] != expected) flipCount++; // flip expected character each time expected = flip(expected); } return flipCount; } // method return minimum flip to make binary string // alternate int minFlipToMakeStringAlternate(string str) { // return minimum of following two // 1) flips when alternate string starts with 0 // 2) flips when alternate string starts with 1 return min(getFlipWithStartingCharcter(str, '0'), getFlipWithStartingCharcter(str, '1')); } // Driver code to test above method int main() { string str = ""0001010111""; cout << minFlipToMakeStringAlternate(str); return 0; } // This code is contributed by Sania Kumari Gupta // (kriSania804)",constant,linear "// An efficient C++ program to find 2's complement #include using namespace std; // Function to find two's complement string findTwoscomplement(string str) { int n = str.length(); // Traverse the string to get first '1' from // the last of string int i; for (i = n-1 ; i >= 0 ; i--) if (str[i] == '1') break; // If there exists no '1' concatenate 1 at the // starting of string if (i == -1) return '1' + str; // Continue traversal after the position of // first '1' for (int k = i-1 ; k >= 0; k--) { //Just flip the values if (str[k] == '1') str[k] = '0'; else str[k] = '1'; } // return the modified string return str; } // Driver code int main() { string str = ""00000101""; cout << findTwoscomplement(str); return 0; } ",constant,linear "// C++ program to count all distinct // binary strings with two consecutive 1's #include using namespace std; // Returns count of n length binary // strings with consecutive 1's int countStrings(int n) { // Count binary strings without consecutive 1's. // See the approach discussed on be // ( http://goo.gl/p8A3sW ) int a[n], b[n]; a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i - 1] + b[i - 1]; b[i] = a[i - 1]; } // Subtract a[n-1]+b[n-1] from 2^n return (1 << n) - a[n - 1] - b[n - 1]; } // Driver code int main() { cout << countStrings(5) << endl; return 0; }",linear,linear "// Recursive C++ program to generate all binary strings // formed by replacing each wildcard character by 0 or 1 #include using namespace std; // Recursive function to generate all binary strings // formed by replacing each wildcard character by 0 or 1 void print(string str, int index) { if (index == str.size()) { cout << str << endl; return; } if (str[index] == '?') { // replace '?' by '0' and recurse str[index] = '0'; print(str, index + 1); // replace '?' by '1' and recurse str[index] = '1'; print(str, index + 1); // No need to backtrack as string is passed // by value to the function } else print(str, index + 1); } // Driver code to test above function int main() { string str = ""1??0?101""; print(str, 0); return 0; }",quadratic,np "// Iterative C++ program to generate all binary // strings formed by replacing each wildcard // character by 0 or 1 #include #include using namespace std; // Iterative function to generate all binary strings // formed by replacing each wildcard character by 0 // or 1 void print(string str) { queue q; q.push(str); while (!q.empty()) { string str = q.front(); // find position of first occurrence of wildcard size_t index = str.find('?'); // If no matches were found, // find returns string::npos if(index != string::npos) { // replace '?' by '0' and push string into queue str[index] = '0'; q.push(str); // replace '?' by '1' and push string into queue str[index] = '1'; q.push(str); } else // If no wildcard characters are left, // print the string. cout << str << endl; q.pop(); } } // Driver code to test above function int main() { string str = ""1??0?101""; print(str); return 0; }",np,quadratic "// C++ program to implement the approach #include using namespace std; /* we store processed strings in all (array) we see if string as ""?"", if so, replace it with 0 and 1 and send it back to recursive func until base case is reached which is no wildcard left */ vector res; void genBin(string s) { auto pos = s.find('?'); if (pos != string::npos) { // copying s to s1 string s1 = s; // replacing first occurrence of ? // with 0 s1.replace(pos, 1, ""0""); // copying s to s2 string s2 = s; // replacing first occurrence of ? // with 1 s2.replace(pos, 1, ""1""); genBin(s1); genBin(s2); } else { res.push_back(s); } } // Driver code int main() { genBin(""1??0?101""); for (string x : res) { cout << x << "" ""; } } // This code is contributed by phasing17",np,quadratic "#include using namespace std; // The function that adds two-bit sequences and returns the addition string addBitStrings(string str1, string str2) { string ans = """"; int i = str1.size() - 1; int j = str2.size() - 1; int carry = 0; while (i >= 0 || j >= 0 || carry) { carry += ((i >= 0) ? (str1[i--] - '0') : (0)); carry += ((j >= 0) ? (str2[j--] - '0') : (0)); ans = char('0' + (carry % 2)) + ans; carry = carry / 2; } return ans; } // Driver program to test above functions int main() { string str1 = ""1100011""; string str2 = ""10""; cout << ""Sum is "" << addBitStrings(str1, str2); return 0; }",constant,linear "// C++ program to count all distinct binary strings // without two consecutive 1's #include using namespace std; int countStrings(int n) { int a[n], b[n]; a[0] = b[0] = 1; for (int i = 1; i < n; i++) { a[i] = a[i-1] + b[i-1]; b[i] = a[i-1]; } return a[n-1] + b[n-1]; } // Driver program to test above functions int main() { cout << countStrings(3) << endl; return 0; }",linear,linear "// C++ program to count all distinct binary strings // without two consecutive 1's #include using namespace std; int countStrings(int n) { int a = 1, b = 1; for (int i = 1; i < n; i++) { // Here we have used the temp variable because we // want to assign the older value of a to b int temp = a + b; b = a; a = temp; } return a + b; } // Driver program to test above functions int main() { cout << countStrings(3) << endl; return 0; } // This code is contributed by Aditya Kumar (adityakumar129)",constant,linear "// C++ program to check if a string is of // the form a^nb^n. #include using namespace std; // Returns true str is of the form a^nb^n. bool isAnBn(string str) { int n = str.length(); // After this loop 'i' has count of a's int i; for (i = 0; i < n; i++) if (str[i] != 'a') break; // Since counts of a's and b's should // be equal, a should appear exactly // n/2 times if (i * 2 != n) return false; // Rest of the characters must be all 'b' int j; for (j = i; j < n; j++) if (str[j] != 'b') return false; return true; } // Driver code int main() { string str = ""abab""; // Function call isAnBn(str) ? cout << ""Yes"" : cout << ""No""; return 0; }",constant,linear "// C++ code to check a^nb^n // pattern #include using namespace std; // Returns ""Yes"" str is of the form a^nb^n. string isAnBn(string str) { int n = str.length(); if (n & 1) return ""No""; // check first half is 'a' and other half is full of 'b' int i; for (i = 0; i < n / 2; i++) if (str[i] != 'a' || str[n - i - 1] != 'b') return ""No""; return ""Yes""; } // Driver code int main() { string str = ""ab""; // Function call cout << isAnBn(str); return 0; }",constant,linear "// C++ implementation to find the binary // representation of next greater integer #include using namespace std; // function to find the required // binary representation string nextGreater(string num) { int l = num.size(); // examine bits from the right for (int i=l-1; i>=0; i--) { // if '0' is encountered, convert // it to '1' and then break if (num.at(i) == '0') { num.at(i) = '1'; break; } // else convert '1' to '0' else num.at(i) = '0'; // if the binary representation // contains only the set bits if (i < 0) num = ""1"" + num; } // final binary representation // of the required integer return num; } // Driver program to test above int main() { string num = ""10011""; cout << ""Binary representation of next number = "" << nextGreater(num); return 0; }",linear,linear "// C++ program to find next permutation in a // binary string. #include using namespace std; // Function to find the next greater number // with same number of 1's and 0's string nextGreaterWithSameDigits(string bnum) { int l = bnum.size(); int i; for (int i=l-2; i>=1; i--) { // locate first 'i' from end such that // bnum[i]=='0' and bnum[i+1]=='1' // swap these value and break; if (bnum.at(i) == '0' && bnum.at(i+1) == '1') { char ch = bnum.at(i); bnum.at(i) = bnum.at(i+1); bnum.at(i+1) = ch; break; } } // if no swapping performed if (i == 0) ""no greater number""; // Since we want the smallest next value, // shift all 1's at the end in the binary // substring starting from index 'i+2' int j = i+2, k = l-1; while (j < k) { if (bnum.at(j) == '1' && bnum.at(k) == '0') { char ch = bnum.at(j); bnum.at(j) = bnum.at(k); bnum.at(k) = ch; j++; k--; } // special case while swapping if '0' // occurs then break else if (bnum.at(i) == '0') break; else j++; } // required next greater number return bnum; } // Driver program to test above int main() { string bnum = ""10010""; cout << ""Binary representation of next greater number = "" << nextGreaterWithSameDigits(bnum); return 0; }",constant,linear "// CPP Program to find the length of // substring with maximum difference of // zeros and ones in binary string. #include using namespace std; // Returns the length of substring with // maximum difference of zeroes and ones // in binary string int findLength(string str, int n) { int current_sum = 0; int max_sum = 0; // traverse a binary string from left // to right for (int i = 0; i < n; i++) { // add current value to the current_sum // according to the Character // if it's '0' add 1 else -1 current_sum += (str[i] == '0' ? 1 : -1); if (current_sum < 0) current_sum = 0; // update maximum sum max_sum = max(current_sum, max_sum); } // return -1 if string does not contain // any zero that means all ones // otherwise max_sum return max_sum == 0 ? -1 : max_sum; } // Driven Program int main() { string s = ""11000010001""; int n = 11; cout << findLength(s, n) << endl; return 0; }",linear,linear "// CPP program to find min flips in binary // string to make all characters equal #include using namespace std; // To find min number of flips in binary string int findFlips(char str[], int n) { char last = ' '; int res = 0; for (int i = 0; i < n; i++) { // If last character is not equal // to str[i] increase res if (last != str[i]) res++; last = str[i]; } // To return min flips return res / 2; } // Driver program to check findFlips() int main() { char str[] = ""00011110001110""; int n = strlen(str); cout << findFlips(str, n); return 0; }",constant,linear "// C++ program to add two binary strings #include using namespace std; // This function adds two binary strings and return // result as a third string string addBinary(string A, string B) { // If the length of string A is greater than the length // of B then just swap the string by calling the // same function and make sure to return the function // otherwise recursion will occur which leads to // calling the same function twice if (A.length() > B.length()) return addBinary(B, A); // Calculating the difference between the length of the // two strings. int diff = B.length() - A.length(); // Initialise the padding string which is used to store // zeroes that should be added as prefix to the string // which has length smaller than the other string. string padding; for (int i = 0; i < diff; i++) padding.push_back('0'); A = padding + A; string res; char carry = '0'; for (int i = A.length() - 1; i >= 0; i--) { // This if condition solves 110 111 possible cases if (A[i] == '1' && B[i] == '1') { if (carry == '1') res.push_back('1'), carry = '1'; else res.push_back('0'), carry = '1'; } // This if condition solves 000 001 possible cases else if (A[i] == '0' && B[i] == '0') { if (carry == '1') res.push_back('1'), carry = '0'; else res.push_back('0'), carry = '0'; } // This if condition solves 100 101 010 011 possible // cases else if (A[i] != B[i]) { if (carry == '1') res.push_back('0'), carry = '1'; else res.push_back('1'), carry = '0'; } } // If at the end there is carry then just add it to the // result if (carry == '1') res.push_back(carry); // reverse the result reverse(res.begin(), res.end()); // To remove leading zeroes int index = 0; while (index + 1 < res.length() && res[index] == '0') index++; return (res.substr(index)); } // Driver program int main() { string a = ""1101"", b = ""100""; cout << addBinary(a, b) << endl; return 0; }",linear,linear "// C++ program to convert // string into binary string #include using namespace std; // utility function void strToBinary(string s) { int n = s.length(); for (int i = 0; i <= n; i++) { // convert each char to // ASCII value int val = int(s[i]); // Convert ASCII value to binary string bin = """"; while (val > 0) { (val % 2)? bin.push_back('1') : bin.push_back('0'); val /= 2; } reverse(bin.begin(), bin.end()); cout << bin << "" ""; } } // driver code int main() { string s = ""geeks""; strToBinary(s); return 0; }",linear,linear "// C++ program to Generate // all binary string without // consecutive 1's of size K #include using namespace std ; // A utility function generate all string without // consecutive 1'sof size K void generateAllStringsUtil(int K, char str[], int n) { // Print binary string without consecutive 1's if (n == K) { // Terminate binary string str[n] = '\0' ; cout << str << "" ""; return ; } // If previous character is '1' then we put // only 0 at end of string //example str = ""01"" then new string be ""010"" if (str[n-1] == '1') { str[n] = '0'; generateAllStringsUtil (K , str , n+1); } // If previous character is '0' than we put // both '1' and '0' at end of string // example str = ""00"" then // new string ""001"" and ""000"" if (str[n-1] == '0') { str[n] = '0'; generateAllStringsUtil(K, str, n+1); str[n] = '1'; generateAllStringsUtil(K, str, n+1) ; } } // Function generate all binary string without // consecutive 1's void generateAllStrings(int K ) { // Base case if (K <= 0) return ; // One by one stores every // binary string of length K char str[K]; // Generate all Binary string // starts with '0' str[0] = '0' ; generateAllStringsUtil ( K , str , 1 ) ; // Generate all Binary string // starts with '1' str[0] = '1' ; generateAllStringsUtil ( K , str , 1 ); } // Driver program to test above function int main() { int K = 3; generateAllStrings (K) ; return 0; }",linear,np "#include using namespace std; void All_Binary_Strings(bool arr[],int num,int r) { if(r==num) { for(int i=0;i using namespace std; void All_Binary_Strings(string str,int num) { int len=str.length(); if(len==num) { cout< using namespace std; // Function to store binary Representation void binary_conversion(string &s, int m) { while (m) { int tmp = m % 2; s += tmp + '0'; m = m / 2; } reverse(s.begin(), s.end()); } // Function to find ith character int find_character(int n, int m, int i) { string s; // Function to change decimal to binary binary_conversion(s, m); string s1 = """"; for (int x = 0; x < n; x++) { for (int y = 0; y < s.length(); y++) { if (s[y] == '1') s1 += ""10""; else s1 += ""01""; } // Assign s1 string in s string s = s1; s1 = """"; } return s[i] - '0'; } // Driver Function int main() { int m = 5, n = 2, i = 8; cout << find_character(n, m, i); return 0; }",linear,quadratic "// CPP program to count substrings // with odd decimal value #include using namespace std; // function to count number of substrings // with odd decimal representation int countSubstr(string s) { int n = s.length(); // auxiliary array to store count // of 1's before ith index int auxArr[n] = {0}; if (s[0] == '1') auxArr[0] = 1; // store count of 1's before // i-th index for (int i=1; i=0; i--) if (s[i] == '1') count += auxArr[i]; return count; } // Driver code int main() { string s = ""1101""; cout << countSubstr(s); return 0; }",linear,linear "// C++ program to generate n-bit Gray codes #include #include #include using namespace std; // This function generates all n bit Gray codes and prints the // generated codes void generateGrayarr(int n) { // base case if (n <= 0) return; // 'arr' will store all generated codes vector arr; // start with one-bit pattern arr.push_back(""0""); arr.push_back(""1""); // Every iteration of this loop generates 2*i codes from previously // generated i codes. int i, j; for (i = 2; i < (1<= 0 ; j--) arr.push_back(arr[j]); // append 0 to the first half for (j = 0 ; j < i ; j++) arr[j] = ""0"" + arr[j]; // append 1 to the second half for (j = i ; j < 2*i ; j++) arr[j] = ""1"" + arr[j]; } // print contents of arr[] for (i = 0 ; i < arr.size() ; i++ ) cout << arr[i] << endl; } // Driver program to test above function int main() { generateGrayarr(3); return 0; }",np,np "// C++ program to generate // n-bit Gray codes #include using namespace std; // This function generates all n // bit Gray codes and prints the // generated codes vector generateGray(int n) { // Base case if (n <= 0) return {""0""}; if (n == 1) { return {""0"",""1""}; } //Recursive case vector recAns= generateGray(n-1); vector mainAns; // Append 0 to the first half for(int i=0;i=0;i--) { string s=recAns[i]; mainAns.push_back(""1""+s); } return mainAns; } // Function to generate the // Gray code of N bits void generateGrayarr(int n) { vector arr; arr=generateGray(n); // print contents of arr for (int i = 0 ; i < arr.size(); i++ ) cout << arr[i] << endl; } // Driver Code int main() { generateGrayarr(3); return 0; }",np,np "// C++ implementation of the above approach #include using namespace std; void GreyCode(int n) { // power of 2 for (int i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form int val = (i ^ (i >> 1)); // Using bitset bitset<32> r(val); // Converting to string string s = r.to_string(); cout << s.substr(32 - n) << "" ""; } } // Driver Code int main() { int n; n = 4; // Function call GreyCode(n); return 0; }",linear,np "// C++ program to print all N-bit binary #include using namespace std; /* function to generate n digit numbers*/ void printRec(string number, int extraOnes, int remainingPlaces) { /* if number generated */ if (0 == remainingPlaces) { cout << number << "" ""; return; } /* Append 1 at the current number and reduce the remaining places by one */ printRec(number + ""1"", extraOnes + 1, remainingPlaces - 1); /* If more ones than zeros, append 0 to the current number and reduce the remaining places by one*/ if (0 < extraOnes) printRec(number + ""0"", extraOnes - 1, remainingPlaces - 1); } void printNums(int n) { string str = """"; printRec(str, 0, n); } // Driver code int main() { int n = 4; // Function call printNums(n); return 0; }",linear,linear "// C++ program to print all N-bit binary #include #include using namespace std; // Function to get the binary representation // of the number N string getBinaryRep(int N, int num_of_bits) { string r = """"; num_of_bits--; // loop for each bit while (num_of_bits >= 0) { if (N & (1 << num_of_bits)) r.append(""1""); else r.append(""0""); num_of_bits--; } return r; } vector NBitBinary(int N) { vector r; int first = 1 << (N - 1); int last = first * 2; // generate numbers in the range of (2^N)-1 to 2^(N-1) // inclusive for (int i = last - 1; i >= first; --i) { int zero_cnt = 0; int one_cnt = 0; int t = i; int num_of_bits = 0; // longest prefix check while (t) { if (t & 1) one_cnt++; else zero_cnt++; num_of_bits++; t = t >> 1; } // if counts of 1 is greater than // counts of zero if (one_cnt >= zero_cnt) { // do sub-prefixes check bool all_prefix_match = true; int msk = (1 << num_of_bits) - 2; int prefix_shift = 1; while (msk) { int prefix = (msk & i) >> prefix_shift; int prefix_one_cnt = 0; int prefix_zero_cnt = 0; while (prefix) { if (prefix & 1) prefix_one_cnt++; else prefix_zero_cnt++; prefix = prefix >> 1; } if (prefix_zero_cnt > prefix_one_cnt) { all_prefix_match = false; break; } prefix_shift++; msk = msk & (msk << 1); } if (all_prefix_match) { r.push_back(getBinaryRep(i, num_of_bits)); } } } return r; } // Driver code int main() { int n = 4; // Function call vector results = NBitBinary(n); for (int i = 0; i < results.size(); ++i) cout << results[i] << "" ""; cout << endl; return 0; }",linear,quadratic "// C++ program to add n binary strings #include using namespace std; // This function adds two binary strings and return // result as a third string string addBinaryUtil(string a, string b) { string result = """"; // Initialize result int s = 0; // Initialize digit sum // Traverse both strings starting from last // characters int i = a.size() - 1, j = b.size() - 1; while (i >= 0 || j >= 0 || s == 1) { // Compute sum of last digits and carry s += ((i >= 0) ? a[i] - '0' : 0); s += ((j >= 0) ? b[j] - '0' : 0); // If current digit sum is 1 or 3, // add 1 to result result = char(s % 2 + '0') + result; // Compute carry s /= 2; // Move to next digits i--; j--; } return result; } // function to add n binary strings string addBinary(string arr[], int n) { string result = """"; for (int i = 0; i < n; i++) result = addBinaryUtil(result, arr[i]); return result; } // Driver program int main() { string arr[] = { ""1"", ""10"", ""11"" }; int n = sizeof(arr) / sizeof(arr[0]); cout << addBinary(arr, n) << endl; return 0; }",linear,linear "// CPP program to generate power set in // lexicographic order. #include using namespace std; // str : Stores input string // n : Length of str. void func(string s, vector& str, int n, int pow_set) { int i, j; for (i = 0; i < pow_set; i++) { string x; for (j = 0; j < n; j++) { if (i & 1 << j) { x = x + s[j]; } } if (i != 0) str.push_back(x); } } int main() { int n; string s; vector str; s = ""cab""; n = s.length(); int pow_set = pow(2, n); func(s, str, n, pow_set); sort(str.begin(), str.end()); for (int i = 0; i < str.size(); i++) cout << str[i] << "" ""; cout << endl; return 0; }",constant,quadratic "// C++ program to print nth permutation with // using next_permute() #include using namespace std; // Function to print nth permutation // using next_permute() void nPermute(string str, long int n) { // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep iterating until // we reach nth position long int i = 1; do { // check for nth iteration if (i == n) break; i++; } while (next_permutation(str.begin(), str.end())); // print string after nth iteration cout << str; } // Driver code int main() { string str = ""GEEKSFORGEEKS""; long int n = 100; nPermute(str, n); return 0; }",constant,nlogn "// C++ program to print rank of // string using next_permute() #include using namespace std; // Function to print rank of string // using next_permute() int findRank(string str) { // store original string string orgStr = str; // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep iterating until // we reach equality condition long int i = 1; do { // check for nth iteration if (str == orgStr) break; i++; } while (next_permutation(str.begin(), str.end())); // return iterator value return i; } // Driver code int main() { string str = ""GEEKS""; cout << findRank(str); return 0; }",constant,nlogn "// A simple C++ program to find lexicographically minimum rotation // of a given string #include #include using namespace std; // This functionr return lexicographically minimum // rotation of str string minLexRotation(string str) { // Find length of given string int n = str.length(); // Create an array of strings to store all rotations string arr[n]; // Create a concatenation of string with itself string concat = str + str; // One by one store all rotations of str in array. // A rotation is obtained by getting a substring of concat for (int i = 0; i < n; i++) arr[i] = concat.substr(i, n); // Sort all rotations sort(arr, arr+n); // Return the first rotation from the sorted array return arr[0]; } // Driver program to test above function int main() { cout << minLexRotation(""GEEKSFORGEEKS"") << endl; cout << minLexRotation(""GEEKSQUIZ"") << endl; cout << minLexRotation(""BCABDADAB"") << endl; }",linear,quadratic "// C++ program to print all distinct subsequences // of a string. #include using namespace std; // Finds and stores result in st for a given // string s. void generate(set& st, string s) { if (s.size() == 0) return; // If current string is not already present. if (st.find(s) == st.end()) { st.insert(s); // Traverse current string, one by one // remove every character and recur. for (int i = 0; i < s.size(); i++) { string t = s; t.erase(i, 1); generate(st, t); } } return; } // Driver code int main() { string s = ""xyz""; set st; set::iterator it; generate(st, s); for (auto it = st.begin(); it != st.end(); it++) cout << *it << endl; return 0; }",linear,quadratic "// CPP code to find the lexicographically // smallest string #include using namespace std; // Compares two strings by checking if // which of the two concatenations causes // lexicographically smaller string. bool compare(string a, string b) { return (a+b < b+a); } string lexSmallest(string a[], int n) { // Sort strings using above compare() sort(a, a+n, compare); // Concatenating sorted strings string answer = """"; for (int i = 0; i < n; i++) answer += a[i]; return answer; } // Driver code int main() { string a[] = { ""c"", ""cb"", ""cba"" }; int n = sizeof(a)/sizeof(a[0]); cout << lexSmallest(a, n); return 0; }",linear,quadratic "// CPP Program to create concatenation of all // substrings in lexicographic order. #include using namespace std; string lexicographicSubConcat(string s) { int n = s.length(); // Creating an array to store substrings int sub_count = n*(n+1)/2; string arr[sub_count]; // finding all substrings of string int index = 0; for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) arr[index++] = s.substr(i, len); // Sort all substrings in lexicographic // order sort(arr, arr + sub_count); // Concatenating all substrings string res = """"; for (int i = 0; i < sub_count; i++) res += arr[i]; return res; } int main() { string s = ""abc""; cout << lexicographicSubConcat(s); return 0; }",linear,cubic "// CPP for constructing smallest palindrome #include using namespace std; // function for printing palindrome string constructPalin(string str, int len) { int i = 0, j = len - 1; // iterate till i using namespace std; // function to find Lexicographically // smallest string with hamming distance k void findString(string str, int n, int k) { // If k is 0, output input string if (k == 0) { cout << str << endl; return; } // Copying input string into output // string string str2 = str; int p = 0; // Traverse all the character of the // string for (int i = 0; i < n; i++) { // If current character is not 'a' if (str2[i] != 'a') { // copy character 'a' to // output string str2[i] = 'a'; p++; // If hamming distance became k, // break; if (p == k) break; } } // If k is less than p if (p < k) { // Traversing string in reverse // order for (int i = n - 1; i >= 0; i--) if (str[i] == 'a') { str2[i] = 'b'; p++; if (p == k) break; } } cout << str2 << endl; } // Driven Program int main() { string str = ""pqrs""; int n = str.length(); int k = 2; findString(str, n, k); return 0; }",linear,linear "// C++ program to find lexicographically next // string #include using namespace std; string nextWord(string s) { // If string is empty. if (s == """") return ""a""; // Find first character from right // which is not z. int i = s.length() - 1; while (s[i] == 'z' && i >= 0) i--; // If all characters are 'z', append // an 'a' at the end. if (i == -1) s = s + 'a'; // If there are some non-z characters else s[i]++; return s; } // Driver code int main() { string str = ""samez""; cout << nextWord(str); return 0; }",constant,linear "// C++ program to find lexicographically largest // subsequence where every character appears at // least k times. #include using namespace std; // Find lexicographically largest subsequence of // s[0..n-1] such that every character appears // at least k times. The result is filled in t[] void subsequence(char s[], char t[], int n, int k) { int last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character 'z' to 'a' for (char ch = 'z'; ch >= 'a'; ch--) { cnt = 0; // Counting the frequency of the character for (int i = last; i < n; i++) { if (s[i] == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (int i = last; i < n; i++) { // check if string contain ch if (s[i] == ch) { // If yes, append to output string t[size++] = ch; new_last = i; } } // Update the last point. last = new_last; } } t[size] = '\0'; } // Driver code int main() { char s[] = ""banana""; int n = sizeof(s); int k = 2; char t[n]; subsequence(s, t, n - 1, k); cout << t << endl; return 0; }",linear,linear "// CPP program to find the string // in lexicographic order which is // in between given two strings #include using namespace std; // Function to find the lexicographically // next string string lexNext(string s, int n) { // Iterate from last character for (int i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { s[i]++; return s; } // if 'z', change it to 'a' s[i] = 'a'; } } // Driver Code int main() { string S = ""abcdeg"", T = ""abcfgh""; int n = S.length(); string res = lexNext(S, n); // If not equal, print the // resultant string if (res != T) cout << res << endl; else cout << ""-1"" << endl; return 0; }",constant,linear "// C++ program to demonstrate working of // prev_permutation() #include using namespace std; // Driver code int main() { string str = ""4321""; if (prev_permutation(str.begin(), str.end())) cout << ""Previous permutation is "" << str; else cout << ""Previous permutation doesn't exist""; return 0; }",constant,linear "// C++ program to print all permutations with // duplicates allowed using prev_permutation() #include using namespace std; // Function to compute the previous permutation bool prevPermutation(string& str) { // Find index of the last element of the string int n = str.length() - 1; // Find largest index i such that str[i - 1] > // str[i] int i = n; while (i > 0 && str[i - 1] <= str[i]) i--; // if string is sorted in ascending order // we're at the last permutation if (i <= 0) return false; // Note - str[i..n] is sorted in ascending order // Find rightmost element's index that is less // than str[i - 1] int j = i - 1; while (j + 1 <= n && str[j + 1] < str[i - 1]) j++; // Swap character at i-1 with j swap(str[i - 1], str[j]); // Reverse the substring [i..n] reverse(str.begin() + i, str.end()); return true; } // Driver code int main() { string str = ""4321""; if (prevPermutation(str)) cout << ""Previous permutation is "" << str; else cout << ""Previous permutation doesn't exist""; return 0; }",constant,linear "// C++ program to print // n-th permutation #include using namespace std; #define ll long long int const int MAX_CHAR = 26; const int MAX_FACT = 20; ll fact[MAX_FACT]; // Utility for calculating factorials void precomputeFactorials() { fact[0] = 1; for (int i = 1; i < MAX_FACT; i++) fact[i] = fact[i - 1] * i; } // Function for nth permutation void nPermute(char str[], int n) { precomputeFactorials(); // Length of given string int len = strlen(str); // Count frequencies of all // characters int freq[MAX_CHAR] = { 0 }; for (int i = 0; i < len; i++) freq[str[i] - 'a']++; // Out string for output string char out[MAX_CHAR]; // Iterate till sum equals n int sum = 0; int k = 0; // We update both n and sum in this // loop. while (sum != n) { sum = 0; // Check for characters present in freq[] for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] == 0) continue; // Remove character freq[i]--; // Calculate sum after fixing // a particular char int xsum = fact[len - 1 - k]; for (int j = 0; j < MAX_CHAR; j++) xsum /= fact[freq[j]]; sum += xsum; // if sum > n fix that char as // present char and update sum // and required nth after fixing // char at that position if (sum >= n) { out[k++] = i + 'a'; n -= (sum - xsum); break; } // if sum < n, add character back if (sum < n) freq[i]++; } } // if sum == n means this // char will provide its // greatest permutation // as nth permutation for (int i = MAX_CHAR - 1; k < len && i >= 0; i--) if (freq[i]) { out[k++] = i + 'a'; freq[i++]--; } // append string termination // character and print result out[k] = '\0'; cout << out; } // Driver program int main() { int n = 2; char str[] = ""geeksquiz""; nPermute(str, n); return 0; }",linear,linear "// C++ program to find lexicographic rank // of a string #include using namespace std; // A utility function to find // factorial of n int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // A utility function to count // smaller characters on right of arr[low] int findSmallerInRight(string str, int low, int high) { int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight; } // A function to find rank of a string // in all permutations of characters int findRank(string str) { int len = str.size(); int mul = fact(len); int rank = 1; int countRight; int i; for (i = 0; i < len; ++i) { mul /= len - i; // Count number of chars smaller than str[i] // from str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank; } // Driver code int main() { string str = ""string""; // Function call cout << findRank(str); return 0; } // This code is contributed by Akanksha Rai",constant,quadratic "// A O(n) solution for finding rank of string #include using namespace std; #define MAX_CHAR 256 // A utility function to find factorial of n int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // Construct a count array where value at every index // contains count of smaller characters in whole string void populateAndIncreaseCount(int* count, string str) { int i; for (i = 0; str[i]; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1]; } // Removes a character ch from count[] array // constructed by populateAndIncreaseCount() void updatecount(int* count, char ch) { int i; for (i = ch; i < MAX_CHAR; ++i) --count[i]; } // A function to find rank of a string in all permutations // of characters int findRank(string str) { int len = str.size(); int mul = fact(len); int rank = 1, i; // All elements of count[] are initialized with 0 int count[MAX_CHAR] = { 0 }; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // Count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank; } // Driver code int main() { string str = ""string""; // Function call cout << findRank(str); return 0; } // This is code is contributed by rathbhupendra",constant,linear "/* C++ Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm */ #include using namespace std; # define NO_OF_CHARS 256 // The preprocessing function for Boyer Moore's // bad character heuristic void badCharHeuristic( string str, int size, int badchar[NO_OF_CHARS]) { int i; // Initialize all occurrences as -1 for (i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character for (i = 0; i < size; i++) badchar[(int) str[i]] = i; } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ void search( string txt, string pat) { int m = pat.size(); int n = txt.size(); int badchar[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text while(s <= (n - m)) { int j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s + j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { cout << ""pattern occurs at shift = "" << s << endl; /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ s += (s + m < n)? m-badchar[txt[s + m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s + j]]); } } /* Driver code */ int main() { string txt= ""ABAAABCD""; string pat = ""ABC""; search(txt, pat); return 0; } // This code is contributed by rathbhupendra",constant,quadratic "// CPP program to print the // string in 'plus' pattern #include #define max 100 using namespace std; // Function to make a cross in the matrix void carveCross(string str) { int n = str.length(); if (n % 2 == 0) { /* As, it is not possible to make the cross exactly in the middle of the matrix with an even length string.*/ cout << ""Not possible. Please enter "" << ""odd length string.\n""; } else { // declaring a 2D array i.e a matrix char arr[max][max]; int m = n / 2; /* Now, we will fill all the elements of the array with 'X'*/ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = 'X'; } } /* Now, we will place the characters of the string in the matrix, such that a cross is formed in it.*/ for (int i = 0; i < n; i++) { /* here the characters of the string will be added in the middle column of our array.*/ arr[i][m] = str[i]; } for (int i = 0; i < n; i++) { // here the characters of the // string will be added in the // middle row of our array. arr[m][i] = str[i]; } /* Now finally, we will print the array*/ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << "" ""; } cout << ""\n""; } } } // driver code int main() { string str = ""PICTURE""; carveCross(str); return 0; }",constant,quadratic "// C++ program to implement wildcard // pattern matching algorithm #include using namespace std; // Function that matches input str with // given wildcard pattern bool strmatch(char str[], char pattern[], int n, int m) { // empty pattern can only match with // empty string if (m == 0) return (n == 0); // lookup table for storing results of // subproblems bool lookup[n + 1][m + 1]; // initialize lookup table to false memset(lookup, false, sizeof(lookup)); // empty pattern can match with empty string lookup[0][0] = true; // Only '*' can match with empty string for (int j = 1; j <= m; j++) if (pattern[j - 1] == '*') lookup[0][j] = lookup[0][j - 1]; // fill the table in bottom-up fashion for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // Two cases if we see a '*' // a) We ignore ‘*’ character and move // to next character in the pattern, // i.e., ‘*’ indicates an empty sequence. // b) '*' character matches with ith // character in input if (pattern[j - 1] == '*') lookup[i][j] = lookup[i][j - 1] || lookup[i - 1][j]; // Current characters are considered as // matching in two cases // (a) current character of pattern is '?' // (b) characters actually match else if (pattern[j - 1] == '?' || str[i - 1] == pattern[j - 1]) lookup[i][j] = lookup[i - 1][j - 1]; // If characters don't match else lookup[i][j] = false; } } return lookup[n][m]; } int main() { char str[] = ""baaabab""; char pattern[] = ""*****ba*****ab""; // char pattern[] = ""ba*****ab""; // char pattern[] = ""ba*ab""; // char pattern[] = ""a*ab""; // char pattern[] = ""a*****ab""; // char pattern[] = ""*a*****ab""; // char pattern[] = ""ba*ab****""; // char pattern[] = ""****""; // char pattern[] = ""*""; // char pattern[] = ""aa?ab""; // char pattern[] = ""b*b""; // char pattern[] = ""a*a""; // char pattern[] = ""baaabab""; // char pattern[] = ""?baaabab""; // char pattern[] = ""*baaaba*""; if (strmatch(str, pattern, strlen(str), strlen(pattern))) cout << ""Yes"" << endl; else cout << ""No"" << endl; return 0; }",quadratic,quadratic "// C++ program to implement wildcard // pattern matching algorithm #include using namespace std; // Function that matches input str with // given wildcard pattern vector > dp; int finding(string& s, string& p, int n, int m) { // return 1 if n and m are negative if (n < 0 && m < 0) return 1; // return 0 if m is negative if (m < 0) return 0; // return n if n is negative if (n < 0) { // while m is positive while (m >= 0) { if (p[m] != '*') return 0; m--; } return 1; } // if dp state is not visited if (dp[n][m] == -1) { if (p[m] == '*') { return dp[n][m] = finding(s, p, n - 1, m) || finding(s, p, n, m - 1); } else { if (p[m] != s[n] && p[m] != '?') return dp[n][m] = 0; else return dp[n][m] = finding(s, p, n - 1, m - 1); } } // return dp[n][m] if dp state is previsited return dp[n][m]; } bool isMatch(string s, string p) { dp.clear(); // resize the dp array dp.resize(s.size() + 1, vector(p.size() + 1, -1)); return dp[s.size()][p.size()] = finding(s, p, s.size() - 1, p.size() - 1); } // Driver code int main() { string str = ""baaabab""; string pattern = ""*****ba*****ab""; // char pattern[] = ""ba*****ab""; // char pattern[] = ""ba*ab""; // char pattern[] = ""a*ab""; // char pattern[] = ""a*****ab""; // char pattern[] = ""*a*****ab""; // char pattern[] = ""ba*ab****""; // char pattern[] = ""****""; // char pattern[] = ""*""; // char pattern[] = ""aa?ab""; // char pattern[] = ""b*b""; // char pattern[] = ""a*a""; // char pattern[] = ""baaabab""; // char pattern[] = ""?baaabab""; // char pattern[] = ""*baaaba*""; if (isMatch(str, pattern)) cout << ""Yes"" << endl; else cout << ""No"" << endl; return 0; }",quadratic,quadratic "// C++ program to implement wildcard // pattern matching algorithm #include using namespace std; // Function that matches input text // with given wildcard pattern bool strmatch(char txt[], char pat[], int n, int m) { // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : int i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false; } // Driver code int main() { char str[] = ""baaabab""; char pattern[] = ""*****ba*****ab""; // char pattern[] = ""ba*****ab""; // char pattern[] = ""ba*ab""; // char pattern[] = ""a*ab""; if (strmatch(str, pattern, strlen(str), strlen(pattern))) cout << ""Yes"" << endl; else cout << ""No"" << endl; char pattern2[] = ""a*****ab""; if (strmatch(str, pattern2, strlen(str), strlen(pattern2))) cout << ""Yes"" << endl; else cout << ""No"" << endl; return 0; }",constant,linear "// CPP program to replace c1 with c2 // and c2 with c1 #include using namespace std; string replace(string s, char c1, char c2) { int l = s.length(); // loop to traverse in the string for (int i = 0; i < l; i++) { // check for c1 and replace if (s[i] == c1) s[i] = c2; // check for c2 and replace else if (s[i] == c2) s[i] = c1; } return s; } // Driver code to check the above function int main() { string s = ""grrksfoegrrks""; char c1 = 'e', c2 = 'r'; cout << replace(s, c1, c2); return 0; }",constant,linear "// C++ program for implementation of Aho Corasick algorithm // for string matching using namespace std; #include // Max number of states in the matching machine. // Should be equal to the sum of the length of all keywords. const int MAXS = 500; // Maximum number of characters in input alphabet const int MAXC = 26; // OUTPUT FUNCTION IS IMPLEMENTED USING out[] // Bit i in this mask is one if the word with index i // appears when the machine enters this state. int out[MAXS]; // FAILURE FUNCTION IS IMPLEMENTED USING f[] int f[MAXS]; // GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING g[][] int g[MAXS][MAXC]; // Builds the string matching machine. // arr - array of words. The index of each keyword is important: // ""out[state] & (1 << i)"" is > 0 if we just found word[i] // in the text. // Returns the number of states that the built machine has. // States are numbered 0 up to the return value - 1, inclusive. int buildMatchingMachine(string arr[], int k) { // Initialize all values in output function as 0. memset(out, 0, sizeof out); // Initialize all values in goto function as -1. memset(g, -1, sizeof g); // Initially, we just have the 0 state int states = 1; // Construct values for goto function, i.e., fill g[][] // This is same as building a Trie for arr[] for (int i = 0; i < k; ++i) { const string &word = arr[i]; int currentState = 0; // Insert all characters of current word in arr[] for (int j = 0; j < word.size(); ++j) { int ch = word[j] - 'a'; // Allocate a new node (create a new state) if a // node for ch doesn't exist. if (g[currentState][ch] == -1) g[currentState][ch] = states++; currentState = g[currentState][ch]; } // Add current word in output function out[currentState] |= (1 << i); } // For all characters which don't have an edge from // root (or state 0) in Trie, add a goto edge to state // 0 itself for (int ch = 0; ch < MAXC; ++ch) if (g[0][ch] == -1) g[0][ch] = 0; // Now, let's build the failure function // Initialize values in fail function memset(f, -1, sizeof f); // Failure function is computed in breadth first order // using a queue queue q; // Iterate over every possible input for (int ch = 0; ch < MAXC; ++ch) { // All nodes of depth 1 have failure function value // as 0. For example, in above diagram we move to 0 // from states 1 and 3. if (g[0][ch] != 0) { f[g[0][ch]] = 0; q.push(g[0][ch]); } } // Now queue has states 1 and 3 while (q.size()) { // Remove the front state from queue int state = q.front(); q.pop(); // For the removed state, find failure function for // all those characters for which goto function is // not defined. for (int ch = 0; ch <= MAXC; ++ch) { // If goto function is defined for character 'ch' // and 'state' if (g[state][ch] != -1) { // Find failure state of removed state int failure = f[state]; // Find the deepest node labeled by proper // suffix of string from root to current // state. while (g[failure][ch] == -1) failure = f[failure]; failure = g[failure][ch]; f[g[state][ch]] = failure; // Merge output values out[g[state][ch]] |= out[failure]; // Insert the next level node (of Trie) in Queue q.push(g[state][ch]); } } } return states; } // Returns the next state the machine will transition to using goto // and failure functions. // currentState - The current state of the machine. Must be between // 0 and the number of states - 1, inclusive. // nextInput - The next character that enters into the machine. int findNextState(int currentState, char nextInput) { int answer = currentState; int ch = nextInput - 'a'; // If goto is not defined, use failure function while (g[answer][ch] == -1) answer = f[answer]; return g[answer][ch]; } // This function finds all occurrences of all array words // in text. void searchWords(string arr[], int k, string text) { // Preprocess patterns. // Build machine with goto, failure and output functions buildMatchingMachine(arr, k); // Initialize current state int currentState = 0; // Traverse the text through the built machine to find // all occurrences of words in arr[] for (int i = 0; i < text.size(); ++i) { currentState = findNextState(currentState, text[i]); // If match not found, move to next state if (out[currentState] == 0) continue; // Match found, print all matching words of arr[] // using output function. for (int j = 0; j < k; ++j) { if (out[currentState] & (1 << j)) { cout << ""Word "" << arr[j] << "" appears from "" << i - arr[j].size() + 1 << "" to "" << i << endl; } } } } // Driver program to test above int main() { string arr[] = {""he"", ""she"", ""hers"", ""his""}; string text = ""ahishers""; int k = sizeof(arr)/sizeof(arr[0]); searchWords(arr, k, text); return 0; }",linear,linear "// C++ program to calculate number of times // the pattern occurred in given string #include using namespace std; // Returns count of occurrences of ""1(0+)1"" // int str. int countPattern(string str) { int len = str.size(); bool oneSeen = 0; int count = 0; // Initialize result for (int i = 0; i < len ; i++) { // Check if encountered '1' forms a valid // pattern as specified if (str[i] == '1' && oneSeen == 1) if (str[i - 1] == '0') count++; // if 1 encountered for first time // set oneSeen to 1 if (str[i] == '1' && oneSeen == 0) { oneSeen = 1; continue; } // Check if there is any other character // other than '0' or '1'. If so then set // oneSeen to 0 to search again for new // pattern if (str[i] != '0' && str[i] != '1') oneSeen = 0; } return count; } // Driver program to test above function int main() { string str = ""100001abc101""; cout << countPattern(str); return 0; }",constant,linear "// C++ program to in-place replace multiple // occurrences of a pattern by character ‘X’ #include using namespace std; // Function to in-place replace multiple // occurrences of a pattern by character ‘X’ void replacePattern(string str, string pattern) { // making an iterator for string str string::iterator it = str.begin(); // run this loop until iterator reaches end of string while (it != str.end()) { // searching the first index in string str where // the first occurrence of string pattern occurs it = search(str.begin(), str.end(), pattern.begin(), pattern.end()); // checking if iterator is not pointing to end of the // string str if (it != str.end()) { // erasing the full pattern string from that iterator // position in string str str.erase(it, it + pattern.size()); // inserting 'X' at that iterator position str.insert(it, 'X'); } } // this loop removes consecutive 'X' in string s // Example: GeeksGeeksforGeeks was changed to 'XXforX' // running this loop will change it to 'XforX' for (int i = 0; i < str.size() - 1; i++) { if (str[i] == 'X' && str[i + 1] == 'X') { // removing 'X' at position i in string str str.erase(str.begin() + i); i--; // i-- because one character was deleted // so repositioning i } } cout << str; } // Driver code int main() { string str = ""GeeksforGeeks""; string pattern = ""Geeks""; replacePattern(str, pattern); return 0; }",constant,quadratic "// C++ program to find if a string follows order // defined by a given pattern. #include using namespace std; const int CHAR_SIZE = 256; // Returns true if characters of str follow // order defined by a given ptr. bool checkPattern(string str, string pat) { // Initialize all orders as -1 vector label(CHAR_SIZE, -1); // Assign an order to pattern characters // according to their appearance in pattern int order = 1; for (int i = 0; i < pat.length() ; i++) { // give the pattern characters order label[pat[i]] = order; // increment the order order++; } // Now one by check if string characters // follow above order int last_order = -1; for (int i = 0; i < str.length(); i++) { if (label[str[i]] != -1) { // If order of this character is less // than order of previous, return false. if (label[str[i]] < last_order) return false; // Update last_order for next iteration last_order = label[str[i]]; } } // return that str followed pat return true; } // Driver code int main() { string str = ""engineers rock""; string pattern = ""gsr""; cout << boolalpha << checkPattern(str, pattern); return 0; }",constant,linear "// C++ code for finding count // of string in a given 2D // character array. #include using namespace std; #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) // utility function to search // complete string from any // given index of 2d char array int internalSearch(string needle, int row, int col, string hay[], int row_max, int col_max, int xx) { int found = 0; if (row >= 0 && row <= row_max && col >= 0 && col <= col_max && needle[xx] == hay[row][col]) { char match = needle[xx]; xx += 1; hay[row][col] = 0; if (needle[xx] == 0) { found = 1; } else { // through Backtrack searching // in every directions found += internalSearch(needle, row, col + 1, hay, row_max, col_max,xx); found += internalSearch(needle, row, col - 1, hay, row_max, col_max,xx); found += internalSearch(needle, row + 1, col, hay, row_max, col_max,xx); found += internalSearch(needle, row - 1, col, hay, row_max, col_max,xx); } hay[row][col] = match; } return found; } // Function to search the string in 2d array int searchString(string needle, int row, int col, string str[], int row_count, int col_count) { int found = 0; int r, c; for (r = 0; r < row_count; ++r) { for (c = 0; c < col_count; ++c) { found += internalSearch(needle, r, c, str, row_count - 1, col_count - 1, 0); } } return found; } // Driver code int main() { string needle = ""MAGIC""; string input[] = { ""BBABBM"", ""CBMBBA"", ""IBABBG"", ""GOZBBI"", ""ABBBBC"", ""MCIGAM"" }; string str[ARRAY_SIZE(input)]; int i; for (i = 0; i < ARRAY_SIZE(input); ++i) { str[i] = input[i]; } cout << ""count: "" << searchString(needle, 0, 0, str, ARRAY_SIZE(str), str[0].size()) << endl; return 0; } // This code is contributed by SHUBHAMSINGH8410",quadratic,quadratic "// C++ program to print words in a sentence #include using namespace std; void removeDupWord(string str) { // Used to split string around spaces. istringstream ss(str); string word; // for storing each word // Traverse through all words // while loop till we get // strings to store in string word while (ss >> word) { // print the read word cout << word << ""\n""; } } // Driver code int main() { string str = ""Geeks for Geeks""; removeDupWord(str); return 0; }",linear,linear "// C++ program to check if we can break a string // into four distinct strings. #include using namespace std; // Return if the given string can be split or not. bool check(string s) { // We can always break a string of size 10 or // more into four distinct strings. if (s.size() >= 10) return true; // Brute Force for (int i =1; i < s.size(); i++) { for (int j = i + 1; j < s.size(); j++) { for (int k = j + 1; k < s.size(); k++) { // Making 4 string from the given string string s1 = s.substr(0, i); string s2 = s.substr(i, j - i); string s3 = s.substr(j, k - j); string s4 = s.substr(k, s.size() - k); // Checking if they are distinct or not. if (s1 != s2 && s1 != s3 && s1 != s4 && s2 != s3 && s2 != s4 && s3 != s4) return true; } } } return false; } // Driven Program int main() { string str = ""aaabb""; (check(str))? (cout << ""Yes"" << endl): (cout << ""No"" << endl); return 0; }",linear,np "// CPP program to split an alphanumeric // string using STL #include using namespace std; void splitString(string str) { string alpha, num, special; for (int i=0; i= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha.push_back(str[i]); else special.push_back(str[i]); } cout << alpha << endl; cout << num << endl; cout << special << endl; } // Driver code int main() { string str = ""geeks01$$for02geeks03!@!!""; splitString(str); return 0; }",linear,linear "// C++ program to split a numeric // string in an Increasing // sequence if possible #include using namespace std; // Function accepts a string and // checks if string can be split. void split(string str) { int len = str.length(); // if there is only 1 number // in the string then // it is not possible to split it if (len == 1) { cout << (""Not Possible""); return; } string s1 = """", s2 = """"; long num1, num2; for (int i = 0; i <= len / 2; i++) { int flag = 0; // storing the substring from // 0 to i+1 to form initial // number of the increasing sequence s1 = str.substr(0, i + 1); num1 = stoi((s1)); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = to_string(num2); int k = i + 1; while (flag == 0) { int l = s2.length(); // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next substring // of the numeric string if ((str.substr(k, k + l) == s2)) { flag = 0; // Increase num2 by 1 i.e the // next number to be looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = to_string(num2); l = s2.length(); if (k + 1 > len) { // If next string doesnot occurs // in a given numeric string // then it is not possible flag = 1; break; } } else flag = 1; } // if the string was fully traversed // and conditions were satisfied if (flag == 0) { cout << ""Possible "" << s1 << endl; break; } // if conditions failed to hold else if (flag == 1 && i > len / 2 - 1) { cout << ""Not Possible"" << endl; break; } } } // Driver code int main() { string str = ""99100""; // Call the split function // for splitting the string split(str); return 0; } // This code is contributed by divyeshrabadiya07",linear,quadratic "// CPP Program to find number of way // to split string such that each partition // starts with distinct character with // maximum number of partitions. #include using namespace std; // Returns the number of we can split // the string int countWays(string s) { int count[26] = { 0 }; // Finding the frequency of each // character. for (char x : s) count[x - 'a']++; // making frequency of first character // of string equal to 1. count[s[0] - 'a'] = 1; // Finding the product of frequency // of occurrence of each character. int ans = 1; for (int i = 0; i < 26; ++i) if (count[i] != 0) ans *= count[i]; return ans; } // Driven Program int main() { string s = ""acbbcc""; cout << countWays(s) << endl; return 0; }",constant,linear "// C++ program to check if a string can be splitted // into two strings such that one is divisible by 'a' // and other is divisible by 'b'. #include using namespace std; // Finds if it is possible to partition str // into two parts such that first part is // divisible by a and second part is divisible // by b. void findDivision(string &str, int a, int b) { int len = str.length(); // Create an array of size len+1 and initialize // it with 0. // Store remainders from left to right when // divided by 'a' vector lr(len+1, 0); lr[0] = (str[0] - '0')%a; for (int i=1; i rl(len+1, 0); rl[len-1] = (str[len-1] - '0')%b; int power10 = 10; for (int i= len-2; i>=0; i--) { rl[i] = (rl[i+1] + (str[i]-'0')*power10)%b; power10 = (power10 * 10) % b; } // Find a point that can partition a number for (int i=0; i using namespace std; // Finds if it is possible to partition str // into two parts such that first part is // divisible by a and second part is divisible // by b. string findDivision(string S, int a, int b) { for (int i = 0; i < S.size() - 1; i++) { string firstPart = S.substr(0, i + 1); string secondPart = S.substr(i + 1); if (stoi(firstPart) % a == 0 and stoi(secondPart) % b == 0) return firstPart + "" "" + secondPart; } return ""-1""; } // Driver code int main() { string str = ""125""; int a = 12, b = 3; string result = findDivision(str, a, b); if (result == ""-1"") { cout << ""NO"" << endl; } else { cout << ""YES"" << endl; cout << result << endl; } return 0; } // This code is contributed by Ishan Khandelwal",constant,linear "#include using namespace std; // This code kind of uses sliding window technique. First // checking if string[0] and string[0..n-1] is divisible if // yes then return else run a loop from 1 to n-1 and check if // taking this (0-i)index number and (i+1 to n-1)index number // on our two declared variables if they are divisible by given two numbers respectively // in any iteration return them simply string stringPartition(string s, int a, int b) { // code here int n = s.length(); // if length is 1 not possible if (n == 1) { return ""-1""; } else { // Checking if number formed bt S[0] and S[1->n-1] is divisible int a1 = s[0] - '0'; int a2 = s[1] - '0'; int multiplyer = 10; for (int i = 2; i < n; i++) { a2 = a2 * multiplyer + (s[i] - '0'); } int i = 1; if (a1 % a == 0 && a2 % b == 0) { string k1 = string(1, s[0]); string k2 = """"; for (int j = 1; j < n; j++) k2 += s[j]; return k1 + "" "" + k2; // return the numbers formed as string } // from here by using sliding window technique we will iterate and check for every i // that if the two current numbers formed are divisible if yes return // else form the two new numbers for next iteration using sliding window technique int q1 = 10; int q2 = 1; for (int i = 1; i < n - 1; i++) q2 *= 10; while (i < n - 1) { char x = s[i]; int ad = x - '0'; a1 = a1 * q1 + ad; a2 = a2 - q2 * ad; if (a1 % a == 0 && a2 % b == 0) { string k1 = """"; string k2 = """"; for (int j = 0; j < i + 1; j++) k1 += s[j]; for (int j = i + 1; j < n; j++) k2 += s[j]; return k1 + "" "" + k2; } q2 /= 10; i++; } } return ""-1""; } // Driver code int main() { string str = ""123""; int a = 12, b = 3; string result = stringPartition(str, a, b); if (result == ""-1"") { cout << ""NO"" << endl; } else { cout << ""YES"" << endl; cout << result << endl; } return 0; } // This code is contributed by Kartikey Singh",constant,linear "#include using namespace std; // c++ function to count ways to divide a // string in two parts a and b such that // b/pow(10, p) == a int calculate(string N) { int len = N.length(); int l = (len) / 2; int count = 0; for (int i = 1; i <= l; i++) { // substring representing int a string s = N.substr(0, i); // no of digits in a int l1 = s.length(); // consider only most significant // l1 characters of remaining string // for int b string t = N.substr(i, l1); // if any of a or b contains leading 0s // discard this combination if (s[0] == '0' || t[0] == '0') continue; // if both are equal if (s.compare(t) == 0) count++; } return count; } // driver function to test above function int main() { string N = ""2202200""; cout << calculate(N); return 0; }",linear,quadratic "// C++ program to divide a string // in n equal parts #include #include using namespace std; class gfg { // Function to print n equal parts of str public: void divideString(char str[], int n) { int str_size = strlen(str); int i; int part_size; // Check if string can be divided in // n equal parts if (str_size % n != 0) { cout << ""Invalid Input: String size""; cout << "" is not divisible by n""; return; } // Calculate the size of parts to // find the division points part_size = str_size / n; for (i = 0; i < str_size; i++) { if (i % part_size == 0) cout << endl; cout << str[i]; } } }; // Driver code int main() { gfg g; // length of string is 28 char str[] = ""a_simple_divide_string_quest""; // Print 4 equal parts of the string g.divideString(str, 4); return 0; } // This code is contributed by SoM15242",constant,linear "#include using namespace std; void divide(string str, int n) { if (str.length() % n != 0) { cout << ""Invalid Input: String size""; cout << "" is not divisible by n""; return; } int parts = str.length() / n; int start = 0; while (start < str.length()) { cout << str.substr(start, parts) << endl; start += parts; // if(start < str.length()) cout << endl; to ignore // final new line } } int main() { string str = ""a_simple_divide_string_quest""; divide(str, 4); } //Contributed By Jagadeesh",linear,linear "// C++ program to find minimum breaks needed // to break a string in dictionary words. #include using namespace std; const int ALPHABET_SIZE = 26; // trie node struct TrieNode { struct TrieNode* children[ALPHABET_SIZE]; // isEndOfWord is true if the node // represents end of a word bool isEndOfWord; }; // Returns new trie node (initialized to NULLs) struct TrieNode* getNode(void) { struct TrieNode* pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode; } // If not present, inserts the key into the trie // If the key is the prefix of trie node, just // marks leaf node void insert(struct TrieNode* root, string key) { struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true; } // function break the string into minimum cut // such the every substring after breaking // in the dictionary. void minWordBreak(struct TrieNode* root, string key, int start, int* min_Break, int level = 0) { struct TrieNode* pCrawl = root; // base case, update minimum Break if (start == key.length()) { *min_Break = min(*min_Break, level - 1); return; } // traverse given key(pattern) int minBreak = 0; for (int i = start; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return; // if we find a condition where we can // move to the next word in a trie // dictionary if (pCrawl->children[index]->isEndOfWord) minWordBreak(root, key, i + 1, min_Break, level + 1); pCrawl = pCrawl->children[index]; } } // Driver program to test above functions int main() { string dictionary[] = { ""Cat"", ""Mat"", ""Ca"", ""Ma"", ""at"", ""C"", ""Dog"", ""og"", ""Do"" }; int n = sizeof(dictionary) / sizeof(dictionary[0]); struct TrieNode* root = getNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, dictionary[i]); int min_Break = INT_MAX; minWordBreak(root, ""CatMatat"", 0, &min_Break, 0); cout << min_Break << endl; return 0; }",linear,quadratic "// A recursive program to print all possible // partitions of a given string into dictionary // words #include using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/ int dictionaryContains(string &word) { string dictionary[] = {""mobile"",""samsung"",""sam"",""sung"", ""man"",""mango"", ""icecream"",""and"", ""go"",""i"",""love"",""ice"",""cream""}; int n = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < n; i++) if (dictionary[i].compare(word) == 0) return true; return false; } // Prototype of wordBreakUtil void wordBreakUtil(string str, int size, string result); // Prints all possible word breaks of given string void wordBreak(string str) { // Last argument is prefix wordBreakUtil(str, str.size(), """"); } // Result store the current prefix with spaces // between words void wordBreakUtil(string str, int n, string result) { //Process all prefixes one by one for (int i=1; i<=n; i++) { // Extract substring from 0 to i in prefix string prefix = str.substr(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if (dictionaryContains(prefix)) { // If no more elements are there, print it if (i == n) { // Add this element to previous prefix result += prefix; cout << result << endl; return; } wordBreakUtil(str.substr(i, n-i), n-i, result + prefix + "" ""); } } } //Driver Code int main() { // Function call cout << ""First Test:\n""; wordBreak(""iloveicecreamandmango""); cout << ""\nSecond Test:\n""; wordBreak(""ilovesamsungmobile""); return 0; }",quadratic,np "// CPP program to mark balanced and unbalanced // parenthesis. #include using namespace std; void identifyParenthesis(string a) { stack st; // run the loop upto end of the string for (int i = 0; i < a.length(); i++) { // if a[i] is opening bracket then push // into stack if (a[i] == '(') st.push(i); // if a[i] is closing bracket ')' else if (a[i] == ')') { // If this closing bracket is unmatched if (st.empty()) a.replace(i, 1, ""-1""); else { // replace all opening brackets with 0 // and closing brackets with 1 a.replace(i, 1, ""1""); a.replace(st.top(), 1, ""0""); st.pop(); } } } // if stack is not empty then pop out all // elements from it and replace -1 at that // index of the string while (!st.empty()) { a.replace(st.top(), 1, ""-1""); st.pop(); } // print final string cout << a << endl; } // Driver code int main() { string str = ""(a))""; identifyParenthesis(str); return 0; }",linear,linear "// C++ program to check for balanced brackets. #include using namespace std; // Function to check if brackets are balanced bool areBracketsBalanced(string expr) { // Declare a stack to hold the previous brackets. stack temp; for (int i = 0; i < expr.length(); i++) { if (temp.empty()) { // If the stack is empty // just push the current bracket temp.push(expr[i]); } else if ((temp.top() == '(' && expr[i] == ')') || (temp.top() == '{' && expr[i] == '}') || (temp.top() == '[' && expr[i] == ']')) { // If we found any complete pair of bracket // then pop temp.pop(); } else { temp.push(expr[i]); } } if (temp.empty()) { // If stack is empty return true return true; } return false; } // Driver code int main() { string expr = ""{()}[]""; // Function call if (areBracketsBalanced(expr)) cout << ""Balanced""; else cout << ""Not Balanced""; return 0; }",linear,linear "// C++ program to find length of // the longest balanced subsequence #include using namespace std; int maxLength(char s[], int n) { int dp[n][n]; memset(dp, 0, sizeof(dp)); // Considering all balanced // substrings of length 2 for (int i = 0; i < n - 1; i++) if (s[i] == '(' && s[i + 1] == ')') dp[i][i + 1] = 2; // Considering all other substrings for (int l = 2; l < n; l++) { for (int i = 0, j = l; j < n; i++, j++) { if (s[i] == '(' && s[j] == ')') dp[i][j] = 2 + dp[i + 1][j - 1]; for (int k = i; k < j; k++) dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j]); } } return dp[0][n - 1]; } // Driver Code int main() { char s[] = ""()(((((()""; int n = strlen(s); cout << maxLength(s, n) << endl; return 0; }",quadratic,quadratic "// C++ program to find length of // the longest balanced subsequence #include using namespace std; int maxLength(char s[], int n) { // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. int invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. int invalidCloseBraces = 0; // Iterating over the String for (int i = 0; i < n; i++) { if (s[i] == '(') { // Number of open braces that // hasn't been closed yet. invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open // brace. invalidCloseBraces++; } else { // Mapping the ith close brace // to one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces)); } // Driver Code int main() { char s[] = ""()(((((()""; int n = strlen(s); cout << maxLength(s, n) << endl; return 0; }",constant,linear "// C++ program to determine whether given // expression is balanced/ parenthesis // expression or not. #include using namespace std; // Function to check if two brackets are matching // or not. int isMatching(char a, char b) { if ((a == '{' && b == '}') || (a == '[' && b == ']') || (a == '(' && b == ')') || a == 'X') return 1; return 0; } // Recursive function to check if given expression // is balanced or not. int isBalanced(string s, stack ele, int ind) { // Base case. // If the string is balanced then all the opening // brackets had been popped and stack should be // empty after string is traversed completely. if (ind == s.length()) return ele.empty(); // variable to store element at the top of the stack. char topEle; // variable to store result of recursive call. int res; // Case 1: When current element is an opening bracket // then push that element in the stack. if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') { ele.push(s[ind]); return isBalanced(s, ele, ind + 1); } // Case 2: When current element is a closing bracket // then check for matching bracket at the top of the // stack. else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') { // If stack is empty then there is no matching opening // bracket for current closing bracket and the // expression is not balanced. if (ele.empty()) return 0; topEle = ele.top(); ele.pop(); // Check bracket is matching or not. if (!isMatching(topEle, s[ind])) return 0; return isBalanced(s, ele, ind + 1); } // Case 3: If current element is 'X' then check // for both the cases when 'X' could be opening // or closing bracket. else if (s[ind] == 'X') { stack tmp = ele; tmp.push(s[ind]); res = isBalanced(s, tmp, ind + 1); if (res) return 1; if (ele.empty()) return 0; ele.pop(); return isBalanced(s, ele, ind + 1); } } int main() { string s = ""{(X}[]""; stack ele; //Check if the String is of even length if(s.length()%2==0){ if (isBalanced(s, ele, 0)) cout << ""Balanced""; else cout << ""Not Balanced""; } // If the length of the string is not even // then it is not a balanced string else{ cout << ""Not Balanced""; } return 0; }",linear,np "// C++ program to evaluate value of an expression. #include using namespace std; int evaluateBoolExpr(string s) { int n = s.length(); // Traverse all operands by jumping // a character after every iteration. for (int i = 0; i < n; i += 2) { // If operator next to current operand // is AND. if (s[i + 1] == 'A') { if (s[i + 2] == '0'|| s[i] == '0') s[i + 2] = '0'; else s[i + 2] = '1'; } // If operator next to current operand // is OR. else if (s[i + 1] == 'B') { if (s[i + 2] == '1'|| s[i] == '1') s[i + 2] = '1'; else s[i + 2] = '0'; } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s[i + 2] == s[i]) s[i + 2] = '0'; else s[i + 2] = '1'; } } return s[n - 1] -'0'; } // Driver code int main() { string s = ""1C1B1B0A0""; cout << evaluateBoolExpr(s); return 0; }",linear,linear "// A C++ program to find the maximum depth of nested // parenthesis in a given expression #include using namespace std; int maxDepth(string& s) { int count = 0; stack st; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') st.push(i); // pushing the bracket in the stack else if (s[i] == ')') { if (count < st.size()) count = st.size(); /*keeping track of the parenthesis and storing it before removing it when it gets balanced*/ st.pop(); } } return count; } // Driver program int main() { string s = ""( ((X)) (((Y))) )""; cout << maxDepth(s); // This code is contributed by rakeshsahni return 0; }",constant,linear "// A C++ program to find the maximum depth of nested // parenthesis in a given expression #include using namespace std; // function takes a string and returns the // maximum depth nested parenthesis int maxDepth(string S) { int current_max = 0; // current count int max = 0; // overall maximum count int n = S.length(); // Traverse the input string for (int i = 0; i < n; i++) { if (S[i] == '(') { current_max++; // update max if required if (current_max > max) max = current_max; } else if (S[i] == ')') { if (current_max > 0) current_max--; else return -1; } } // finally check for unbalanced string if (current_max != 0) return -1; return max; } // Driver program int main() { string s = ""( ((X)) (((Y))) )""; cout << maxDepth(s); return 0; }",constant,linear "// C++ Program to find all combinations of Non- // overlapping substrings formed from given // string #include using namespace std; // find all combinations of non-overlapping // substrings formed by input string str // index – index of the next character to // be processed // out - output string so far void findCombinations(string str, int index, string out) { if (index == str.length()) cout << out << endl; for (int i = index; i < str.length(); i++) { // append substring formed by str[index, // i] to output string findCombinations( str, i + 1, out + ""("" + str.substr(index, i + 1 - index) + "")""); } } // Driver Code int main() { // input string string str = ""abcd""; findCombinations(str, 0, """"); return 0; }",quadratic,quadratic "// C++ program to find an index k which // decides the number of opening brackets // is equal to the number of closing brackets #include using namespace std; // Function to find an equal index int findIndex(string str) { int len = str.length(); int open[len+1], close[len+1]; int index = -1; memset(open, 0, sizeof (open)); memset(close, 0, sizeof (close)); open[0] = 0; close[len] = 0; if (str[0]=='(') open[1] = 1; if (str[len-1] == ')') close[len-1] = 1; // Store the number of opening brackets // at each index for (int i = 1; i < len; i++) { if ( str[i] == '(' ) open[i+1] = open[i] + 1; else open[i+1] = open[i]; } // Store the number of closing brackets // at each index for (int i = len-2; i >= 0; i--) { if ( str[i] == ')' ) close[i] = close[i+1] + 1; else close[i] = close[i+1]; } // check if there is no opening or closing // brackets if (open[len] == 0) return len; if (close[0] == 0) return 0; // check if there is any index at which // both brackets are equal for (int i=0; i<=len; i++) if (open[i] == close[i]) index = i; return index; } // Driver code int main() { string str = ""(()))(()()())))""; cout << findIndex(str); return 0; }",linear,linear "// C++ program to find an index k which // decides the number of opening brackets // is equal to the number of closing brackets #include using namespace std; // Function to find an equal index int findIndex(string str) { // STL to count occurrences of ')' int cnt_close = count(str.begin(), str.end(), ')'); for (int i = 0; str[i] != '\0'; i++) if (cnt_close == i) return i; // If no opening brackets return str.size(); } // Driver code int main() { string str = ""(()))(()()())))""; cout << findIndex(str); return 0; } // This code is contributed by Dhananjay Dhawale @chessnoobdj",constant,linear "// CPP program to check if two expressions // evaluate to same. #include using namespace std; const int MAX_CHAR = 26; // Return local sign of the operand. For example, // in the expr a-b-(c), local signs of the operands // are +a, -b, +c bool adjSign(string s, int i) { if (i == 0) return true; if (s[i - 1] == '-') return false; return true; }; // Evaluate expressions into the count vector of // the 26 alphabets.If add is true, then add count // to the count vector of the alphabets, else remove // count from the count vector. void eval(string s, vector& v, bool add) { // stack stores the global sign // for operands. stack stk; stk.push(true); // + means true // global sign is positive initially int i = 0; while (s[i] != '\0') { if (s[i] == '+' || s[i] == '-') { i++; continue; } if (s[i] == '(') { // global sign for the bracket is // pushed to the stack if (adjSign(s, i)) stk.push(stk.top()); else stk.push(!stk.top()); } // global sign is popped out which // was pushed in for the last bracket else if (s[i] == ')') stk.pop(); else { // global sign is positive (we use different // values in two calls of functions so that // we finally check if all vector elements // are 0. if (stk.top()) v[s[i] - 'a'] += (adjSign(s, i) ? add ? 1 : -1 : add ? -1 : 1); // global sign is negative here else v[s[i] - 'a'] += (adjSign(s, i) ? add ? -1 : 1 : add ? 1 : -1); } i++; } }; // Returns true if expr1 and expr2 represent // same expressions bool areSame(string expr1, string expr2) { // Create a vector for all operands and // initialize the vector as 0. vector v(MAX_CHAR, 0); // Put signs of all operands in expr1 eval(expr1, v, true); // Subtract signs of operands in expr2 eval(expr2, v, false); // If expressions are same, vector must // be 0. for (int i = 0; i < MAX_CHAR; i++) if (v[i] != 0) return false; return true; } // Driver code int main() { string expr1 = ""-(a+b+c)"", expr2 = ""-a-b-c""; if (areSame(expr1, expr2)) cout << ""Yes\n""; else cout << ""No\n""; return 0; }",linear,linear "/* C++ Program to check whether valid expression is redundant or not*/ #include using namespace std; // Function to check redundant brackets in a // balanced expression bool checkRedundancy(string& str) { // create a stack of characters stack st; // Iterate through the given expression for (auto& ch : str) { // if current character is close parenthesis ')' if (ch == ')') { char top = st.top(); st.pop(); // If immediate pop have open parenthesis '(' // duplicate brackets found bool flag = true; while (!st.empty() and top != '(') { // Check for operators in expression if (top == '+' || top == '-' || top == '*' || top == '/') flag = false; // Fetch top element of stack top = st.top(); st.pop(); } // If operators not found if (flag == true) return true; } else st.push(ch); // push open parenthesis '(', // operators and operands to stack } return false; } // Function to check redundant brackets void findRedundant(string& str) { bool ans = checkRedundancy(str); if (ans == true) cout << ""Yes\n""; else cout << ""No\n""; } // Driver code int main() { string str = ""((a+b))""; findRedundant(str); return 0; }",linear,linear "/* CPP Program to find the longest correct bracket subsequence in a given range */ #include using namespace std; /* Declaring Structure for storing three values in each segment tree node */ struct Node { int pairs; int open; // unused int closed; // unused Node() { pairs = open = closed = 0; } }; // A utility function to get the middle index from corner // indexes. int getMid(int s, int e) { return s + (e - s) / 2; } // Returns Parent Node after merging its left and right // child Node merge(Node leftChild, Node rightChild) { Node parentNode; int minMatched = min(leftChild.open, rightChild.closed); parentNode.pairs = leftChild.pairs + rightChild.pairs + minMatched; parentNode.open = leftChild.open + rightChild.open - minMatched; parentNode.closed = leftChild.closed + rightChild.closed - minMatched; return parentNode; } // A recursive function that constructs Segment Tree // for string[ss..se]. si is index of current node in // segment tree st void constructSTUtil(char str[], int ss, int se, Node* st, int si) { // If there is one element in string, store it in // current node of segment tree and return if (ss == se) { // since it contains one element, pairs // will be zero st[si].pairs = 0; // check whether that one element is opening // bracket or not st[si].open = (str[ss] == '(' ? 1 : 0); // check whether that one element is closing // bracket or not st[si].closed = (str[ss] == ')' ? 1 : 0); return; } // If there are more than one elements, then recur // for left and right subtrees and store the relation // of values in this node int mid = getMid(ss, se); constructSTUtil(str, ss, mid, st, si * 2 + 1); constructSTUtil(str, mid + 1, se, st, si * 2 + 2); // Merge left and right child into the Parent Node st[si] = merge(st[si * 2 + 1], st[si * 2 + 2]); } /* Function to construct segment tree from given string. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ Node* constructST(char str[], int n) { // Allocate memory for segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; // Declaring array of structure Allocate memory Node* st = new Node[max_size]; // Fill the allocated memory st constructSTUtil(str, 0, n - 1, st, 0); // Return the constructed segment tree return st; } /* A Recursive function to get the desired Maximum Sum Sub-Array, The following are parameters of the function- st --> Pointer to segment tree si --> Index of the segment tree Node ss & se --> Starting and ending indexes of the segment represented by current Node, i.e., tree[index] qs & qe --> Starting and ending indexes of query range */ Node queryUtil(Node* st, int ss, int se, int qs, int qe, int si) { // No overlap if (ss > qe || se < qs) { // returns a Node for out of bounds condition Node nullNode; return nullNode; } // Complete overlap if (ss >= qs && se <= qe) { return st[si]; } // Partial Overlap Merge results of Left // and Right subtrees int mid = getMid(ss, se); Node left = queryUtil(st, ss, mid, qs, qe, si * 2 + 1); Node right = queryUtil(st, mid + 1, se, qs, qe, si * 2 + 2); // merge left and right subtree query results Node res = merge(left, right); return res; } /* Returns the maximum length correct bracket subsequencebetween start and end It mainly uses queryUtil(). */ int query(Node* st, int qs, int qe, int n) { Node res = queryUtil(st, 0, n - 1, qs, qe, 0); // since we are storing numbers pairs // and have to return maximum length, hence // multiply no of pairs by 2 return 2 * res.pairs; } // Driver Code int main() { char str[] = ""())(())(())(""; int n = strlen(str); // Build segment tree from given string Node* st = constructST(str, n); // Function call int startIndex = 0, endIndex = 11; cout << ""Maximum Length Correct Bracket"" "" Subsequence between "" << startIndex << "" and "" << endIndex << "" = "" << query(st, startIndex, endIndex, n) << endl; startIndex = 1, endIndex = 2; cout << ""Maximum Length Correct Bracket"" "" Subsequence between "" << startIndex << "" and "" << endIndex << "" = "" << query(st, startIndex, endIndex, n) << endl; return 0; }",linear,logn "// C++ program to find sum of given array of // string type in integer form #include using namespace std; // Function to find the sum of given array int calculateSum(string arr[], int n) { // if string is empty if (n == 0) return 0; string s = arr[0]; // stoi function to convert // string into integer int value = stoi(s); int sum = value; for (int i = 2; i < n; i = i + 2) { s = arr[i]; // stoi function to convert // string into integer int value = stoi(s); // Find operator char operation = arr[i - 1][0]; // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum; } // Driver Function int main() { string arr[] = { ""3"", ""+"", ""4"", ""-"", ""7"", ""+"", ""13"" }; int n = sizeof(arr) / sizeof(arr[0]); cout << calculateSum(arr, n); return 0; }",constant,linear "// C++ implementation to print the bracket number #include using namespace std; // function to print the bracket number void printBracketNumber(string exp, int n) { // used to print the bracket number // for the left bracket int left_bnum = 1; // used to obtain the bracket number // for the right bracket stack right_bnum; // traverse the given expression 'exp' for (int i = 0; i < n; i++) { // if current character is a left bracket if (exp[i] == '(') { // print 'left_bnum', cout << left_bnum << "" ""; // push 'left_bnum' on to the stack 'right_bnum' right_bnum.push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character is a right bracket else if(exp[i] == ')') { // print the top element of stack 'right_bnum' // it will be the right bracket number cout << right_bnum.top() << "" ""; // pop the top element from the stack right_bnum.pop(); } } } // Driver program to test above int main() { string exp = ""(a+(b*c))+(d/e)""; int n = exp.size(); printBracketNumber(exp, n); return 0; }",linear,linear "// CPP program to find index of closing // bracket for given opening bracket. #include using namespace std; // Function to find index of closing // bracket for given opening bracket. void test(string expression, int index){ int i; // If index given is invalid and is // not an opening bracket. if(expression[index]!='['){ cout << expression << "", "" << index << "": -1\n""; return; } // Stack to store opening brackets. stack st; // Traverse through string starting from // given index. for(i = index; i < expression.length(); i++){ // If current character is an // opening bracket push it in stack. if(expression[i] == '[') st.push(expression[i]); // If current character is a closing // bracket, pop from stack. If stack // is empty, then this closing // bracket is required bracket. else if(expression[i] == ']'){ st.pop(); if(st.empty()){ cout << expression << "", "" << index << "": "" << i << ""\n""; return; } } } // If no matching closing bracket // is found. cout << expression << "", "" << index << "": -1\n""; } // Driver Code int main() { test(""[ABC[23]][89]"", 0); // should be 8 test(""[ABC[23]][89]"", 4); // should be 7 test(""[ABC[23]][89]"", 9); // should be 12 test(""[ABC[23]][89]"", 1); // No matching bracket return 0; } // This code is contributed by Nikhil Jindal.",linear,linear "/* C++ program to construct string from binary tree*/ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } // Function to construct string from binary tree void treeToString(Node* root, string& str) { // bases case if (root == NULL) return; // push the root data as character str.push_back(root->data + '0'); // if leaf node, then return if (!root->left && !root->right) return; // for left subtree str.push_back('('); treeToString(root->left, str); str.push_back(')'); // only if right child is present to // avoid extra parenthesis if (root->right) { str.push_back('('); treeToString(root->right, str); str.push_back(')'); } } // Driver Code int main() { /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); string str = """"; treeToString(root, str); cout << str; }",linear,linear "/* C++ program to construct a binary tree from the given string */ #include using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } /* This function is here just to test */ void preOrder(Node* node) { if (node == NULL) return; printf(""%d "", node->data); preOrder(node->left); preOrder(node->right); } // function to return the index of close parenthesis int findIndex(string str, int si, int ei) { if (si > ei) return -1; // Inbuilt stack stack s; for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s.top() == '(') { s.pop(); // if stack is empty, this is // the required index if (s.empty()) return i; } } } // if not found return -1 return -1; } // function to construct tree from string Node* treeFromString(string str, int si, int ei) { // Base case if (si > ei) return NULL; int num = 0; // In case the number is having more than 1 digit while(si <= ei && str[si] >= '0' && str[si] <= '9') { num *= 10; num += (str[si] - '0'); si++; } // new root Node* root = newNode(num); int index = -1; // if next char is '(' find the index of // its complement ')' if (si <= ei && str[si] == '(') index = findIndex(str, si, ei); // if index found if (index != -1) { // call for left subtree root->left = treeFromString(str, si + 1, index - 1); // call for right subtree root->right = treeFromString(str, index + 2, ei - 1); } return root; } // Driver Code int main() { string str = ""4(2(3)(1))(6(5))""; Node* root = treeFromString(str, 0, str.length() - 1); preOrder(root); }",linear,quadratic "// Simple C++ program to convert all substrings from // decimal to given base. #include using namespace std; int substringConversions(string str, int k, int b) { for (int i=0; i + k <= str.size(); i++) { // Saving substring in sub string sub = str.substr(i, k); // Evaluating decimal for current substring // and printing it. int sum = 0, counter = 0; for (int i = sub.size() - 1; i >= 0; i--) { sum = sum + ((sub.at(i) - '0') * pow(b, counter)); counter++; } cout << sum << "" ""; } } // Driver code int main() { string str = ""12212""; int b = 3, k = 3; substringConversions(str, b, k); return 0; }",linear,quadratic "// Efficient C++ program to convert all substrings from // decimal to given base. #include using namespace std; int substringConversions(string str, int k, int b) { int i = 0, sum = 0, counter = k-1; // Computing the decimal of first window for (i; i < k; i++) { sum = sum + ((str.at(i) - '0') * pow(b, counter)); counter--; } cout << sum << "" ""; // prev stores the previous decimal int prev = sum; // Computing decimal equivalents of all other windows sum = 0, counter = 0; for (i; i < str.size(); i++) { // Subtracting weight of the element pushed out of window sum = prev - ((str.at(i - k) - '0') * pow(b, k-1)); // Multiplying the decimal by base to formulate other window sum = sum * b; // Adding the new element of window to sum sum = sum + (str.at(i) - '0'); // Decimal of current window cout << sum << "" ""; // Updating prev prev = sum; counter++; } } // Driver code int main() { string str = ""12212""; int b = 3, k = 3; substringConversions(str, b, k); return 0; }",linear,linear "// C++ program to demonstrate above steps of // binary fractional to decimal conversion #include using namespace std; // Function to convert binary fractional to // decimal double binaryToDecimal(string binary, int len) { // Fetch the radix point size_t point = binary.find('.'); // Update point if not found if (point == string::npos) point = len; double intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for (int i = point-1; i>=0; --i) { // Subtract '0' to convert character // into integer intDecimal += (binary[i] - '0') * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for (int i = point+1; i < len; ++i) { fracDecimal += (binary[i] - '0') / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal; } // Driver code int main() { string n = ""110.101""; cout << binaryToDecimal(n, n.length()) << ""\n""; n = ""101.1101""; cout << binaryToDecimal(n, n.length()); return 0; }",linear,linear "// C++ program to convert fractional decimal // to binary number #include using namespace std; // Function to convert decimal to binary upto // k-precision after decimal point string decimalToBinary(double num, int k_prec) { string binary = """"; // Fetch the integral part of decimal number int Integral = num; // Fetch the fractional part decimal number double fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral) { int rem = Integral % 2; // Append 0 in binary binary.push_back(rem +'0'); Integral /= 2; } // Reverse string to get original binary // equivalent reverse(binary.begin(),binary.end()); // Append point before conversion of // fractional part binary.push_back('.'); // Conversion of fractional part to // binary equivalent while (k_prec--) { // Find next bit in fraction fractional *= 2; int fract_bit = fractional; if (fract_bit == 1) { fractional -= fract_bit; binary.push_back(1 + '0'); } else binary.push_back(0 + '0'); } return binary; } // Driver code int main() { double n = 4.47; int k = 3; cout << decimalToBinary(n, k) << ""\n""; n = 6.986 , k = 5; cout << decimalToBinary(n, k); return 0; }",linear,linear "// C++ implementation to convert a // sentence into its equivalent // mobile numeric keypad sequence #include using namespace std; // Function which computes the sequence string printSequence(string arr[], string input) { string output = """"; // length of input string int n = input.length(); for (int i = 0; i < n; i++) { // Checking for space if (input[i] == ' ') output = output + ""0""; else { // Calculating index for each // character int position = input[i] - 'A'; output = output + arr[position]; } } // Output sequence return output; } // Driver Code int main() { // storing the sequence in array string str[] = { ""2"", ""22"", ""222"", ""3"", ""33"", ""333"", ""4"", ""44"", ""444"", ""5"", ""55"", ""555"", ""6"", ""66"", ""666"", ""7"", ""77"", ""777"", ""7777"", ""8"", ""88"", ""888"", ""9"", ""99"", ""999"", ""9999"" }; string input = ""GEEKSFORGEEKS""; cout << printSequence(str, input); return 0; }",linear,linear "// C++ Program for above implementation #include using namespace std; // Function to check is it possible to convert // first string into another string or not. bool isItPossible(string str1, string str2, int m, int n) { // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both strings or not. if (count(str1.begin(), str1.end(), 'A') != count(str2.begin(), str2.end(), 'A') || count(str1.begin(), str1.end(), 'B') != count(str2.begin(), str2.end(), 'B')) return false; // Start traversing for (int i = 0; i < m; i++) { if (str1[i] != '#') { for (int j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2[j] = '#'; // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true; } // Drivers code int main() { string str1 = ""A#B#""; string str2 = ""A##B""; int m = str1.length(); int n = str2.length(); isItPossible(str1, str2, m, n) ? cout << ""Yes\n"" : cout << ""No\n""; return 0; }",linear,quadratic "// CPP Program to convert str1 to str2 in // exactly k operations #include using namespace std; // Returns true if it is possible to convert // str1 to str2 using k operations. bool isConvertible(string str1, string str2, int k) { // Case A (i) if ((str1.length() + str2.length()) < k) return true; // finding common length of both string int commonLength = 0; for (int i = 0; i < min(str1.length(), str2.length()); i++) { if (str1[i] == str2[i]) commonLength++; else break; } // Case A (ii)- if ((k - str1.length() - str2.length() + 2 * commonLength) % 2 == 0) return true; // Case B- return false; } // driver program int main() { string str1 = ""geek"", str2 = ""geek""; int k = 7; if (isConvertible(str1, str2, k)) cout << ""Yes""; else cout << ""No""; str1 = ""geeks"", str2 = ""geek""; k = 5; cout << endl; if (isConvertible(str1, str2, k)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,linear "// C++ Program to convert decimal number to // roman numerals #include using namespace std; // Function to convert decimal to Roman Numerals int printRoman(int number) { int num[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000}; string sym[] = {""I"",""IV"",""V"",""IX"",""X"",""XL"",""L"",""XC"",""C"",""CD"",""D"",""CM"",""M""}; int i=12; while(number>0) { int div = number/num[i]; number = number%num[i]; while(div--) { cout< using namespace std; // Function to calculate roman equivalent string intToRoman(int num) { // storing roman values of digits from 0-9 // when placed at different places string m[] = { """", ""M"", ""MM"", ""MMM"" }; string c[] = { """", ""C"", ""CC"", ""CCC"", ""CD"", ""D"", ""DC"", ""DCC"", ""DCCC"", ""CM"" }; string x[] = { """", ""X"", ""XX"", ""XXX"", ""XL"", ""L"", ""LX"", ""LXX"", ""LXXX"", ""XC"" }; string i[] = { """", ""I"", ""II"", ""III"", ""IV"", ""V"", ""VI"", ""VII"", ""VIII"", ""IX"" }; // Converting to roman string thousands = m[num / 1000]; string hundreds = c[(num % 1000) / 100]; string tens = x[(num % 100) / 10]; string ones = i[num % 10]; string ans = thousands + hundreds + tens + ones; return ans; } // Driver program to test above function int main() { int number = 3549; cout << intToRoman(number); return 0; }",constant,linear "// cpp program to check if a string can // be converted to another string by // performing operations #include using namespace std; // function to check if a string can be // converted to another string by // performing following operations bool check(string s1, string s2) { // calculates length int n = s1.length(); int m = s2.length(); bool dp[n + 1][m + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= m; j++) { dp[i][j] = false; } } // mark 1st position as true dp[0][0] = true; // traverse for all DPi, j for (int i = 0; i < s1.length(); i++) { for (int j = 0; j <= s2.length(); j++) { // if possible for to convert i // characters of s1 to j characters // of s2 if (dp[i][j]) { // if upper_case(s1[i])==s2[j] // is same if (j < s2.length() && (toupper(s1[i]) == s2[j])) dp[i + 1][j + 1] = true; // if not upper then deletion is // possible if (!isupper(s1[i])) dp[i + 1][j] = true; } } } return (dp[n][m]); } // driver code int main() { string s1 = ""daBcd""; string s2 = ""ABC""; if (check(s1, s2)) cout << ""YES""; else cout << ""NO""; return 0; }",quadratic,quadratic "// CPP code to transform string #include using namespace std; // Function to change // character's case string change_case(string a) { int l = a.length(); for(int i = 0 ; i < l ; i++) { // If character is lowercase // change to uppercase if(a[i] >= 'a' && a[i] <= 'z') a[i] = a[i] - 32; // If character is uppercase // change to lowercase else if(a[i] >= 'A' && a[i] <= 'Z') a[i] = a[i] + 32; } return a; } // Function to delete vowels string delete_vowels(string a) { string temp = """"; int l = a.length(); for(int i = 0 ; i < l ; i++) { //If character is consonant if(a[i] != 'a' && a[i] != 'e' && a[i] != 'i' && a[i] != 'o' && a[i] != 'u' && a[i] != 'A' && a[i] != 'E' && a[i] != 'O' && a[i] != 'U'&& a[i] != 'I') temp += a[i]; } return temp; } // Function to insert ""#"" string insert_hash(string a) { string temp = """"; int l = a.length(); for(int i = 0 ; i < l ; i++) { // If character is not special if((a[i] >= 'a' && a[i] <= 'z') || (a[i] >= 'A' && a[i] <= 'Z')) temp = temp + '#' + a[i]; else temp = temp + a[i]; } return temp; } // Function to transform string void transformSting(string a) { string b = delete_vowels(a); string c = change_case(b); string d = insert_hash(c); //corner case // when all the words of string are vowel then string empty after deletion if(d=="""") cout<<""-1""< using namespace std; // A utility function to swap characters void swap ( char* a, char* b ) { char t = *a; *a = *b; *b = t; } // A utility function to reverse string str[low..high] void reverse ( char* str, int low, int high ) { while ( low < high ) { swap( &str[low], &str[high] ); ++low; --high; } } // Cycle leader algorithm to move all even // positioned elements at the end. void cycleLeader ( char* str, int shift, int len ) { int j; char item; for (int i = 1; i < len; i *= 3 ) { j = i; item = str[j + shift]; do { // odd index if ( j & 1 ) j = len / 2 + j / 2; // even index else j /= 2; // keep the back-up of element at new position swap (&str[j + shift], &item); } while ( j != i ); } } // The main function to transform a string. This function // mainly uses cycleLeader() to transform void moveNumberToSecondHalf( char* str ) { int k, lenFirst; int lenRemaining = strlen( str ); int shift = 0; while ( lenRemaining ) { k = 0; // Step 1: Find the largest prefix // subarray of the form 3^k + 1 while ( pow( 3, k ) + 1 <= lenRemaining ) k++; lenFirst = pow( 3, k - 1 ) + 1; lenRemaining -= lenFirst; // Step 2: Apply cycle leader algorithm // for the largest subarrau cycleLeader ( str, shift, lenFirst ); // Step 4.1: Reverse the second half of first subarray reverse ( str, shift / 2, shift - 1 ); // Step 4.2: Reverse the first half of second sub-string. reverse ( str, shift, shift + lenFirst / 2 - 1 ); // Step 4.3 Reverse the second half of first sub-string // and first half of second sub-string together reverse ( str, shift / 2, shift + lenFirst / 2 - 1 ); // Increase the length of first subarray shift += lenFirst; } } // Driver program to test above function int main() { char str[] = ""a1b2c3d4e5f6g7""; moveNumberToSecondHalf( str ); cout< using namespace std; int countTransformation(string a, string b) { int n = a.size(), m = b.size(); // If b = """" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) return 1; int dp[m][n]; memset(dp, 0, sizeof(dp)); // Fill dp[][] in bottom up manner // Traverse all character of b[] for (int i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (int j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 0) { if (j == 0) dp[i][j] = (a[j] == b[i]) ? 1 : 0; else if (a[j] == b[i]) dp[i][j] = dp[i][j - 1] + 1; else dp[i][j] = dp[i][j - 1]; } // Filling other rows. else { if (a[j] == b[i]) dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]; else dp[i][j] = dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } // Driver code int main() { string a = ""abcccdf"", b = ""abccdf""; cout << countTransformation(a, b) << endl; return 0; }",quadratic,quadratic "// C++ program to convert a ternary expression to // a tree. #include using namespace std; // tree structure struct Node { char data; Node *left, *right; }; // function create a new node Node *newNode(char Data) { Node *new_node = new Node; new_node->data = Data; new_node->left = new_node->right = NULL; return new_node; } // Function to convert Ternary Expression to a Binary // Tree. It return the root of tree // Notice that we pass index i by reference because we // want to skip the characters in the subtree Node *convertExpression(string str, int & i) { // store current character of expression_string // [ 'a' to 'z'] Node * root =newNode(str[i]); //If it was last character return //Base Case if(i==str.length()-1) return root; // Move ahead in str i++; //If the next character is '?'.Then there will be subtree for the current node if(str[i]=='?') { //skip the '?' i++; // construct the left subtree // Notice after the below recursive call i will point to ':' // just before the right child of current node since we pass i by reference root->left = convertExpression(str,i); //skip the ':' character i++; //construct the right subtree root->right = convertExpression(str,i); return root; } //If the next character is not '?' no subtree just return it else return root; } // function print tree void printTree( Node *root) { if (!root) return ; cout << root->data <<"" ""; printTree(root->left); printTree(root->right); } // Driver program to test above function int main() { string expression = ""a?b?c:d:e""; int i=0; Node *root = convertExpression(expression, i); printTree(root) ; return 0; }",linear,linear "// C++ Program to convert prefix to Infix #include #include using namespace std; // function to check if character is operator or not bool isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': case '^': case '%': return true; } return false; } // Convert prefix to Infix expression string preToInfix(string pre_exp) { stack s; // length of expression int length = pre_exp.size(); // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = ""("" + op1 + pre_exp[i] + op2 + "")""; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, pre_exp[i])); } } // Stack now contains the Infix expression return s.top(); } // Driver Code int main() { string pre_exp = ""*-A/BC-/AKL""; cout << ""Infix : "" << preToInfix(pre_exp); return 0; }",linear,linear "// CPP Program to convert prefix to postfix #include #include using namespace std; // function to check if character is operator or not bool isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert prefix to Postfix expression string preToPost(string pre_exp) { stack s; // length of expression int length = pre_exp.size(); // reading from right to left for (int i = length - 1; i >= 0; i--) { // check if symbol is operator if (isOperator(pre_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = op1 + op2 + pre_exp[i]; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, pre_exp[i])); } } // stack contains only the Postfix expression return s.top(); } // Driver Code int main() { string pre_exp = ""*-A/BC-/AKL""; cout << ""Postfix : "" << preToPost(pre_exp); return 0; }",linear,linear "// CPP Program to convert postfix to prefix #include using namespace std; // function to check if character is operator or not bool isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } // Convert postfix to Prefix expression string postToPre(string post_exp) { stack s; // length of expression int length = post_exp.size(); // reading from right to left for (int i = 0; i < length; i++) { // check if symbol is operator if (isOperator(post_exp[i])) { // pop two operands from stack string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); // concat the operands and operator string temp = post_exp[i] + op2 + op1; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, post_exp[i])); } } string ans = """"; while (!s.empty()) { ans += s.top(); s.pop(); } return ans; } // Driver Code int main() { string post_exp = ""ABC/-AK/L-*""; // Function call cout << ""Prefix : "" << postToPre(post_exp); return 0; }",linear,linear "// CPP program to find infix for // a given postfix. #include using namespace std; bool isOperand(char x) { return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'); } // Get Infix for a given postfix // expression string getInfix(string exp) { stack s; for (int i=0; exp[i]!='\0'; i++) { // Push operands if (isOperand(exp[i])) { string op(1, exp[i]); s.push(op); } // We assume that input is // a valid postfix and expect // an operator. else { string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); s.push(""("" + op2 + exp[i] + op1 + "")""); } } // There must be a single element // in stack now which is the required // infix. return s.top(); } // Driver code int main() { string exp = ""ab*c+""; cout << getInfix(exp); return 0; }",linear,linear "// C++ program for space optimized // solution of Word Wrap problem. #include using namespace std; // Function to find space optimized // solution of Word Wrap problem. void solveWordWrap(int arr[], int n, int k) { int i, j; // Variable to store number of // characters in given line. int currlen; // Variable to store possible // minimum cost of line. int cost; // DP table in which dp[i] represents // cost of line starting with word // arr[i]. int dp[n]; // Array in which ans[i] store index // of last word in line starting with // word arr[i]. int ans[n]; // If only one word is present then // only one line is required. Cost // of last line is zero. Hence cost // of this line is zero. Ending point // is also n-1 as single word is // present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first word of line // by iterating over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = INT_MAX; // Keep on adding words in current // line by iterating from starting // word upto last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) cost = 0; else cost = (k - currlen) * (k - currlen) + dp[j + 1]; // Check if this arrangement gives // minimum cost for line starting // with word arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index and ending index // of words present in each line. i = 0; while (i < n) { cout << i + 1 << "" "" << ans[i] + 1 << "" ""; i = ans[i] + 1; } } // Driver function int main() { int arr[] = { 3, 2, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int M = 6; solveWordWrap(arr, n, M); return 0; }",linear,quadratic "// C++ program to print minimum number that can be formed // from a given sequence of Is and Ds #include using namespace std; // Function to decode the given sequence to construct // minimum number without repeated digits void PrintMinNumberForPattern(string seq) { // result store output string string result; // create an empty stack of integers stack stk; // run n+1 times where n is length of input sequence for (int i = 0; i <= seq.length(); i++) { // push number i+1 into the stack stk.push(i + 1); // if all characters of the input sequence are // processed or current character is 'I' // (increasing) if (i == seq.length() || seq[i] == 'I') { // run till stack is empty while (!stk.empty()) { // remove top element from the stack and // add it to solution result += to_string(stk.top()); result += "" ""; stk.pop(); } } } cout << result << endl; } // main function int main() { PrintMinNumberForPattern(""IDID""); PrintMinNumberForPattern(""I""); PrintMinNumberForPattern(""DD""); PrintMinNumberForPattern(""II""); PrintMinNumberForPattern(""DIDI""); PrintMinNumberForPattern(""IIDDD""); PrintMinNumberForPattern(""DDIDDIID""); return 0; }",linear,linear "// C++ program of above approach #include using namespace std; // Returns minimum number made from given sequence without repeating digits string getMinNumberForPattern(string seq) { int n = seq.length(); if (n >= 9) return ""-1""; string result(n+1, ' '); int count = 1; // The loop runs for each input character as well as // one additional time for assigning rank to remaining characters for (int i = 0; i <= n; i++) { if (i == n || seq[i] == 'I') { for (int j = i - 1 ; j >= -1 ; j--) { result[j + 1] = '0' + count++; if(j >= 0 && seq[j] == 'I') break; } } } return result; } // main function int main() { string inputs[] = {""IDID"", ""I"", ""DD"", ""II"", ""DIDI"", ""IIDDD"", ""DDIDDIID""}; for (string input : inputs) { cout << getMinNumberForPattern(input) << ""\n""; } return 0; }",linear,linear "// c++ program to generate required sequence #include #include #include #include using namespace std; //:param s: a seq consisting only of 'D' and 'I' chars. D is //for decreasing and I for increasing :return: digits from //1-9 that fit the str. The number they repr should the min //such number vector didi_seq_gen(string s) { if (s.size() == 0) return {}; vector base_list = { ""1"" }; for (int i = 2; i < s.size() + 2; i++) base_list.push_back(to_string(i)); int last_D = -1; for (int i = 1; i < base_list.size(); i++) { if (s[i - 1] == 'D') { if (last_D < 0) last_D = i - 1; string v = base_list[i]; base_list.erase(base_list.begin() + i); base_list.insert(base_list.begin() + last_D, v); } else last_D = -1; } return base_list; } int main() { vector inputs = { ""IDID"", ""I"", ""DD"", ""II"", ""DIDI"", ""IIDDD"", ""DDIDDIID"" }; for (auto x : inputs) { vector ans = didi_seq_gen(x); for (auto i : ans) { cout << i; } cout << endl; } return 0; }",linear,linear "// C++ program to print shortest possible path to // type all characters of given string using a remote #include using namespace std; // Function to print shortest possible path to // type all characters of given string using a remote void printPath(string str) { int i = 0; // start from character 'A' present at position (0, 0) int curX = 0, curY = 0; while (i < str.length()) { // find coordinates of next character int nextX = (str[i] - 'A') / 5; int nextY = (str[i] - 'B' + 1) % 5; // Move Up if destination is above while (curX > nextX) { cout << ""Move Up"" << endl; curX--; } // Move Left if destination is to the left while (curY > nextY) { cout << ""Move Left"" << endl; curY--; } // Move down if destination is below while (curX < nextX) { cout << ""Move Down"" << endl; curX++; } // Move Right if destination is to the right while (curY < nextY) { cout << ""Move Right"" << endl; curY++; } // At this point, destination is reached cout << ""Press OK"" << endl; i++; } } // Driver code int main() { string str = ""COZY""; printPath(str); return 0; }",constant,quadratic "// C++ program to find minimum number of points // in a given path #include using namespace std; // method returns minimum number of points in given path int numberOfPointInPath(string path) { int N = path.length(); // Map to store last occurrence of direction map dirMap; // variable to store count of points till now, // initializing from 1 to count first point int points = 1; // looping over all characters of path string for (int i = 0; i < N; i++) { // storing current direction in curDir // variable char curDir = path[i]; // marking current direction as visited dirMap[curDir] = 1; // if at current index, we found both 'L' // and 'R' or 'U' and 'D' then current // index must be a point if ((dirMap['L'] && dirMap['R']) || (dirMap['U'] && dirMap['D'])) { // clearing the map for next segment dirMap.clear(); // increasing point count points++; // revisiting current direction for next segment dirMap[curDir] = 1; } } // +1 to count the last point also return (points + 1); } // Driver code to test above methods int main() { string path = ""LLUUULLDD""; cout << numberOfPointInPath(path) << endl; return 0; }",linear,nlogn "// CPP program to check whether second string // can be formed from first string #include using namespace std; const int MAX = 256; bool canMakeStr2(string str1, string str2) { // Create a count array and count frequencies // characters in str1. int count[MAX] = {0}; for (int i = 0; i < str1.length(); i++) count[str1[i]]++; // Now traverse through str2 to check // if every character has enough counts for (int i = 0; i < str2.length(); i++) { if (count[str2[i]] == 0) return false; count[str2[i]]--; } return true; } // Driver Code int main() { string str1 = ""geekforgeeks""; string str2 = ""for""; if (canMakeStr2(str1, str2)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,linear "// C++ code to find the reverse alphabetical // order from a given position #include #include using namespace std; // Function which take the given string // and the position from which the reversing shall // be done and returns the modified string string compute(string str, int n) { // Creating a string having reversed alphabetical order string reverseAlphabet = ""zyxwvutsrqponmlkjihgfedcba""; int l = str.length(); // The string up to the point specified in the question, // the string remains unchanged and from the point up to // the length of the string, we reverse the alphabetical // order for (int i = n; i < l; i++) str[i] = reverseAlphabet[str[i] - 'a']; return str; } // Driver function int main() { string str = ""pneumonia""; int n = 4; string answer = compute(str, n - 1); cout << answer; return 0; }",constant,linear "// CPP program to find last index of // character x in given string. #include using namespace std; // Returns last index of x if it is present. // Else returns -1. int findLastIndex(string& str, char x) { int index = -1; for (int i = 0; i < str.length(); i++) if (str[i] == x) index = i; return index; } // Driver code int main() { // String in which char is to be found string str = ""geeksforgeeks""; // char whose index is to be found char x = 'e'; int index = findLastIndex(str, x); if (index == -1) cout << ""Character not found""; else cout << ""Last index is "" << index; return 0; }",constant,linear "// Simple CPP program to find last index of // character x in given string. #include using namespace std; // Returns last index of x if it is present. // Else returns -1. int findLastIndex(string& str, char x) { // Traverse from right for (int i = str.length() - 1; i >= 0; i--) if (str[i] == x) return i; return -1; } // Driver code int main() { string str = ""geeksforgeeks""; char x = 'e'; int index = findLastIndex(str, x); if (index == -1) cout << ""Character not found""; else cout << ""Last index is "" << index; return 0; }",constant,linear "// C++ program to find position of a number // in a series of numbers with 4 and 7 as the // only digits. #include #include using namespace std; int findpos(string n) { int i = 0, pos = 0; while (n[i] != '\0') { // check all digit position switch (n[i]) { // if number is left then pos*2+1 case '4': pos = pos * 2 + 1; break; // if number is right then pos*2+2 case '7': pos = pos * 2 + 2; break; } i++; } return pos; } // Driver code int main() { // given a number which is constructed // by 4 and 7 digit only string n = ""774""; cout << findpos(n); return 0; }",constant,linear "// C++++ program to find winner in an election. #include ""bits/stdc++.h"" using namespace std; /* We have four Candidates with name as 'John', 'Johnny', 'jamie', 'jackie'. The votes in String array are as per the votes casted. Print the name of candidates received Max vote. */ void findWinner(vector& votes) { // Insert all votes in a hashmap unordered_map mapObj; for (auto& str : votes) { mapObj[str]++; } // Traverse through map to find the candidate // with maximum votes. int maxValueInMap = 0; string winner; for (auto& entry : mapObj) { string key = entry.first; int val = entry.second; if (val > maxValueInMap) { maxValueInMap = val; winner = key; } // If there is a tie, pick lexicographically // smaller. else if (val == maxValueInMap && winner > key) winner = key; } cout << winner << endl; } // Driver code int main() { vector votes = { ""john"", ""johnny"", ""jackie"", ""johnny"", ""john"", ""jackie"", ""jamie"", ""jamie"", ""john"", ""johnny"", ""jamie"", ""johnny"", ""john"" }; findWinner(votes); return 0; }",linear,linear "// CPP program to check if a query string // is present is given set. #include using namespace std; const int MAX_CHAR = 256; bool isPresent(string s, string q) { // Count occurrences of all characters // in s. int freq[MAX_CHAR] = { 0 }; for (int i = 0; i < s.length(); i++) freq[s[i]]++; // Check if number of occurrences of // every character in q is less than // or equal to that in s. for (int i = 0; i < q.length(); i++) { freq[q[i]]--; if (freq[q[i]] < 0) return false; } return true; } // driver program int main() { string s = ""abctd""; string q = ""cat""; if (isPresent(s, q)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,linear "// CPP program to find the arrangement // of queue at time = t #include using namespace std; // prints the arrangement at time = t void solve(int n, int t, string s) { // Checking the entire queue for // every moment from time = 1 to // time = t. for (int i = 0; i < t; i++) for (int j = 0; j < n - 1; j++) /*If current index contains 'B' and next index contains 'G' then swap*/ if (s[j] == 'B' && s[j + 1] == 'G') { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; j++; } cout << s; } // Driver function for the program int main() { int n = 6, t = 2; string s = ""BBGBBG""; solve(n, t, s); return 0; }",constant,quadratic "// C++ program to check whether the // given EMEI number is valid or not. #include using namespace std; // Function for finding and returning // sum of digits of a number int sumDig(int n) { int a = 0; while (n > 0) { a = a + n % 10; n = n / 10; } return a; } bool isValidIMEI(long n) { // Converting the number into // String for finding length string s = to_string(n); int len = s.length(); if (len != 15) return false; int sum = 0; for(int i = len; i >= 1; i--) { int d = (int)(n % 10); // Doubling every alternate digit if (i % 2 == 0) d = 2 * d; // Finding sum of the digits sum += sumDig(d); n = n / 10; } return (sum % 10 == 0); } // Driver code int main() { // 15 digits cannot be stored // in 'int' data type long n = 490154203237518L; if (isValidIMEI(n)) cout << ""Valid IMEI Code""; else cout << ""Invalid IMEI Code""; return 0; } // This code is contributed by Yash_R",linear,nlogn "// C++ program to decode a median string // to the original string #include using namespace std; // function to calculate the median back string string decodeMedianString(string s) { // length of string int l = s.length(); // initialize a blank string string s1 = """"; // Flag to check if length is even or odd bool isEven = (l % 2 == 0)? true : false; // traverse from first to last for (int i = 0; i < l; i += 2) { // if len is even then add first character // to beginning of new string and second // character to end if (isEven) { s1 = s[i] + s1; s1 += s[i + 1]; } else { // if current length is odd and is // greater than 1 if (l - i > 1) { // add first character to end and // second character to beginning s1 += s[i]; s1 = s[i + 1] + s1; } else { // if length is 1, add character // to end s1 += s[i]; } } } return s1; } // driver program int main() { string s = ""eekgs""; cout << decodeMedianString(s); return 0; }",constant,linear "// CPP program to check if a // given ISBN is valid or not #include using namespace std; bool isValidISBN(string& isbn) { // length must be 10 int n = isbn.length(); if (n != 10) return false; // Computing weighted sum // of first 9 digits int sum = 0; for (int i = 0; i < 9; i++) { int digit = isbn[i] - '0'; if (0 > digit || 9 < digit) return false; sum += (digit * (10 - i)); } // Checking last digit. char last = isbn[9]; if (last != 'X' && (last < '0' || last > '9')) return false; // If last digit is 'X', add 10 // to sum, else add its value. sum += ((last == 'X') ? 10 : (last - '0')); // Return true if weighted sum // of digits is divisible by 11. return (sum % 11 == 0); } // Driver code int main() { string isbn = ""007462542X""; if (isValidISBN(isbn)) cout << ""Valid""; else cout << ""Invalid""; return 0; }",constant,constant "// C++ program to check if a given credit // card is valid or not. #include using namespace std; // Return this number if it is a single digit, otherwise, // return the sum of the two digits int getDigit(int number) { if (number < 9) return number; return number / 10 + number % 10; } // Return the number of digits in d int getSize(long d) { string num = to_string(d); return num.length(); } // Return the first k number of digits from // number. If the number of digits in number // is less than k, return number. long getPrefix(long number, int k) { if (getSize(number) > k) { string num = to_string(number); return stol(num.substr(0, k)); } return number; } // Return true if the digit d is a prefix for number bool prefixMatched(long number, int d) { return getPrefix(number, getSize(d)) == d; } // Get the result from Step 2 int sumOfDoubleEvenPlace(long int number) { int sum = 0; string num = to_string(number) ; for (int i = getSize(number) - 2; i >= 0; i -= 2) sum += getDigit(int(num[i] - '0') * 2); return sum; } // Return sum of odd-place digits in number int sumOfOddPlace(long number) { int sum = 0; string num = to_string(number) ; for (int i = getSize(number) - 1; i >= 0; i -= 2) sum += num[i] - '0'; return sum; } // Return true if the card number is valid bool isValid(long int number) { return (getSize(number) >= 13 && getSize(number) <= 16) && (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 37) || prefixMatched(number, 6)) && ((sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0); } // Driver Code int main() { long int number = 5196081888500645L; cout << number << "" is "" << (isValid(number) ? ""valid"" : ""invalid""); return 0; } // This code is contributed by yuvraj_chandra",constant,linear "// CPP program to Maximize the given number. #include using namespace std; // Function to maximize the number N with // limit as M. string maximizeNumber(string N, int M) { // Sorting the digits of the // number in increasing order. sort(N.begin(), N.end()); for (int i = 0; i < N.size(); i++) { for (int j = i + 1; j < N.size(); j++) { // Copying the string into another // temp string. string t = N; // Swapping the j-th char(digit) // with i-th char(digit) swap(t[j], t[i]); // Sorting the temp string // from i-th pos to end. sort(t.begin() + i + 1, t.end()); // Checking if the string t is // greater than string N and less // than or equal to the number M. if (stoll(t) > stoll(N) && stoll(t) <= M) // If yes then, we will permanently // swap the i-th char(or digit) // with j-th char(digit). swap(N[i], N[j]); } } // Returns the maximized number. return N; } // Driver function int main() { string N = ""123""; int M = 222; cout << maximizeNumber(N, M); return 0; } // This code is contributed by KaaL-EL.",linear,cubic "// CPP program to find if a given corner string // is present at corners. #include using namespace std; bool isCornerPresent(string str, string corner) { int n = str.length(); int cl = corner.length(); // If length of corner string is more, it // cannot be present at corners. if (n < cl) return false; // Return true if corner string is present at // both corners of given string. return (str.substr(0, cl).compare(corner) == 0 && str.substr(n-cl, cl).compare(corner) == 0); } // Driver code int main() { string str = ""geeksforgeeks""; string corner = ""geeks""; if (isCornerPresent(str, corner)) cout << ""Yes""; else cout << ""No""; return 0; }",constant,linear