code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// C++ program to implement a stack using // Priority queue(min heap) #include<bits/stdc++.h> using namespace std; typedef pair<int, int> 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<pair<int, int> > 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<<s->top()<<endl; s->pop(); } }
linear
logn
// program to demonstrate customized data structure // which supports functions in O(1) #include <iostream> #include <vector> using namespace std; const int MAXX = 1000; // class stack class stack { int minn; int size; public: stack() { minn = 99999; size = -1; } vector<pair<int, int> > 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 <bits/stdc++.h> 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 <iostream> #include <stack> 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<string> 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 <bits/stdc++.h> 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<string> 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 <iostream> #include <stack> 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<int> 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 <bits/stdc++.h> using namespace std; vector <int> calculateSpan(int arr[], int n) { // Your code here stack<int> s; vector<int> ans; for(int i=0;i<n;i++) { while(!s.empty() and arr[s.top()] <= arr[i]) s.pop(); if(s.empty()) ans.push_back(i+1); else { int top = s.top(); ans.push_back(i-top); } s.push(i); } return ans; } // A utility function to print elements of array void printArray(vector<int> 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<int> 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 <bits/stdc++.h> using namespace std; // Function to check if brackets are balanced bool areBracketsBalanced(string expr) { // Declare a stack to hold the previous brackets. stack<char> 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 <iostream> #include <stack> #include <stdio.h> 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<int> 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 <bits/stdc++.h> using namespace std; stack<pair<int,int>> mystack; map<int, int> 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 <bits/stdc++.h> using namespace std; // Function to find number of next // greater elements on the right of // a given element int nextGreaterElements(vector<int>& 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<int> a = { 3, 4, 2, 7, 5, 8, 10, 6 }; int Q = 2; vector<int> 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 <bits/stdc++.h> #include <list> 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 <bits/stdc++.h> #include <list> 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 <bits/stdc++.h> #include <list> 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<int> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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 <int> values; // stack to store operators. stack <char> 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 <iostream> #include <string.h> 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 <bits/stdc++.h> 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 <bits/stdc++.h> using namespace std; // Below is a recursive function // that inserts an element // at the bottom of a stack. void insert_at_bottom(stack<int>& 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<int>& 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<int> 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<<endl; // function to reverse // the stack reverse(st); cout << "Reversed Stack" << endl; // printing the stack after reversal while (!st.empty()) { cout << st.top() << " "; st.pop(); } return 0; }
linear
quadratic
// C++ program to sort a stack using recursion #include <iostream> 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 <bits/stdc++.h> using namespace std; // This function return the sorted stack stack<int> sortStack(stack<int> &input) { stack<int> 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<int> 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<int> 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<bits/stdc++.h> 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<bits/stdc++.h> using namespace std; // Deletes middle of stack of size // n. Curr is current item number void deleteMid_util(stack<char>&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<char>&s, int sizeOfStack) { deleteMid_util(s,sizeOfStack,0); } //Driver function to test above functions int main() { stack<char> 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 <bits/stdc++.h> using namespace std; // Deletes middle of stack of size n. Curr is current item number void deleteMid(stack<char>& st) { int n = st.size(); stack<char> 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<char> 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 <bits/stdc++.h> using namespace std; // This function return the sorted stack stack<int> sortStack(stack<int> input) { stack<int> 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<int> input; for (int i=0; i<n; i++) input.push(arr[i]); // Sort the temporary stack stack<int> tmpStack = sortStack(input); // Put stack elements in arrp[] for (int i=0; i<n; i++) { arr[i] = tmpStack.top(); tmpStack.pop(); } } // main function int main() { int arr[] = {10, 5, 15, 45}; int n = sizeof(arr)/sizeof(arr[0]); sortArrayUsingStacks(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; }
linear
quadratic
// C++ program to delete elements from array. #include <bits/stdc++.h> using namespace std; // Function for deleting k elements void deleteElements(int arr[], int n, int k) { // Create a stack and push arr[0] stack<int> s; s.push(arr[0]); int count = 0; // traversing a loop from i = 1 to n for (int i=1; i<n; i++) { // condition for deleting an element while (!s.empty() && s.top() < arr[i] && count < k) { s.pop(); count++; } s.push(arr[i]); } // Putting elements of stack in a vector // from end to begin. int m = s.size(); vector<int> 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 <bits/stdc++.h> #define MAXN 100005 using namespace std; // Finding the next greater element of the array. void makeNext(int arr[], int n, int nextBig[]) { stack<pair<int, int> > 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<int, int>(arr[i], i)); } } // Finding the previous greater element of the array. void makePrev(int arr[], int n, int prevBig[]) { stack<pair<int, int> > 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<int, int>(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 <bits/stdc++.h> 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<Interval> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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<int> 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 <bits/stdc++.h> 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<int> 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<int> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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 <bits/stdc++.h> using namespace std; int maxDepth(string& s) { int count = 0; stack<int> 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 <iostream> 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 <bits/stdc++.h> 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 <iostream> #include <stack> using namespace std; void printMaxOfMin(int arr[], int n) { // Used to find previous and next smaller stack<int> 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 <bits/stdc++.h> using namespace std; // Function to check redundant brackets in a // balanced expression bool checkRedundancy(string& str) { // create a stack of characters stack<char> 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 <bits/stdc++.h> using namespace std; void identifyParenthesis(string a) { stack<int> 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 <bits/stdc++.h> 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<int>& v, bool add) { // stack stores the global sign // for operands. stack<bool> 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<int> 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 <bits/stdc++.h> 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 <int> 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 <bits/stdc++.h> using namespace std; // Function to check if brackets are balanced bool areBracketsBalanced(string expr) { // Declare a stack to hold the previous brackets. stack<char> 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 <bits/stdc++.h> 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<char> 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<char> 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<char> 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<bits/stdc++.h> using namespace std; bool canRepresentBST(int pre[], int n) { // Create an empty stack stack<int> s; // Initialize current root as minimum possible // value int root = INT_MIN; // Traverse given array for (int i=0; i<n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) return false; // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (!s.empty() && s.top()<pre[i]) { root = s.top(); s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true; } // Driver program int main() { int pre1[] = {40, 30, 35, 80, 100}; int n = sizeof(pre1)/sizeof(pre1[0]); canRepresentBST(pre1, n)? cout << "true\n": cout << "false\n"; int pre2[] = {40, 30, 35, 20, 80, 100}; n = sizeof(pre2)/sizeof(pre2[0]); canRepresentBST(pre2, n)? cout << "true\n": cout << "false\n"; return 0; }
linear
linear
// C++ program to illustrate if a given array can represent // a preorder traversal of a BST or not #include <bits/stdc++.h> 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 <bits/stdc++.h> 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<int> 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 <bits/stdc++.h> 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 <iostream> #include <stdlib.h> #include <string> #include <vector> 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<string> didi_seq_gen(string s) { if (s.size() == 0) return {}; vector<string> 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<string> inputs = { "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" }; for (auto x : inputs) { vector<string> 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<bits/stdc++.h> 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 stack<int>S; // Traverse all array elements // compute nearest smaller elements of every element for (int i=0; i<n; i++) { // Keep removing top element from S while the top // element is greater than or equal to arr[i] while (!S.empty() && S.top() >= 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<bits/stdc++.h> using namespace std; // function find Next greater element void nextGreater(int arr[], int n, int next[], char order) { // create empty stack stack<int> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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<int> 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 <bits/stdc++.h> using namespace std; // Function for bubble sort using Stack void bubbleSortStack(int a[], int n) { stack<int> s1; // Push all elements of array in 1st stack for(int i = 0; i < n; i++) { s1.push(a[i]); } stack<int> 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 <bits/stdc++.h> 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<struct Node*> 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<bits/stdc++.h> 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<int> input; for (int i=0;i<n;i++) input.push(ip[i]); // output queue queue<int> output; for (int i=0;i<n;i++) output.push(op[i]); // stack to be used for permutation stack <int> 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<bits/stdc++.h> 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 stack<int>s; // 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<n;i++) { // pushed an element from input array to stack s.push(ip[i]); // if our stack isn't empty and top matches with output array // then we will keep popping out from stack uptill top matches with // output array while(!s.empty() and s.top()==op[j]) { s.pop(); // increasing j so next time we can compare next element in output array j++; } } // if output array was a correct permutation of input array then // by now our stack should be empty if(s.empty()) { return true; } return false; } // Driver program to test above function int main() { // Input Array int input[] = {4,5,6,7,8}; // Output Array int output[] = {8,7,6,5,4}; int n = 5; if (checkStackPermutation(input, output, n)) cout << "Yes"; else cout << "Not Possible"; return 0; }
linear
linear
// C++ program to keep track of maximum // element in a stack #include <bits/stdc++.h> using namespace std; class StackWithMax { // main stack stack<int> mainStack; // stack to keep track of max element stack<int> 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 <bits/stdc++.h> using namespace std; // Stack to maintain order of digits stack <int> 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 <bits/stdc++.h> using namespace std; /* Function to reverse the first K elements of the Queue */ void reverseQueueFirstKElements(int k, queue<int>& Queue) { if (Queue.empty() == true || k > Queue.size()) return; if (k <= 0) return; stack<int> 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<int>& Queue) { while (!Queue.empty()) { cout << Queue.front() << " "; Queue.pop(); } } // Driver code int main() { queue<int> 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 <bits/stdc++.h> using namespace std; // Utility function to print the queue void Print(queue<int>& Queue) { while (!Queue.empty()) { cout << Queue.front() << " "; Queue.pop(); } } // Function to reverse the queue void reverseQueue(queue<int>& Queue) { stack<int> Stack; while (!Queue.empty()) { Stack.push(Queue.front()); Queue.pop(); } while (!Stack.empty()) { Queue.push(Stack.top()); Stack.pop(); } } // Driver code int main() { queue<int> 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 <bits/stdc++.h> using namespace std; // Utility function to print the queue void Print(queue<int>& Queue) { while (!Queue.empty()) { cout << Queue.front() << " "; Queue.pop(); } } // Function to reverse the queue void reverseQueue(queue<int>& 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<int> 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 <bits/stdc++.h> using namespace std; // Function to check if elements are // pairwise consecutive in stack bool pairWiseConsecutive(stack<int> s) { // Transfer elements of s to aux. stack<int> 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<int> 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 <bits/stdc++.h> using namespace std; // Function to interleave the queue void interLeaveQueue(queue<int>& 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<int> 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<int> 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 <iostream> 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 <bits/stdc++.h> 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<int> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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<int> 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 <bits/stdc++.h> 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<bits/stdc++.h> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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<seg_len; i++) res = res * 10 + (s[i] - '0'); // Find value of remaining segments using sliding // window int seg_len_pow = pow(10, seg_len-1); int curr_val = res; for (int i = 1; i <= (s.length() - seg_len); i++) { // To find value of current segment, first remove // leading digit from previous value curr_val = curr_val - (s[i-1]- '0')*seg_len_pow; // Then add trailing digit curr_val = curr_val*10 + (s[i+seg_len-1]- '0'); res = max(res, curr_val); } return res; } // Driver's Function int main() { string s = "8754"; int k = 2; cout << "Maximum number = " << findMaxSegment(s, k); return 0; }
constant
linear
// C++ program to find if a number is divisible by // 4 or not #include <bits/stdc++.h> 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 <bits/stdc++.h> #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 <bits/stdc++.h> 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<bin.size(); i+= 2) { // if digit of base 4 is at odd place, then // add it to odd_sum if (isOddDigit) odd_sum += equivalentBase4(bin.substr(i, 2)); // else digit of base 4 is at even place, // add it to even_sum else even_sum += equivalentBase4(bin.substr(i, 2)); isOddDigit ^= 1; } // if this diff is divisible by 11(which is 5 in decimal) // then, the binary number is divisible by 5 if (abs(odd_sum - even_sum) % 5 == 0) return "Yes"; // else not divisible by 5 return "No"; } // Driver program to test above int main() { string bin = "10000101001"; cout << isDivisibleBy5(bin); return 0; }
constant
linear
// CPP Program to count substrings which are // divisible by 8 but not by 3 #include <bits/stdc++.h> 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) <<endl; return 0; }
linear
linear
// CPP for divisibility of number by 999 #include<bits/stdc++.h> 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<n; i++) { // group saves 3-digit group int group = 0; group += (num[i++] - '0') * 100; group += (num[i++] - '0') * 10; group += num[i] - '0'; gSum += group; } // calculate result till 3 digit sum if (gSum > 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 <bits/stdc++.h> 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<iostream> 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 <iostream> 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 <iostream> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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<bits/stdc++.h> 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<n; i++) { int curr_xor = 0; // to store xor of current subarray // Pick ending points of subarrays starting with i for (int j=i; j<n; j++) { curr_xor = curr_xor ^ arr[j]; ans = max(ans, curr_xor); } } return ans; } // Driver program to test above functions int main() { int arr[] = {8, 1, 2, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n); return 0; }
constant
quadratic
// C++ program for a Trie based O(n) solution to find max // subarray XOR #include<bits/stdc++.h> 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<<i); // Create a new node if needed if (temp->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<<i); // Traverse Trie, first look for a // prefix that has opposite bit if (temp->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<n; i++) { // update current prefix xor and insert it into Trie pre_xor = pre_xor^arr[i]; insert(root, pre_xor); // Query for current prefix xor in Trie and update // result if required result = max(result, query(root, pre_xor)); } return result; } // Driver program to test above functions int main() { int arr[] = {8, 1, 2, 12}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n); return 0; }
linear
linear
// C++ program to find difficulty of a sentence #include <iostream> 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 <bits/stdc++.h> using namespace std; // Function to print common strings with minimum index sum void find(vector<string> list1, vector<string> list2) { vector<string> 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<string> list1; list1.push_back("GeeksforGeeks"); list1.push_back("Udemy"); list1.push_back("Coursera"); list1.push_back("edX"); // Creating list2 vector<string> 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 <bits/stdc++.h> using namespace std; // Function to print common strings with minimum index sum void find(vector<string> list1, vector<string> list2) { // mapping strings to their indices unordered_map<string, int> map; for (int i = 0; i < list1.size(); i++) map[list1[i]] = i; vector<string> 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<string> list1; list1.push_back("GeeksforGeeks"); list1.push_back("Udemy"); list1.push_back("Coursera"); list1.push_back("edX"); // Creating list2 vector<string> 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<iostream> 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 <bits/stdc++.h> 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 <bits/stdc++.h> 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<bits/stdc++.h> 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<n; j++) { // If this is a new character for this // substring, increment dist_count. if (cnt[str[j] - 'a'] == 0) dist_count++; // Increment count of current character cnt[str[j] - 'a']++; // If distinct character count becomes k, // then increment result. if (dist_count == k) res++; if(dist_count > 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 <iostream> #include <string> #include <unordered_map> 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<char, int> 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 <bits/stdc++.h> 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 <iostream> #include <map> #include <set> #include <string> int min(int a, int b) { return a < b ? a : b; } using namespace std; bool have_same_frequency(map<char, int>& 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<char>(s.begin(), s.end())).size(); for (int length = 1; length <= distinct; length++) { int window_length = length * k; map<char, int> 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 <iostream> 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