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 que...
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<...
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 D...
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 ...
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 Prefi...
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; s...
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...
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 (tem...
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...
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) { ...
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] > ...
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,...
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,...
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,...
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...
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 ...
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; } // Fun...
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*) m...
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...
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 item...
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...
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(); ...
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; } }; ...
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 s...
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 ...
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(...
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...
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...
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::...
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) { ...
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[] arr...
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 fo...
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(unsi...
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 << ...
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 ...
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...
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 ...
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 le...
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 expre...
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...
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; ...
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 open...
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 (tem...
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 == '...
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 ...
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) ret...
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 ...
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; ...
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 ...
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[]) { /...
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 ...
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 ...
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; // Pushi...
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]); } sta...
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(...
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++) ...
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 o...
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...
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; ...
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) ...
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)...
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) { ...
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; whi...
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...
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) { ...
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...
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 th...
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 fo...
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 // b...
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 st...
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}; //...
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 resu...
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 ...
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++) ...
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;...
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; /...
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]) { // E...
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...
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(s...
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" +...
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 larg...
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}; ...
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"; ...
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.lengt...
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; // loo...
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();...
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 subarra...
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 *ne...
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 ...
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 ...
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; ...
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...
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(); ...
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++) { ...
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 i...
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...
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] && fr...
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; } ...
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 // ...
linear
linear