code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// C++ program to convert // string into binary string #include <bits/stdc++.h> using namespace std; // utility function void strToBinary(string s) { int n = s.length(); for (int i = 0; i <= n; i++) { // convert each char to // ASCII value int val = int(s[i]); // Convert ASCII value to binary string bin = ""; while (val > 0) { (val % 2)? bin.push_back('1') : bin.push_back('0'); val /= 2; } reverse(bin.begin(), bin.end()); cout << bin << " "; } } // driver code int main() { string s = "geeks"; strToBinary(s); return 0; }
linear
linear
// C++ program to Generate // all binary string without // consecutive 1's of size K #include<bits/stdc++.h> using namespace std ; // A utility function generate all string without // consecutive 1'sof size K void generateAllStringsUtil(int K, char str[], int n) { // Print binary string without consecutive 1's if (n == K) { // Terminate binary string str[n] = '\0' ; cout << str << " "; return ; } // If previous character is '1' then we put // only 0 at end of string //example str = "01" then new string be "010" if (str[n-1] == '1') { str[n] = '0'; generateAllStringsUtil (K , str , n+1); } // If previous character is '0' than we put // both '1' and '0' at end of string // example str = "00" then // new string "001" and "000" if (str[n-1] == '0') { str[n] = '0'; generateAllStringsUtil(K, str, n+1); str[n] = '1'; generateAllStringsUtil(K, str, n+1) ; } } // Function generate all binary string without // consecutive 1's void generateAllStrings(int K ) { // Base case if (K <= 0) return ; // One by one stores every // binary string of length K char str[K]; // Generate all Binary string // starts with '0' str[0] = '0' ; generateAllStringsUtil ( K , str , 1 ) ; // Generate all Binary string // starts with '1' str[0] = '1' ; generateAllStringsUtil ( K , str , 1 ); } // Driver program to test above function int main() { int K = 3; generateAllStrings (K) ; return 0; }
linear
np
#include <bits/stdc++.h> using namespace std; void All_Binary_Strings(bool arr[],int num,int r) { if(r==num) { for(int i=0;i<num;i++) cout<<arr[i]; cout<<" "; return; } else if(arr[r-1]) { arr[r]=0; All_Binary_Strings(arr,num,r+1); } else { arr[r]=0; All_Binary_Strings(arr,num,r+1); arr[r]=1; All_Binary_Strings(arr,num,r+1); } } void print(bool a[],int& num) { a[0]=0; All_Binary_Strings(a,num,1); a[0]=1; All_Binary_Strings(a,num,1); } //driver's code int main() { int n=2; bool a[n]; print(a,n); return 0; }
linear
np
#include <bits/stdc++.h> using namespace std; void All_Binary_Strings(string str,int num) { int len=str.length(); if(len==num) { cout<<str<<" "; return; } else if(str[len-1]=='1') All_Binary_Strings(str+'0',num); else { All_Binary_Strings(str+'0',num); All_Binary_Strings(str+'1',num); } } void print(int& num) { string word; word.push_back('0'); All_Binary_Strings(word,num); word[0]='1'; All_Binary_Strings(word,num); } //driver's code int main() { int n=4; print(n); return 0; }
linear
np
// C++ Program to find ith character in // a binary string. #include <bits/stdc++.h> using namespace std; // Function to store binary Representation void binary_conversion(string &s, int m) { while (m) { int tmp = m % 2; s += tmp + '0'; m = m / 2; } reverse(s.begin(), s.end()); } // Function to find ith character int find_character(int n, int m, int i) { string s; // Function to change decimal to binary binary_conversion(s, m); string s1 = ""; for (int x = 0; x < n; x++) { for (int y = 0; y < s.length(); y++) { if (s[y] == '1') s1 += "10"; else s1 += "01"; } // Assign s1 string in s string s = s1; s1 = ""; } return s[i] - '0'; } // Driver Function int main() { int m = 5, n = 2, i = 8; cout << find_character(n, m, i); return 0; }
linear
quadratic
// CPP program to count substrings // with odd decimal value #include<iostream> using namespace std; // function to count number of substrings // with odd decimal representation int countSubstr(string s) { int n = s.length(); // auxiliary array to store count // of 1's before ith index int auxArr[n] = {0}; if (s[0] == '1') auxArr[0] = 1; // store count of 1's before // i-th index for (int i=1; i<n; i++) { if (s[i] == '1') auxArr[i] = auxArr[i-1]+1; else auxArr[i] = auxArr[i-1]; } // variable to store answer int count = 0; // traverse the string reversely to // calculate number of odd substrings // before i-th index for (int i=n-1; i>=0; i--) if (s[i] == '1') count += auxArr[i]; return count; } // Driver code int main() { string s = "1101"; cout << countSubstr(s); return 0; }
linear
linear
// C++ program to generate n-bit Gray codes #include <iostream> #include <string> #include <vector> using namespace std; // This function generates all n bit Gray codes and prints the // generated codes void generateGrayarr(int n) { // base case if (n <= 0) return; // 'arr' will store all generated codes vector<string> arr; // start with one-bit pattern arr.push_back("0"); arr.push_back("1"); // Every iteration of this loop generates 2*i codes from previously // generated i codes. int i, j; for (i = 2; i < (1<<n); i = i<<1) { // Enter the previously generated codes again in arr[] in reverse // order. Nor arr[] has double number of codes. for (j = i-1 ; j >= 0 ; j--) arr.push_back(arr[j]); // append 0 to the first half for (j = 0 ; j < i ; j++) arr[j] = "0" + arr[j]; // append 1 to the second half for (j = i ; j < 2*i ; j++) arr[j] = "1" + arr[j]; } // print contents of arr[] for (i = 0 ; i < arr.size() ; i++ ) cout << arr[i] << endl; } // Driver program to test above function int main() { generateGrayarr(3); return 0; }
np
np
// C++ program to generate // n-bit Gray codes #include <bits/stdc++.h> using namespace std; // This function generates all n // bit Gray codes and prints the // generated codes vector<string> generateGray(int n) { // Base case if (n <= 0) return {"0"}; if (n == 1) { return {"0","1"}; } //Recursive case vector<string> recAns= generateGray(n-1); vector<string> mainAns; // Append 0 to the first half for(int i=0;i<recAns.size();i++) { string s=recAns[i]; mainAns.push_back("0"+s); } // Append 1 to the second half for(int i=recAns.size()-1;i>=0;i--) { string s=recAns[i]; mainAns.push_back("1"+s); } return mainAns; } // Function to generate the // Gray code of N bits void generateGrayarr(int n) { vector<string> arr; arr=generateGray(n); // print contents of arr for (int i = 0 ; i < arr.size(); i++ ) cout << arr[i] << endl; } // Driver Code int main() { generateGrayarr(3); return 0; }
np
np
// C++ implementation of the above approach #include <bits/stdc++.h> using namespace std; void GreyCode(int n) { // power of 2 for (int i = 0; i < (1 << n); i++) { // Generating the decimal // values of gray code then using // bitset to convert them to binary form int val = (i ^ (i >> 1)); // Using bitset bitset<32> r(val); // Converting to string string s = r.to_string(); cout << s.substr(32 - n) << " "; } } // Driver Code int main() { int n; n = 4; // Function call GreyCode(n); return 0; }
linear
np
// C++ program to print all N-bit binary #include <bits/stdc++.h> using namespace std; /* function to generate n digit numbers*/ void printRec(string number, int extraOnes, int remainingPlaces) { /* if number generated */ if (0 == remainingPlaces) { cout << number << " "; return; } /* Append 1 at the current number and reduce the remaining places by one */ printRec(number + "1", extraOnes + 1, remainingPlaces - 1); /* If more ones than zeros, append 0 to the current number and reduce the remaining places by one*/ if (0 < extraOnes) printRec(number + "0", extraOnes - 1, remainingPlaces - 1); } void printNums(int n) { string str = ""; printRec(str, 0, n); } // Driver code int main() { int n = 4; // Function call printNums(n); return 0; }
linear
linear
// C++ program to print all N-bit binary #include <bits/stdc++.h> #include <iostream> using namespace std; // Function to get the binary representation // of the number N string getBinaryRep(int N, int num_of_bits) { string r = ""; num_of_bits--; // loop for each bit while (num_of_bits >= 0) { if (N & (1 << num_of_bits)) r.append("1"); else r.append("0"); num_of_bits--; } return r; } vector<string> NBitBinary(int N) { vector<string> r; int first = 1 << (N - 1); int last = first * 2; // generate numbers in the range of (2^N)-1 to 2^(N-1) // inclusive for (int i = last - 1; i >= first; --i) { int zero_cnt = 0; int one_cnt = 0; int t = i; int num_of_bits = 0; // longest prefix check while (t) { if (t & 1) one_cnt++; else zero_cnt++; num_of_bits++; t = t >> 1; } // if counts of 1 is greater than // counts of zero if (one_cnt >= zero_cnt) { // do sub-prefixes check bool all_prefix_match = true; int msk = (1 << num_of_bits) - 2; int prefix_shift = 1; while (msk) { int prefix = (msk & i) >> prefix_shift; int prefix_one_cnt = 0; int prefix_zero_cnt = 0; while (prefix) { if (prefix & 1) prefix_one_cnt++; else prefix_zero_cnt++; prefix = prefix >> 1; } if (prefix_zero_cnt > prefix_one_cnt) { all_prefix_match = false; break; } prefix_shift++; msk = msk & (msk << 1); } if (all_prefix_match) { r.push_back(getBinaryRep(i, num_of_bits)); } } } return r; } // Driver code int main() { int n = 4; // Function call vector<string> results = NBitBinary(n); for (int i = 0; i < results.size(); ++i) cout << results[i] << " "; cout << endl; return 0; }
linear
quadratic
// C++ program to add n binary strings #include <bits/stdc++.h> using namespace std; // This function adds two binary strings and return // result as a third string string addBinaryUtil(string a, string b) { string result = ""; // Initialize result int s = 0; // Initialize digit sum // Traverse both strings starting from last // characters int i = a.size() - 1, j = b.size() - 1; while (i >= 0 || j >= 0 || s == 1) { // Compute sum of last digits and carry s += ((i >= 0) ? a[i] - '0' : 0); s += ((j >= 0) ? b[j] - '0' : 0); // If current digit sum is 1 or 3, // add 1 to result result = char(s % 2 + '0') + result; // Compute carry s /= 2; // Move to next digits i--; j--; } return result; } // function to add n binary strings string addBinary(string arr[], int n) { string result = ""; for (int i = 0; i < n; i++) result = addBinaryUtil(result, arr[i]); return result; } // Driver program int main() { string arr[] = { "1", "10", "11" }; int n = sizeof(arr) / sizeof(arr[0]); cout << addBinary(arr, n) << endl; return 0; }
linear
linear
// CPP program to generate power set in // lexicographic order. #include <bits/stdc++.h> using namespace std; // str : Stores input string // n : Length of str. void func(string s, vector<string>& str, int n, int pow_set) { int i, j; for (i = 0; i < pow_set; i++) { string x; for (j = 0; j < n; j++) { if (i & 1 << j) { x = x + s[j]; } } if (i != 0) str.push_back(x); } } int main() { int n; string s; vector<string> str; s = "cab"; n = s.length(); int pow_set = pow(2, n); func(s, str, n, pow_set); sort(str.begin(), str.end()); for (int i = 0; i < str.size(); i++) cout << str[i] << " "; cout << endl; return 0; }
constant
quadratic
// C++ program to print nth permutation with // using next_permute() #include <bits/stdc++.h> using namespace std; // Function to print nth permutation // using next_permute() void nPermute(string str, long int n) { // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep iterating until // we reach nth position long int i = 1; do { // check for nth iteration if (i == n) break; i++; } while (next_permutation(str.begin(), str.end())); // print string after nth iteration cout << str; } // Driver code int main() { string str = "GEEKSFORGEEKS"; long int n = 100; nPermute(str, n); return 0; }
constant
nlogn
// C++ program to print rank of // string using next_permute() #include <bits/stdc++.h> using namespace std; // Function to print rank of string // using next_permute() int findRank(string str) { // store original string string orgStr = str; // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep iterating until // we reach equality condition long int i = 1; do { // check for nth iteration if (str == orgStr) break; i++; } while (next_permutation(str.begin(), str.end())); // return iterator value return i; } // Driver code int main() { string str = "GEEKS"; cout << findRank(str); return 0; }
constant
nlogn
// A simple C++ program to find lexicographically minimum rotation // of a given string #include <iostream> #include <algorithm> using namespace std; // This functionr return lexicographically minimum // rotation of str string minLexRotation(string str) { // Find length of given string int n = str.length(); // Create an array of strings to store all rotations string arr[n]; // Create a concatenation of string with itself string concat = str + str; // One by one store all rotations of str in array. // A rotation is obtained by getting a substring of concat for (int i = 0; i < n; i++) arr[i] = concat.substr(i, n); // Sort all rotations sort(arr, arr+n); // Return the first rotation from the sorted array return arr[0]; } // Driver program to test above function int main() { cout << minLexRotation("GEEKSFORGEEKS") << endl; cout << minLexRotation("GEEKSQUIZ") << endl; cout << minLexRotation("BCABDADAB") << endl; }
linear
quadratic
// C++ program to print all distinct subsequences // of a string. #include <bits/stdc++.h> using namespace std; // Finds and stores result in st for a given // string s. void generate(set<string>& st, string s) { if (s.size() == 0) return; // If current string is not already present. if (st.find(s) == st.end()) { st.insert(s); // Traverse current string, one by one // remove every character and recur. for (int i = 0; i < s.size(); i++) { string t = s; t.erase(i, 1); generate(st, t); } } return; } // Driver code int main() { string s = "xyz"; set<string> st; set<string>::iterator it; generate(st, s); for (auto it = st.begin(); it != st.end(); it++) cout << *it << endl; return 0; }
linear
quadratic
// CPP code to find the lexicographically // smallest string #include <bits/stdc++.h> using namespace std; // Compares two strings by checking if // which of the two concatenations causes // lexicographically smaller string. bool compare(string a, string b) { return (a+b < b+a); } string lexSmallest(string a[], int n) { // Sort strings using above compare() sort(a, a+n, compare); // Concatenating sorted strings string answer = ""; for (int i = 0; i < n; i++) answer += a[i]; return answer; } // Driver code int main() { string a[] = { "c", "cb", "cba" }; int n = sizeof(a)/sizeof(a[0]); cout << lexSmallest(a, n); return 0; }
linear
quadratic
// CPP Program to create concatenation of all // substrings in lexicographic order. #include <bits/stdc++.h> using namespace std; string lexicographicSubConcat(string s) { int n = s.length(); // Creating an array to store substrings int sub_count = n*(n+1)/2; string arr[sub_count]; // finding all substrings of string int index = 0; for (int i = 0; i < n; i++) for (int len = 1; len <= n - i; len++) arr[index++] = s.substr(i, len); // Sort all substrings in lexicographic // order sort(arr, arr + sub_count); // Concatenating all substrings string res = ""; for (int i = 0; i < sub_count; i++) res += arr[i]; return res; } int main() { string s = "abc"; cout << lexicographicSubConcat(s); return 0; }
linear
cubic
// CPP for constructing smallest palindrome #include <bits/stdc++.h> using namespace std; // function for printing palindrome string constructPalin(string str, int len) { int i = 0, j = len - 1; // iterate till i<j for (; i < j; i++, j--) { // continue if str[i]==str[j] if (str[i] == str[j] && str[i] != '*') continue; // update str[i]=str[j]='a' if both are '*' else if (str[i] == str[j] && str[i] == '*') { str[i] = 'a'; str[j] = 'a'; continue; } // update str[i]=str[j] if only str[i]='*' else if (str[i] == '*') { str[i] = str[j]; continue; } // update str[j]=str[i] if only str[j]='*' else if (str[j] == '*') { str[j] = str[i]; continue; } // else print not possible and return cout << "Not Possible"; return ""; } return str; } // driver program int main() { string str = "bca*xc**b"; int len = str.size(); cout << constructPalin(str, len); return 0; }
constant
linear
// CPP program to find Lexicographically // smallest string whose hamming distance // from given string is exactly K #include <bits/stdc++.h> using namespace std; // function to find Lexicographically // smallest string with hamming distance k void findString(string str, int n, int k) { // If k is 0, output input string if (k == 0) { cout << str << endl; return; } // Copying input string into output // string string str2 = str; int p = 0; // Traverse all the character of the // string for (int i = 0; i < n; i++) { // If current character is not 'a' if (str2[i] != 'a') { // copy character 'a' to // output string str2[i] = 'a'; p++; // If hamming distance became k, // break; if (p == k) break; } } // If k is less than p if (p < k) { // Traversing string in reverse // order for (int i = n - 1; i >= 0; i--) if (str[i] == 'a') { str2[i] = 'b'; p++; if (p == k) break; } } cout << str2 << endl; } // Driven Program int main() { string str = "pqrs"; int n = str.length(); int k = 2; findString(str, n, k); return 0; }
linear
linear
// C++ program to find lexicographically next // string #include <bits/stdc++.h> using namespace std; string nextWord(string s) { // If string is empty. if (s == "") return "a"; // Find first character from right // which is not z. int i = s.length() - 1; while (s[i] == 'z' && i >= 0) i--; // If all characters are 'z', append // an 'a' at the end. if (i == -1) s = s + 'a'; // If there are some non-z characters else s[i]++; return s; } // Driver code int main() { string str = "samez"; cout << nextWord(str); return 0; }
constant
linear
// C++ program to find lexicographically largest // subsequence where every character appears at // least k times. #include <bits/stdc++.h> using namespace std; // Find lexicographically largest subsequence of // s[0..n-1] such that every character appears // at least k times. The result is filled in t[] void subsequence(char s[], char t[], int n, int k) { int last = 0, cnt = 0, new_last = 0, size = 0; // Starting from largest character 'z' to 'a' for (char ch = 'z'; ch >= 'a'; ch--) { cnt = 0; // Counting the frequency of the character for (int i = last; i < n; i++) { if (s[i] == ch) cnt++; } // If frequency is greater than k if (cnt >= k) { // From the last point we leave for (int i = last; i < n; i++) { // check if string contain ch if (s[i] == ch) { // If yes, append to output string t[size++] = ch; new_last = i; } } // Update the last point. last = new_last; } } t[size] = '\0'; } // Driver code int main() { char s[] = "banana"; int n = sizeof(s); int k = 2; char t[n]; subsequence(s, t, n - 1, k); cout << t << endl; return 0; }
linear
linear
// CPP program to find the string // in lexicographic order which is // in between given two strings #include <bits/stdc++.h> using namespace std; // Function to find the lexicographically // next string string lexNext(string s, int n) { // Iterate from last character for (int i = n - 1; i >= 0; i--) { // If not 'z', increase by one if (s[i] != 'z') { s[i]++; return s; } // if 'z', change it to 'a' s[i] = 'a'; } } // Driver Code int main() { string S = "abcdeg", T = "abcfgh"; int n = S.length(); string res = lexNext(S, n); // If not equal, print the // resultant string if (res != T) cout << res << endl; else cout << "-1" << endl; return 0; }
constant
linear
// C++ program to demonstrate working of // prev_permutation() #include <bits/stdc++.h> using namespace std; // Driver code int main() { string str = "4321"; if (prev_permutation(str.begin(), str.end())) cout << "Previous permutation is " << str; else cout << "Previous permutation doesn't exist"; return 0; }
constant
linear
// C++ program to print all permutations with // duplicates allowed using prev_permutation() #include <bits/stdc++.h> using namespace std; // Function to compute the previous permutation bool prevPermutation(string& str) { // Find index of the last element of the string int n = str.length() - 1; // Find largest index i such that str[i - 1] > // str[i] int i = n; while (i > 0 && str[i - 1] <= str[i]) i--; // if string is sorted in ascending order // we're at the last permutation if (i <= 0) return false; // Note - str[i..n] is sorted in ascending order // Find rightmost element's index that is less // than str[i - 1] int j = i - 1; while (j + 1 <= n && str[j + 1] < str[i - 1]) j++; // Swap character at i-1 with j swap(str[i - 1], str[j]); // Reverse the substring [i..n] reverse(str.begin() + i, str.end()); return true; } // Driver code int main() { string str = "4321"; if (prevPermutation(str)) cout << "Previous permutation is " << str; else cout << "Previous permutation doesn't exist"; return 0; }
constant
linear
// C++ program to print // n-th permutation #include <bits/stdc++.h> using namespace std; #define ll long long int const int MAX_CHAR = 26; const int MAX_FACT = 20; ll fact[MAX_FACT]; // Utility for calculating factorials void precomputeFactorials() { fact[0] = 1; for (int i = 1; i < MAX_FACT; i++) fact[i] = fact[i - 1] * i; } // Function for nth permutation void nPermute(char str[], int n) { precomputeFactorials(); // Length of given string int len = strlen(str); // Count frequencies of all // characters int freq[MAX_CHAR] = { 0 }; for (int i = 0; i < len; i++) freq[str[i] - 'a']++; // Out string for output string char out[MAX_CHAR]; // Iterate till sum equals n int sum = 0; int k = 0; // We update both n and sum in this // loop. while (sum != n) { sum = 0; // Check for characters present in freq[] for (int i = 0; i < MAX_CHAR; i++) { if (freq[i] == 0) continue; // Remove character freq[i]--; // Calculate sum after fixing // a particular char int xsum = fact[len - 1 - k]; for (int j = 0; j < MAX_CHAR; j++) xsum /= fact[freq[j]]; sum += xsum; // if sum > n fix that char as // present char and update sum // and required nth after fixing // char at that position if (sum >= n) { out[k++] = i + 'a'; n -= (sum - xsum); break; } // if sum < n, add character back if (sum < n) freq[i]++; } } // if sum == n means this // char will provide its // greatest permutation // as nth permutation for (int i = MAX_CHAR - 1; k < len && i >= 0; i--) if (freq[i]) { out[k++] = i + 'a'; freq[i++]--; } // append string termination // character and print result out[k] = '\0'; cout << out; } // Driver program int main() { int n = 2; char str[] = "geeksquiz"; nPermute(str, n); return 0; }
linear
linear
// C++ program to find lexicographic rank // of a string #include <bits/stdc++.h> using namespace std; // A utility function to find // factorial of n int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // A utility function to count // smaller characters on right of arr[low] int findSmallerInRight(string str, int low, int high) { int countRight = 0, i; for (i = low + 1; i <= high; ++i) if (str[i] < str[low]) ++countRight; return countRight; } // A function to find rank of a string // in all permutations of characters int findRank(string str) { int len = str.size(); int mul = fact(len); int rank = 1; int countRight; int i; for (i = 0; i < len; ++i) { mul /= len - i; // Count number of chars smaller than str[i] // from str[i+1] to str[len-1] countRight = findSmallerInRight(str, i, len - 1); rank += countRight * mul; } return rank; } // Driver code int main() { string str = "string"; // Function call cout << findRank(str); return 0; } // This code is contributed by Akanksha Rai
constant
quadratic
// A O(n) solution for finding rank of string #include <bits/stdc++.h> using namespace std; #define MAX_CHAR 256 // A utility function to find factorial of n int fact(int n) { return (n <= 1) ? 1 : n * fact(n - 1); } // Construct a count array where value at every index // contains count of smaller characters in whole string void populateAndIncreaseCount(int* count, string str) { int i; for (i = 0; str[i]; ++i) ++count[str[i]]; for (i = 1; i < MAX_CHAR; ++i) count[i] += count[i - 1]; } // Removes a character ch from count[] array // constructed by populateAndIncreaseCount() void updatecount(int* count, char ch) { int i; for (i = ch; i < MAX_CHAR; ++i) --count[i]; } // A function to find rank of a string in all permutations // of characters int findRank(string str) { int len = str.size(); int mul = fact(len); int rank = 1, i; // All elements of count[] are initialized with 0 int count[MAX_CHAR] = { 0 }; // Populate the count array such that count[i] // contains count of characters which are present // in str and are smaller than i populateAndIncreaseCount(count, str); for (i = 0; i < len; ++i) { mul /= len - i; // Count number of chars smaller than str[i] // from str[i+1] to str[len-1] rank += count[str[i] - 1] * mul; // Reduce count of characters greater than str[i] updatecount(count, str[i]); } return rank; } // Driver code int main() { string str = "string"; // Function call cout << findRank(str); return 0; } // This is code is contributed by rathbhupendra
constant
linear
/* C++ Program for Bad Character Heuristic of Boyer Moore String Matching Algorithm */ #include <bits/stdc++.h> using namespace std; # define NO_OF_CHARS 256 // The preprocessing function for Boyer Moore's // bad character heuristic void badCharHeuristic( string str, int size, int badchar[NO_OF_CHARS]) { int i; // Initialize all occurrences as -1 for (i = 0; i < NO_OF_CHARS; i++) badchar[i] = -1; // Fill the actual value of last occurrence // of a character for (i = 0; i < size; i++) badchar[(int) str[i]] = i; } /* A pattern searching function that uses Bad Character Heuristic of Boyer Moore Algorithm */ void search( string txt, string pat) { int m = pat.size(); int n = txt.size(); int badchar[NO_OF_CHARS]; /* Fill the bad character array by calling the preprocessing function badCharHeuristic() for given pattern */ badCharHeuristic(pat, m, badchar); int s = 0; // s is shift of the pattern with // respect to text while(s <= (n - m)) { int j = m - 1; /* Keep reducing index j of pattern while characters of pattern and text are matching at this shift s */ while(j >= 0 && pat[j] == txt[s + j]) j--; /* If the pattern is present at current shift, then index j will become -1 after the above loop */ if (j < 0) { cout << "pattern occurs at shift = " << s << endl; /* Shift the pattern so that the next character in text aligns with the last occurrence of it in pattern. The condition s+m < n is necessary for the case when pattern occurs at the end of text */ s += (s + m < n)? m-badchar[txt[s + m]] : 1; } else /* Shift the pattern so that the bad character in text aligns with the last occurrence of it in pattern. The max function is used to make sure that we get a positive shift. We may get a negative shift if the last occurrence of bad character in pattern is on the right side of the current character. */ s += max(1, j - badchar[txt[s + j]]); } } /* Driver code */ int main() { string txt= "ABAAABCD"; string pat = "ABC"; search(txt, pat); return 0; } // This code is contributed by rathbhupendra
constant
quadratic
// CPP program to print the // string in 'plus' pattern #include <bits/stdc++.h> #define max 100 using namespace std; // Function to make a cross in the matrix void carveCross(string str) { int n = str.length(); if (n % 2 == 0) { /* As, it is not possible to make the cross exactly in the middle of the matrix with an even length string.*/ cout << "Not possible. Please enter " << "odd length string.\n"; } else { // declaring a 2D array i.e a matrix char arr[max][max]; int m = n / 2; /* Now, we will fill all the elements of the array with 'X'*/ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { arr[i][j] = 'X'; } } /* Now, we will place the characters of the string in the matrix, such that a cross is formed in it.*/ for (int i = 0; i < n; i++) { /* here the characters of the string will be added in the middle column of our array.*/ arr[i][m] = str[i]; } for (int i = 0; i < n; i++) { // here the characters of the // string will be added in the // middle row of our array. arr[m][i] = str[i]; } /* Now finally, we will print the array*/ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << arr[i][j] << " "; } cout << "\n"; } } } // driver code int main() { string str = "PICTURE"; carveCross(str); return 0; }
constant
quadratic
// C++ program to implement wildcard // pattern matching algorithm #include <bits/stdc++.h> using namespace std; // Function that matches input str with // given wildcard pattern bool strmatch(char str[], char pattern[], int n, int m) { // empty pattern can only match with // empty string if (m == 0) return (n == 0); // lookup table for storing results of // subproblems bool lookup[n + 1][m + 1]; // initialize lookup table to false memset(lookup, false, sizeof(lookup)); // empty pattern can match with empty string lookup[0][0] = true; // Only '*' can match with empty string for (int j = 1; j <= m; j++) if (pattern[j - 1] == '*') lookup[0][j] = lookup[0][j - 1]; // fill the table in bottom-up fashion for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // Two cases if we see a '*' // a) We ignore ‘*’ character and move // to next character in the pattern, // i.e., ‘*’ indicates an empty sequence. // b) '*' character matches with ith // character in input if (pattern[j - 1] == '*') lookup[i][j] = lookup[i][j - 1] || lookup[i - 1][j]; // Current characters are considered as // matching in two cases // (a) current character of pattern is '?' // (b) characters actually match else if (pattern[j - 1] == '?' || str[i - 1] == pattern[j - 1]) lookup[i][j] = lookup[i - 1][j - 1]; // If characters don't match else lookup[i][j] = false; } } return lookup[n][m]; } int main() { char str[] = "baaabab"; char pattern[] = "*****ba*****ab"; // char pattern[] = "ba*****ab"; // char pattern[] = "ba*ab"; // char pattern[] = "a*ab"; // char pattern[] = "a*****ab"; // char pattern[] = "*a*****ab"; // char pattern[] = "ba*ab****"; // char pattern[] = "****"; // char pattern[] = "*"; // char pattern[] = "aa?ab"; // char pattern[] = "b*b"; // char pattern[] = "a*a"; // char pattern[] = "baaabab"; // char pattern[] = "?baaabab"; // char pattern[] = "*baaaba*"; if (strmatch(str, pattern, strlen(str), strlen(pattern))) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
quadratic
quadratic
// C++ program to implement wildcard // pattern matching algorithm #include <bits/stdc++.h> using namespace std; // Function that matches input str with // given wildcard pattern vector<vector<int> > dp; int finding(string& s, string& p, int n, int m) { // return 1 if n and m are negative if (n < 0 && m < 0) return 1; // return 0 if m is negative if (m < 0) return 0; // return n if n is negative if (n < 0) { // while m is positive while (m >= 0) { if (p[m] != '*') return 0; m--; } return 1; } // if dp state is not visited if (dp[n][m] == -1) { if (p[m] == '*') { return dp[n][m] = finding(s, p, n - 1, m) || finding(s, p, n, m - 1); } else { if (p[m] != s[n] && p[m] != '?') return dp[n][m] = 0; else return dp[n][m] = finding(s, p, n - 1, m - 1); } } // return dp[n][m] if dp state is previsited return dp[n][m]; } bool isMatch(string s, string p) { dp.clear(); // resize the dp array dp.resize(s.size() + 1, vector<int>(p.size() + 1, -1)); return dp[s.size()][p.size()] = finding(s, p, s.size() - 1, p.size() - 1); } // Driver code int main() { string str = "baaabab"; string pattern = "*****ba*****ab"; // char pattern[] = "ba*****ab"; // char pattern[] = "ba*ab"; // char pattern[] = "a*ab"; // char pattern[] = "a*****ab"; // char pattern[] = "*a*****ab"; // char pattern[] = "ba*ab****"; // char pattern[] = "****"; // char pattern[] = "*"; // char pattern[] = "aa?ab"; // char pattern[] = "b*b"; // char pattern[] = "a*a"; // char pattern[] = "baaabab"; // char pattern[] = "?baaabab"; // char pattern[] = "*baaaba*"; if (isMatch(str, pattern)) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
quadratic
quadratic
// C++ program to implement wildcard // pattern matching algorithm #include <bits/stdc++.h> using namespace std; // Function that matches input text // with given wildcard pattern bool strmatch(char txt[], char pat[], int n, int m) { // empty pattern can only // match with empty string. // Base Case : if (m == 0) return (n == 0); // step-1 : // initialize markers : int i = 0, j = 0, index_txt = -1, index_pat = -1; while (i < n) { // For step - (2, 5) if (j < m && txt[i] == pat[j]) { i++; j++; } // For step - (3) else if (j < m && pat[j] == '?') { i++; j++; } // For step - (4) else if (j < m && pat[j] == '*') { index_txt = i; index_pat = j; j++; } // For step - (5) else if (index_pat != -1) { j = index_pat + 1; i = index_txt + 1; index_txt++; } // For step - (6) else { return false; } } // For step - (7) while (j < m && pat[j] == '*') { j++; } // Final Check if (j == m) { return true; } return false; } // Driver code int main() { char str[] = "baaabab"; char pattern[] = "*****ba*****ab"; // char pattern[] = "ba*****ab"; // char pattern[] = "ba*ab"; // char pattern[] = "a*ab"; if (strmatch(str, pattern, strlen(str), strlen(pattern))) cout << "Yes" << endl; else cout << "No" << endl; char pattern2[] = "a*****ab"; if (strmatch(str, pattern2, strlen(str), strlen(pattern2))) cout << "Yes" << endl; else cout << "No" << endl; return 0; }
constant
linear
// CPP program to replace c1 with c2 // and c2 with c1 #include <bits/stdc++.h> using namespace std; string replace(string s, char c1, char c2) { int l = s.length(); // loop to traverse in the string for (int i = 0; i < l; i++) { // check for c1 and replace if (s[i] == c1) s[i] = c2; // check for c2 and replace else if (s[i] == c2) s[i] = c1; } return s; } // Driver code to check the above function int main() { string s = "grrksfoegrrks"; char c1 = 'e', c2 = 'r'; cout << replace(s, c1, c2); return 0; }
constant
linear
// C++ program for implementation of Aho Corasick algorithm // for string matching using namespace std; #include <bits/stdc++.h> // Max number of states in the matching machine. // Should be equal to the sum of the length of all keywords. const int MAXS = 500; // Maximum number of characters in input alphabet const int MAXC = 26; // OUTPUT FUNCTION IS IMPLEMENTED USING out[] // Bit i in this mask is one if the word with index i // appears when the machine enters this state. int out[MAXS]; // FAILURE FUNCTION IS IMPLEMENTED USING f[] int f[MAXS]; // GOTO FUNCTION (OR TRIE) IS IMPLEMENTED USING g[][] int g[MAXS][MAXC]; // Builds the string matching machine. // arr - array of words. The index of each keyword is important: // "out[state] & (1 << i)" is > 0 if we just found word[i] // in the text. // Returns the number of states that the built machine has. // States are numbered 0 up to the return value - 1, inclusive. int buildMatchingMachine(string arr[], int k) { // Initialize all values in output function as 0. memset(out, 0, sizeof out); // Initialize all values in goto function as -1. memset(g, -1, sizeof g); // Initially, we just have the 0 state int states = 1; // Construct values for goto function, i.e., fill g[][] // This is same as building a Trie for arr[] for (int i = 0; i < k; ++i) { const string &word = arr[i]; int currentState = 0; // Insert all characters of current word in arr[] for (int j = 0; j < word.size(); ++j) { int ch = word[j] - 'a'; // Allocate a new node (create a new state) if a // node for ch doesn't exist. if (g[currentState][ch] == -1) g[currentState][ch] = states++; currentState = g[currentState][ch]; } // Add current word in output function out[currentState] |= (1 << i); } // For all characters which don't have an edge from // root (or state 0) in Trie, add a goto edge to state // 0 itself for (int ch = 0; ch < MAXC; ++ch) if (g[0][ch] == -1) g[0][ch] = 0; // Now, let's build the failure function // Initialize values in fail function memset(f, -1, sizeof f); // Failure function is computed in breadth first order // using a queue queue<int> q; // Iterate over every possible input for (int ch = 0; ch < MAXC; ++ch) { // All nodes of depth 1 have failure function value // as 0. For example, in above diagram we move to 0 // from states 1 and 3. if (g[0][ch] != 0) { f[g[0][ch]] = 0; q.push(g[0][ch]); } } // Now queue has states 1 and 3 while (q.size()) { // Remove the front state from queue int state = q.front(); q.pop(); // For the removed state, find failure function for // all those characters for which goto function is // not defined. for (int ch = 0; ch <= MAXC; ++ch) { // If goto function is defined for character 'ch' // and 'state' if (g[state][ch] != -1) { // Find failure state of removed state int failure = f[state]; // Find the deepest node labeled by proper // suffix of string from root to current // state. while (g[failure][ch] == -1) failure = f[failure]; failure = g[failure][ch]; f[g[state][ch]] = failure; // Merge output values out[g[state][ch]] |= out[failure]; // Insert the next level node (of Trie) in Queue q.push(g[state][ch]); } } } return states; } // Returns the next state the machine will transition to using goto // and failure functions. // currentState - The current state of the machine. Must be between // 0 and the number of states - 1, inclusive. // nextInput - The next character that enters into the machine. int findNextState(int currentState, char nextInput) { int answer = currentState; int ch = nextInput - 'a'; // If goto is not defined, use failure function while (g[answer][ch] == -1) answer = f[answer]; return g[answer][ch]; } // This function finds all occurrences of all array words // in text. void searchWords(string arr[], int k, string text) { // Preprocess patterns. // Build machine with goto, failure and output functions buildMatchingMachine(arr, k); // Initialize current state int currentState = 0; // Traverse the text through the built machine to find // all occurrences of words in arr[] for (int i = 0; i < text.size(); ++i) { currentState = findNextState(currentState, text[i]); // If match not found, move to next state if (out[currentState] == 0) continue; // Match found, print all matching words of arr[] // using output function. for (int j = 0; j < k; ++j) { if (out[currentState] & (1 << j)) { cout << "Word " << arr[j] << " appears from " << i - arr[j].size() + 1 << " to " << i << endl; } } } } // Driver program to test above int main() { string arr[] = {"he", "she", "hers", "his"}; string text = "ahishers"; int k = sizeof(arr)/sizeof(arr[0]); searchWords(arr, k, text); return 0; }
linear
linear
// C++ program to calculate number of times // the pattern occurred in given string #include<iostream> using namespace std; // Returns count of occurrences of "1(0+)1" // int str. int countPattern(string str) { int len = str.size(); bool oneSeen = 0; int count = 0; // Initialize result for (int i = 0; i < len ; i++) { // Check if encountered '1' forms a valid // pattern as specified if (str[i] == '1' && oneSeen == 1) if (str[i - 1] == '0') count++; // if 1 encountered for first time // set oneSeen to 1 if (str[i] == '1' && oneSeen == 0) { oneSeen = 1; continue; } // Check if there is any other character // other than '0' or '1'. If so then set // oneSeen to 0 to search again for new // pattern if (str[i] != '0' && str[i] != '1') oneSeen = 0; } return count; } // Driver program to test above function int main() { string str = "100001abc101"; cout << countPattern(str); return 0; }
constant
linear
// C++ program to in-place replace multiple // occurrences of a pattern by character ‘X’ #include <bits/stdc++.h> using namespace std; // Function to in-place replace multiple // occurrences of a pattern by character ‘X’ void replacePattern(string str, string pattern) { // making an iterator for string str string::iterator it = str.begin(); // run this loop until iterator reaches end of string while (it != str.end()) { // searching the first index in string str where // the first occurrence of string pattern occurs it = search(str.begin(), str.end(), pattern.begin(), pattern.end()); // checking if iterator is not pointing to end of the // string str if (it != str.end()) { // erasing the full pattern string from that iterator // position in string str str.erase(it, it + pattern.size()); // inserting 'X' at that iterator position str.insert(it, 'X'); } } // this loop removes consecutive 'X' in string s // Example: GeeksGeeksforGeeks was changed to 'XXforX' // running this loop will change it to 'XforX' for (int i = 0; i < str.size() - 1; i++) { if (str[i] == 'X' && str[i + 1] == 'X') { // removing 'X' at position i in string str str.erase(str.begin() + i); i--; // i-- because one character was deleted // so repositioning i } } cout << str; } // Driver code int main() { string str = "GeeksforGeeks"; string pattern = "Geeks"; replacePattern(str, pattern); return 0; }
constant
quadratic
// C++ program to find if a string follows order // defined by a given pattern. #include <bits/stdc++.h> using namespace std; const int CHAR_SIZE = 256; // Returns true if characters of str follow // order defined by a given ptr. bool checkPattern(string str, string pat) { // Initialize all orders as -1 vector<int> label(CHAR_SIZE, -1); // Assign an order to pattern characters // according to their appearance in pattern int order = 1; for (int i = 0; i < pat.length() ; i++) { // give the pattern characters order label[pat[i]] = order; // increment the order order++; } // Now one by check if string characters // follow above order int last_order = -1; for (int i = 0; i < str.length(); i++) { if (label[str[i]] != -1) { // If order of this character is less // than order of previous, return false. if (label[str[i]] < last_order) return false; // Update last_order for next iteration last_order = label[str[i]]; } } // return that str followed pat return true; } // Driver code int main() { string str = "engineers rock"; string pattern = "gsr"; cout << boolalpha << checkPattern(str, pattern); return 0; }
constant
linear
// C++ code for finding count // of string in a given 2D // character array. #include <bits/stdc++.h> using namespace std; #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a)) // utility function to search // complete string from any // given index of 2d char array int internalSearch(string needle, int row, int col, string hay[], int row_max, int col_max, int xx) { int found = 0; if (row >= 0 && row <= row_max && col >= 0 && col <= col_max && needle[xx] == hay[row][col]) { char match = needle[xx]; xx += 1; hay[row][col] = 0; if (needle[xx] == 0) { found = 1; } else { // through Backtrack searching // in every directions found += internalSearch(needle, row, col + 1, hay, row_max, col_max,xx); found += internalSearch(needle, row, col - 1, hay, row_max, col_max,xx); found += internalSearch(needle, row + 1, col, hay, row_max, col_max,xx); found += internalSearch(needle, row - 1, col, hay, row_max, col_max,xx); } hay[row][col] = match; } return found; } // Function to search the string in 2d array int searchString(string needle, int row, int col, string str[], int row_count, int col_count) { int found = 0; int r, c; for (r = 0; r < row_count; ++r) { for (c = 0; c < col_count; ++c) { found += internalSearch(needle, r, c, str, row_count - 1, col_count - 1, 0); } } return found; } // Driver code int main() { string needle = "MAGIC"; string input[] = { "BBABBM", "CBMBBA", "IBABBG", "GOZBBI", "ABBBBC", "MCIGAM" }; string str[ARRAY_SIZE(input)]; int i; for (i = 0; i < ARRAY_SIZE(input); ++i) { str[i] = input[i]; } cout << "count: " << searchString(needle, 0, 0, str, ARRAY_SIZE(str), str[0].size()) << endl; return 0; } // This code is contributed by SHUBHAMSINGH8410
quadratic
quadratic
// C++ program to print words in a sentence #include <bits/stdc++.h> using namespace std; void removeDupWord(string str) { // Used to split string around spaces. istringstream ss(str); string word; // for storing each word // Traverse through all words // while loop till we get // strings to store in string word while (ss >> word) { // print the read word cout << word << "\n"; } } // Driver code int main() { string str = "Geeks for Geeks"; removeDupWord(str); return 0; }
linear
linear
// C++ program to check if we can break a string // into four distinct strings. #include<bits/stdc++.h> using namespace std; // Return if the given string can be split or not. bool check(string s) { // We can always break a string of size 10 or // more into four distinct strings. if (s.size() >= 10) return true; // Brute Force for (int i =1; i < s.size(); i++) { for (int j = i + 1; j < s.size(); j++) { for (int k = j + 1; k < s.size(); k++) { // Making 4 string from the given string string s1 = s.substr(0, i); string s2 = s.substr(i, j - i); string s3 = s.substr(j, k - j); string s4 = s.substr(k, s.size() - k); // Checking if they are distinct or not. if (s1 != s2 && s1 != s3 && s1 != s4 && s2 != s3 && s2 != s4 && s3 != s4) return true; } } } return false; } // Driven Program int main() { string str = "aaabb"; (check(str))? (cout << "Yes" << endl): (cout << "No" << endl); return 0; }
linear
np
// CPP program to split an alphanumeric // string using STL #include<bits/stdc++.h> using namespace std; void splitString(string str) { string alpha, num, special; for (int i=0; i<str.length(); i++) { if (isdigit(str[i])) num.push_back(str[i]); else if((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) alpha.push_back(str[i]); else special.push_back(str[i]); } cout << alpha << endl; cout << num << endl; cout << special << endl; } // Driver code int main() { string str = "geeks01$$for02geeks03!@!!"; splitString(str); return 0; }
linear
linear
// C++ program to split a numeric // string in an Increasing // sequence if possible #include <bits/stdc++.h> using namespace std; // Function accepts a string and // checks if string can be split. void split(string str) { int len = str.length(); // if there is only 1 number // in the string then // it is not possible to split it if (len == 1) { cout << ("Not Possible"); return; } string s1 = "", s2 = ""; long num1, num2; for (int i = 0; i <= len / 2; i++) { int flag = 0; // storing the substring from // 0 to i+1 to form initial // number of the increasing sequence s1 = str.substr(0, i + 1); num1 = stoi((s1)); num2 = num1 + 1; // convert string to integer // and add 1 and again convert // back to string s2 s2 = to_string(num2); int k = i + 1; while (flag == 0) { int l = s2.length(); // if s2 is not a substring // of number than not possible if (k + l > len) { flag = 1; break; } // if s2 is the next substring // of the numeric string if ((str.substr(k, k + l) == s2)) { flag = 0; // Increase num2 by 1 i.e the // next number to be looked for num2++; k = k + l; // check if string is fully // traversed then break if (k == len) break; s2 = to_string(num2); l = s2.length(); if (k + 1 > len) { // If next string doesnot occurs // in a given numeric string // then it is not possible flag = 1; break; } } else flag = 1; } // if the string was fully traversed // and conditions were satisfied if (flag == 0) { cout << "Possible " << s1 << endl; break; } // if conditions failed to hold else if (flag == 1 && i > len / 2 - 1) { cout << "Not Possible" << endl; break; } } } // Driver code int main() { string str = "99100"; // Call the split function // for splitting the string split(str); return 0; } // This code is contributed by divyeshrabadiya07
linear
quadratic
// CPP Program to find number of way // to split string such that each partition // starts with distinct character with // maximum number of partitions. #include <bits/stdc++.h> using namespace std; // Returns the number of we can split // the string int countWays(string s) { int count[26] = { 0 }; // Finding the frequency of each // character. for (char x : s) count[x - 'a']++; // making frequency of first character // of string equal to 1. count[s[0] - 'a'] = 1; // Finding the product of frequency // of occurrence of each character. int ans = 1; for (int i = 0; i < 26; ++i) if (count[i] != 0) ans *= count[i]; return ans; } // Driven Program int main() { string s = "acbbcc"; cout << countWays(s) << endl; return 0; }
constant
linear
// C++ program to check if a string can be splitted // into two strings such that one is divisible by 'a' // and other is divisible by 'b'. #include <bits/stdc++.h> using namespace std; // Finds if it is possible to partition str // into two parts such that first part is // divisible by a and second part is divisible // by b. void findDivision(string &str, int a, int b) { int len = str.length(); // Create an array of size len+1 and initialize // it with 0. // Store remainders from left to right when // divided by 'a' vector<int> lr(len+1, 0); lr[0] = (str[0] - '0')%a; for (int i=1; i<len; i++) lr[i] = ((lr[i-1]*10)%a + (str[i]-'0'))%a; // Compute remainders from right to left when // divided by 'b' vector<int> rl(len+1, 0); rl[len-1] = (str[len-1] - '0')%b; int power10 = 10; for (int i= len-2; i>=0; i--) { rl[i] = (rl[i+1] + (str[i]-'0')*power10)%b; power10 = (power10 * 10) % b; } // Find a point that can partition a number for (int i=0; i<len-1; i++) { // If split is not possible at this point if (lr[i] != 0) continue; // We can split at i if one of the following // two is true. // a) All characters after str[i] are 0 // b) String after str[i] is divisible by b, i.e., // str[i+1..n-1] is divisible by b. if (rl[i+1] == 0) { cout << "YES\n"; for (int k=0; k<=i; k++) cout << str[k]; cout << ", "; for (int k=i+1; k<len; k++) cout << str[k]; return; } } cout << "NO\n"; } // Driver code int main() { string str = "123"; int a = 12, b = 3; findDivision(str, a, b); return 0; }
linear
linear
// C++ program to check if a string can be splitted // into two strings such that one is divisible by 'a' // and other is divisible by 'b'. #include <bits/stdc++.h> using namespace std; // Finds if it is possible to partition str // into two parts such that first part is // divisible by a and second part is divisible // by b. string findDivision(string S, int a, int b) { for (int i = 0; i < S.size() - 1; i++) { string firstPart = S.substr(0, i + 1); string secondPart = S.substr(i + 1); if (stoi(firstPart) % a == 0 and stoi(secondPart) % b == 0) return firstPart + " " + secondPart; } return "-1"; } // Driver code int main() { string str = "125"; int a = 12, b = 3; string result = findDivision(str, a, b); if (result == "-1") { cout << "NO" << endl; } else { cout << "YES" << endl; cout << result << endl; } return 0; } // This code is contributed by Ishan Khandelwal
constant
linear
#include <bits/stdc++.h> using namespace std; // This code kind of uses sliding window technique. First // checking if string[0] and string[0..n-1] is divisible if // yes then return else run a loop from 1 to n-1 and check if // taking this (0-i)index number and (i+1 to n-1)index number // on our two declared variables if they are divisible by given two numbers respectively // in any iteration return them simply string stringPartition(string s, int a, int b) { // code here int n = s.length(); // if length is 1 not possible if (n == 1) { return "-1"; } else { // Checking if number formed bt S[0] and S[1->n-1] is divisible int a1 = s[0] - '0'; int a2 = s[1] - '0'; int multiplyer = 10; for (int i = 2; i < n; i++) { a2 = a2 * multiplyer + (s[i] - '0'); } int i = 1; if (a1 % a == 0 && a2 % b == 0) { string k1 = string(1, s[0]); string k2 = ""; for (int j = 1; j < n; j++) k2 += s[j]; return k1 + " " + k2; // return the numbers formed as string } // from here by using sliding window technique we will iterate and check for every i // that if the two current numbers formed are divisible if yes return // else form the two new numbers for next iteration using sliding window technique int q1 = 10; int q2 = 1; for (int i = 1; i < n - 1; i++) q2 *= 10; while (i < n - 1) { char x = s[i]; int ad = x - '0'; a1 = a1 * q1 + ad; a2 = a2 - q2 * ad; if (a1 % a == 0 && a2 % b == 0) { string k1 = ""; string k2 = ""; for (int j = 0; j < i + 1; j++) k1 += s[j]; for (int j = i + 1; j < n; j++) k2 += s[j]; return k1 + " " + k2; } q2 /= 10; i++; } } return "-1"; } // Driver code int main() { string str = "123"; int a = 12, b = 3; string result = stringPartition(str, a, b); if (result == "-1") { cout << "NO" << endl; } else { cout << "YES" << endl; cout << result << endl; } return 0; } // This code is contributed by Kartikey Singh
constant
linear
#include <bits/stdc++.h> using namespace std; // c++ function to count ways to divide a // string in two parts a and b such that // b/pow(10, p) == a int calculate(string N) { int len = N.length(); int l = (len) / 2; int count = 0; for (int i = 1; i <= l; i++) { // substring representing int a string s = N.substr(0, i); // no of digits in a int l1 = s.length(); // consider only most significant // l1 characters of remaining string // for int b string t = N.substr(i, l1); // if any of a or b contains leading 0s // discard this combination if (s[0] == '0' || t[0] == '0') continue; // if both are equal if (s.compare(t) == 0) count++; } return count; } // driver function to test above function int main() { string N = "2202200"; cout << calculate(N); return 0; }
linear
quadratic
// C++ program to divide a string // in n equal parts #include <iostream> #include <string.h> using namespace std; class gfg { // Function to print n equal parts of str public: void divideString(char str[], int n) { int str_size = strlen(str); int i; int part_size; // Check if string can be divided in // n equal parts if (str_size % n != 0) { cout << "Invalid Input: String size"; cout << " is not divisible by n"; return; } // Calculate the size of parts to // find the division points part_size = str_size / n; for (i = 0; i < str_size; i++) { if (i % part_size == 0) cout << endl; cout << str[i]; } } }; // Driver code int main() { gfg g; // length of string is 28 char str[] = "a_simple_divide_string_quest"; // Print 4 equal parts of the string g.divideString(str, 4); return 0; } // This code is contributed by SoM15242
constant
linear
#include <iostream> using namespace std; void divide(string str, int n) { if (str.length() % n != 0) { cout << "Invalid Input: String size"; cout << " is not divisible by n"; return; } int parts = str.length() / n; int start = 0; while (start < str.length()) { cout << str.substr(start, parts) << endl; start += parts; // if(start < str.length()) cout << endl; to ignore // final new line } } int main() { string str = "a_simple_divide_string_quest"; divide(str, 4); } //Contributed By Jagadeesh
linear
linear
// C++ program to find minimum breaks needed // to break a string in dictionary words. #include <bits/stdc++.h> using namespace std; const int ALPHABET_SIZE = 26; // trie node struct TrieNode { struct TrieNode* children[ALPHABET_SIZE]; // isEndOfWord is true if the node // represents end of a word bool isEndOfWord; }; // Returns new trie node (initialized to NULLs) struct TrieNode* getNode(void) { struct TrieNode* pNode = new TrieNode; pNode->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) pNode->children[i] = NULL; return pNode; } // If not present, inserts the key into the trie // If the key is the prefix of trie node, just // marks leaf node void insert(struct TrieNode* root, string key) { struct TrieNode* pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true; } // function break the string into minimum cut // such the every substring after breaking // in the dictionary. void minWordBreak(struct TrieNode* root, string key, int start, int* min_Break, int level = 0) { struct TrieNode* pCrawl = root; // base case, update minimum Break if (start == key.length()) { *min_Break = min(*min_Break, level - 1); return; } // traverse given key(pattern) int minBreak = 0; for (int i = start; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return; // if we find a condition where we can // move to the next word in a trie // dictionary if (pCrawl->children[index]->isEndOfWord) minWordBreak(root, key, i + 1, min_Break, level + 1); pCrawl = pCrawl->children[index]; } } // Driver program to test above functions int main() { string dictionary[] = { "Cat", "Mat", "Ca", "Ma", "at", "C", "Dog", "og", "Do" }; int n = sizeof(dictionary) / sizeof(dictionary[0]); struct TrieNode* root = getNode(); // Construct trie for (int i = 0; i < n; i++) insert(root, dictionary[i]); int min_Break = INT_MAX; minWordBreak(root, "CatMatat", 0, &min_Break, 0); cout << min_Break << endl; return 0; }
linear
quadratic
// A recursive program to print all possible // partitions of a given string into dictionary // words #include <iostream> using namespace std; /* A utility function to check whether a word is present in dictionary or not. An array of strings is used for dictionary. Using array of strings for dictionary is definitely not a good idea. We have used for simplicity of the program*/ int dictionaryContains(string &word) { string dictionary[] = {"mobile","samsung","sam","sung", "man","mango", "icecream","and", "go","i","love","ice","cream"}; int n = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < n; i++) if (dictionary[i].compare(word) == 0) return true; return false; } // Prototype of wordBreakUtil void wordBreakUtil(string str, int size, string result); // Prints all possible word breaks of given string void wordBreak(string str) { // Last argument is prefix wordBreakUtil(str, str.size(), ""); } // Result store the current prefix with spaces // between words void wordBreakUtil(string str, int n, string result) { //Process all prefixes one by one for (int i=1; i<=n; i++) { // Extract substring from 0 to i in prefix string prefix = str.substr(0, i); // If dictionary contains this prefix, then // we check for remaining string. Otherwise // we ignore this prefix (there is no else for // this if) and try next if (dictionaryContains(prefix)) { // If no more elements are there, print it if (i == n) { // Add this element to previous prefix result += prefix; cout << result << endl; return; } wordBreakUtil(str.substr(i, n-i), n-i, result + prefix + " "); } } } //Driver Code int main() { // Function call cout << "First Test:\n"; wordBreak("iloveicecreamandmango"); cout << "\nSecond Test:\n"; wordBreak("ilovesamsungmobile"); return 0; }
quadratic
np
// CPP program to mark balanced and unbalanced // parenthesis. #include <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
// 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 find length of // the longest balanced subsequence #include <bits/stdc++.h> using namespace std; int maxLength(char s[], int n) { int dp[n][n]; memset(dp, 0, sizeof(dp)); // Considering all balanced // substrings of length 2 for (int i = 0; i < n - 1; i++) if (s[i] == '(' && s[i + 1] == ')') dp[i][i + 1] = 2; // Considering all other substrings for (int l = 2; l < n; l++) { for (int i = 0, j = l; j < n; i++, j++) { if (s[i] == '(' && s[j] == ')') dp[i][j] = 2 + dp[i + 1][j - 1]; for (int k = i; k < j; k++) dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j]); } } return dp[0][n - 1]; } // Driver Code int main() { char s[] = "()(((((()"; int n = strlen(s); cout << maxLength(s, n) << endl; return 0; }
quadratic
quadratic
// C++ program to find length of // the longest balanced subsequence #include <bits/stdc++.h> using namespace std; int maxLength(char s[], int n) { // As it's subsequence - assuming first // open brace would map to a first close // brace which occurs after the open brace // to make subsequence balanced and second // open brace would map to second close // brace and so on. // Variable to count all the open brace // that does not have the corresponding // closing brace. int invalidOpenBraces = 0; // To count all the close brace that // does not have the corresponding open brace. int invalidCloseBraces = 0; // Iterating over the String for (int i = 0; i < n; i++) { if (s[i] == '(') { // Number of open braces that // hasn't been closed yet. invalidOpenBraces++; } else { if (invalidOpenBraces == 0) { // Number of close braces that // cannot be mapped to any open // brace. invalidCloseBraces++; } else { // Mapping the ith close brace // to one of the open brace. invalidOpenBraces--; } } } return ( n - (invalidOpenBraces + invalidCloseBraces)); } // Driver Code int main() { char s[] = "()(((((()"; int n = strlen(s); cout << maxLength(s, n) << endl; return 0; }
constant
linear
// C++ program to determine whether given // expression is balanced/ parenthesis // expression or not. #include <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 to evaluate value of an expression. #include <bits/stdc++.h> using namespace std; int evaluateBoolExpr(string s) { int n = s.length(); // Traverse all operands by jumping // a character after every iteration. for (int i = 0; i < n; i += 2) { // If operator next to current operand // is AND. if (s[i + 1] == 'A') { if (s[i + 2] == '0'|| s[i] == '0') s[i + 2] = '0'; else s[i + 2] = '1'; } // If operator next to current operand // is OR. else if (s[i + 1] == 'B') { if (s[i + 2] == '1'|| s[i] == '1') s[i + 2] = '1'; else s[i + 2] = '0'; } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s[i + 2] == s[i]) s[i + 2] = '0'; else s[i + 2] = '1'; } } return s[n - 1] -'0'; } // Driver code int main() { string s = "1C1B1B0A0"; cout << evaluateBoolExpr(s); return 0; }
linear
linear
// A C++ program to find the maximum depth of nested // parenthesis in a given expression #include <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
// C++ Program to find all combinations of Non- // overlapping substrings formed from given // string #include <iostream> using namespace std; // find all combinations of non-overlapping // substrings formed by input string str // index – index of the next character to // be processed // out - output string so far void findCombinations(string str, int index, string out) { if (index == str.length()) cout << out << endl; for (int i = index; i < str.length(); i++) { // append substring formed by str[index, // i] to output string findCombinations( str, i + 1, out + "(" + str.substr(index, i + 1 - index) + ")"); } } // Driver Code int main() { // input string string str = "abcd"; findCombinations(str, 0, ""); return 0; }
quadratic
quadratic
// C++ program to find an index k which // decides the number of opening brackets // is equal to the number of closing brackets #include<bits/stdc++.h> using namespace std; // Function to find an equal index int findIndex(string str) { int len = str.length(); int open[len+1], close[len+1]; int index = -1; memset(open, 0, sizeof (open)); memset(close, 0, sizeof (close)); open[0] = 0; close[len] = 0; if (str[0]=='(') open[1] = 1; if (str[len-1] == ')') close[len-1] = 1; // Store the number of opening brackets // at each index for (int i = 1; i < len; i++) { if ( str[i] == '(' ) open[i+1] = open[i] + 1; else open[i+1] = open[i]; } // Store the number of closing brackets // at each index for (int i = len-2; i >= 0; i--) { if ( str[i] == ')' ) close[i] = close[i+1] + 1; else close[i] = close[i+1]; } // check if there is no opening or closing // brackets if (open[len] == 0) return len; if (close[0] == 0) return 0; // check if there is any index at which // both brackets are equal for (int i=0; i<=len; i++) if (open[i] == close[i]) index = i; return index; } // Driver code int main() { string str = "(()))(()()())))"; cout << findIndex(str); return 0; }
linear
linear
// C++ program to find an index k which // decides the number of opening brackets // is equal to the number of closing brackets #include <bits/stdc++.h> using namespace std; // Function to find an equal index int findIndex(string str) { // STL to count occurrences of ')' int cnt_close = count(str.begin(), str.end(), ')'); for (int i = 0; str[i] != '\0'; i++) if (cnt_close == i) return i; // If no opening brackets return str.size(); } // Driver code int main() { string str = "(()))(()()())))"; cout << findIndex(str); return 0; } // This code is contributed by Dhananjay Dhawale @chessnoobdj
constant
linear
// CPP program to check if two expressions // evaluate to same. #include <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
/* 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 find the longest correct bracket subsequence in a given range */ #include <bits/stdc++.h> using namespace std; /* Declaring Structure for storing three values in each segment tree node */ struct Node { int pairs; int open; // unused int closed; // unused Node() { pairs = open = closed = 0; } }; // A utility function to get the middle index from corner // indexes. int getMid(int s, int e) { return s + (e - s) / 2; } // Returns Parent Node after merging its left and right // child Node merge(Node leftChild, Node rightChild) { Node parentNode; int minMatched = min(leftChild.open, rightChild.closed); parentNode.pairs = leftChild.pairs + rightChild.pairs + minMatched; parentNode.open = leftChild.open + rightChild.open - minMatched; parentNode.closed = leftChild.closed + rightChild.closed - minMatched; return parentNode; } // A recursive function that constructs Segment Tree // for string[ss..se]. si is index of current node in // segment tree st void constructSTUtil(char str[], int ss, int se, Node* st, int si) { // If there is one element in string, store it in // current node of segment tree and return if (ss == se) { // since it contains one element, pairs // will be zero st[si].pairs = 0; // check whether that one element is opening // bracket or not st[si].open = (str[ss] == '(' ? 1 : 0); // check whether that one element is closing // bracket or not st[si].closed = (str[ss] == ')' ? 1 : 0); return; } // If there are more than one elements, then recur // for left and right subtrees and store the relation // of values in this node int mid = getMid(ss, se); constructSTUtil(str, ss, mid, st, si * 2 + 1); constructSTUtil(str, mid + 1, se, st, si * 2 + 2); // Merge left and right child into the Parent Node st[si] = merge(st[si * 2 + 1], st[si * 2 + 2]); } /* Function to construct segment tree from given string. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ Node* constructST(char str[], int n) { // Allocate memory for segment tree // Height of segment tree int x = (int)(ceil(log2(n))); // Maximum size of segment tree int max_size = 2 * (int)pow(2, x) - 1; // Declaring array of structure Allocate memory Node* st = new Node[max_size]; // Fill the allocated memory st constructSTUtil(str, 0, n - 1, st, 0); // Return the constructed segment tree return st; } /* A Recursive function to get the desired Maximum Sum Sub-Array, The following are parameters of the function- st --> Pointer to segment tree si --> Index of the segment tree Node ss & se --> Starting and ending indexes of the segment represented by current Node, i.e., tree[index] qs & qe --> Starting and ending indexes of query range */ Node queryUtil(Node* st, int ss, int se, int qs, int qe, int si) { // No overlap if (ss > qe || se < qs) { // returns a Node for out of bounds condition Node nullNode; return nullNode; } // Complete overlap if (ss >= qs && se <= qe) { return st[si]; } // Partial Overlap Merge results of Left // and Right subtrees int mid = getMid(ss, se); Node left = queryUtil(st, ss, mid, qs, qe, si * 2 + 1); Node right = queryUtil(st, mid + 1, se, qs, qe, si * 2 + 2); // merge left and right subtree query results Node res = merge(left, right); return res; } /* Returns the maximum length correct bracket subsequencebetween start and end It mainly uses queryUtil(). */ int query(Node* st, int qs, int qe, int n) { Node res = queryUtil(st, 0, n - 1, qs, qe, 0); // since we are storing numbers pairs // and have to return maximum length, hence // multiply no of pairs by 2 return 2 * res.pairs; } // Driver Code int main() { char str[] = "())(())(())("; int n = strlen(str); // Build segment tree from given string Node* st = constructST(str, n); // Function call int startIndex = 0, endIndex = 11; cout << "Maximum Length Correct Bracket" " Subsequence between " << startIndex << " and " << endIndex << " = " << query(st, startIndex, endIndex, n) << endl; startIndex = 1, endIndex = 2; cout << "Maximum Length Correct Bracket" " Subsequence between " << startIndex << " and " << endIndex << " = " << query(st, startIndex, endIndex, n) << endl; return 0; }
linear
logn
// C++ program to find sum of given array of // string type in integer form #include <bits/stdc++.h> using namespace std; // Function to find the sum of given array int calculateSum(string arr[], int n) { // if string is empty if (n == 0) return 0; string s = arr[0]; // stoi function to convert // string into integer int value = stoi(s); int sum = value; for (int i = 2; i < n; i = i + 2) { s = arr[i]; // stoi function to convert // string into integer int value = stoi(s); // Find operator char operation = arr[i - 1][0]; // If operator is equal to '+', // add value in sum variable // else subtract if (operation == '+') sum += value; else sum -= value; } return sum; } // Driver Function int main() { string arr[] = { "3", "+", "4", "-", "7", "+", "13" }; int n = sizeof(arr) / sizeof(arr[0]); cout << calculateSum(arr, n); return 0; }
constant
linear
// C++ implementation to print the bracket number #include <bits/stdc++.h> using namespace std; // function to print the bracket number void printBracketNumber(string exp, int n) { // used to print the bracket number // for the left bracket int left_bnum = 1; // used to obtain the bracket number // for the right bracket stack<int> right_bnum; // traverse the given expression 'exp' for (int i = 0; i < n; i++) { // if current character is a left bracket if (exp[i] == '(') { // print 'left_bnum', cout << left_bnum << " "; // push 'left_bnum' on to the stack 'right_bnum' right_bnum.push(left_bnum); // increment 'left_bnum' by 1 left_bnum++; } // else if current character is a right bracket else if(exp[i] == ')') { // print the top element of stack 'right_bnum' // it will be the right bracket number cout << right_bnum.top() << " "; // pop the top element from the stack right_bnum.pop(); } } } // Driver program to test above int main() { string exp = "(a+(b*c))+(d/e)"; int n = exp.size(); printBracketNumber(exp, n); return 0; }
linear
linear
// CPP program to find index of closing // bracket for given opening bracket. #include <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 construct string from binary tree*/ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } // Function to construct string from binary tree void treeToString(Node* root, string& str) { // bases case if (root == NULL) return; // push the root data as character str.push_back(root->data + '0'); // if leaf node, then return if (!root->left && !root->right) return; // for left subtree str.push_back('('); treeToString(root->left, str); str.push_back(')'); // only if right child is present to // avoid extra parenthesis if (root->right) { str.push_back('('); treeToString(root->right, str); str.push_back(')'); } } // Driver Code int main() { /* Let us construct below tree 1 / \ 2 3 / \ \ 4 5 6 */ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(6); string str = ""; treeToString(root, str); cout << str; }
linear
linear
/* C++ program to construct a binary tree from the given string */ #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node */ Node* newNode(int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->left = node->right = NULL; return (node); } /* This function is here just to test */ void preOrder(Node* node) { if (node == NULL) return; printf("%d ", node->data); preOrder(node->left); preOrder(node->right); } // function to return the index of close parenthesis int findIndex(string str, int si, int ei) { if (si > ei) return -1; // Inbuilt stack stack<char> s; for (int i = si; i <= ei; i++) { // if open parenthesis, push it if (str[i] == '(') s.push(str[i]); // if close parenthesis else if (str[i] == ')') { if (s.top() == '(') { s.pop(); // if stack is empty, this is // the required index if (s.empty()) return i; } } } // if not found return -1 return -1; } // function to construct tree from string Node* treeFromString(string str, int si, int ei) { // Base case if (si > ei) return NULL; int num = 0; // In case the number is having more than 1 digit while(si <= ei && str[si] >= '0' && str[si] <= '9') { num *= 10; num += (str[si] - '0'); si++; } // new root Node* root = newNode(num); int index = -1; // if next char is '(' find the index of // its complement ')' if (si <= ei && str[si] == '(') index = findIndex(str, si, ei); // if index found if (index != -1) { // call for left subtree root->left = treeFromString(str, si + 1, index - 1); // call for right subtree root->right = treeFromString(str, index + 2, ei - 1); } return root; } // Driver Code int main() { string str = "4(2(3)(1))(6(5))"; Node* root = treeFromString(str, 0, str.length() - 1); preOrder(root); }
linear
quadratic
// Simple C++ program to convert all substrings from // decimal to given base. #include <bits/stdc++.h> using namespace std; int substringConversions(string str, int k, int b) { for (int i=0; i + k <= str.size(); i++) { // Saving substring in sub string sub = str.substr(i, k); // Evaluating decimal for current substring // and printing it. int sum = 0, counter = 0; for (int i = sub.size() - 1; i >= 0; i--) { sum = sum + ((sub.at(i) - '0') * pow(b, counter)); counter++; } cout << sum << " "; } } // Driver code int main() { string str = "12212"; int b = 3, k = 3; substringConversions(str, b, k); return 0; }
linear
quadratic
// Efficient C++ program to convert all substrings from // decimal to given base. #include <bits/stdc++.h> using namespace std; int substringConversions(string str, int k, int b) { int i = 0, sum = 0, counter = k-1; // Computing the decimal of first window for (i; i < k; i++) { sum = sum + ((str.at(i) - '0') * pow(b, counter)); counter--; } cout << sum << " "; // prev stores the previous decimal int prev = sum; // Computing decimal equivalents of all other windows sum = 0, counter = 0; for (i; i < str.size(); i++) { // Subtracting weight of the element pushed out of window sum = prev - ((str.at(i - k) - '0') * pow(b, k-1)); // Multiplying the decimal by base to formulate other window sum = sum * b; // Adding the new element of window to sum sum = sum + (str.at(i) - '0'); // Decimal of current window cout << sum << " "; // Updating prev prev = sum; counter++; } } // Driver code int main() { string str = "12212"; int b = 3, k = 3; substringConversions(str, b, k); return 0; }
linear
linear
// C++ program to demonstrate above steps of // binary fractional to decimal conversion #include<bits/stdc++.h> using namespace std; // Function to convert binary fractional to // decimal double binaryToDecimal(string binary, int len) { // Fetch the radix point size_t point = binary.find('.'); // Update point if not found if (point == string::npos) point = len; double intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for (int i = point-1; i>=0; --i) { // Subtract '0' to convert character // into integer intDecimal += (binary[i] - '0') * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for (int i = point+1; i < len; ++i) { fracDecimal += (binary[i] - '0') / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal; } // Driver code int main() { string n = "110.101"; cout << binaryToDecimal(n, n.length()) << "\n"; n = "101.1101"; cout << binaryToDecimal(n, n.length()); return 0; }
linear
linear
// C++ program to convert fractional decimal // to binary number #include<bits/stdc++.h> using namespace std; // Function to convert decimal to binary upto // k-precision after decimal point string decimalToBinary(double num, int k_prec) { string binary = ""; // Fetch the integral part of decimal number int Integral = num; // Fetch the fractional part decimal number double fractional = num - Integral; // Conversion of integral part to // binary equivalent while (Integral) { int rem = Integral % 2; // Append 0 in binary binary.push_back(rem +'0'); Integral /= 2; } // Reverse string to get original binary // equivalent reverse(binary.begin(),binary.end()); // Append point before conversion of // fractional part binary.push_back('.'); // Conversion of fractional part to // binary equivalent while (k_prec--) { // Find next bit in fraction fractional *= 2; int fract_bit = fractional; if (fract_bit == 1) { fractional -= fract_bit; binary.push_back(1 + '0'); } else binary.push_back(0 + '0'); } return binary; } // Driver code int main() { double n = 4.47; int k = 3; cout << decimalToBinary(n, k) << "\n"; n = 6.986 , k = 5; cout << decimalToBinary(n, k); return 0; }
linear
linear
// C++ implementation to convert a // sentence into its equivalent // mobile numeric keypad sequence #include <bits/stdc++.h> using namespace std; // Function which computes the sequence string printSequence(string arr[], string input) { string output = ""; // length of input string int n = input.length(); for (int i = 0; i < n; i++) { // Checking for space if (input[i] == ' ') output = output + "0"; else { // Calculating index for each // character int position = input[i] - 'A'; output = output + arr[position]; } } // Output sequence return output; } // Driver Code int main() { // storing the sequence in array string str[] = { "2", "22", "222", "3", "33", "333", "4", "44", "444", "5", "55", "555", "6", "66", "666", "7", "77", "777", "7777", "8", "88", "888", "9", "99", "999", "9999" }; string input = "GEEKSFORGEEKS"; cout << printSequence(str, input); return 0; }
linear
linear
// C++ Program for above implementation #include <bits/stdc++.h> using namespace std; // Function to check is it possible to convert // first string into another string or not. bool isItPossible(string str1, string str2, int m, int n) { // To Check Length of Both String is Equal or Not if (m != n) return false; // To Check Frequency of A's and B's are // equal in both strings or not. if (count(str1.begin(), str1.end(), 'A') != count(str2.begin(), str2.end(), 'A') || count(str1.begin(), str1.end(), 'B') != count(str2.begin(), str2.end(), 'B')) return false; // Start traversing for (int i = 0; i < m; i++) { if (str1[i] != '#') { for (int j = 0; j < n; j++) { // To Check no two elements cross each other. if ((str2[j] != str1[i]) && str2[j] != '#') return false; if (str2[j] == str1[i]) { str2[j] = '#'; // To Check Is it Possible to Move // towards Left or not. if (str1[i] == 'A' && i < j) return false; // To Check Is it Possible to Move // towards Right or not. if (str1[i] == 'B' && i > j) return false; break; } } } } return true; } // Drivers code int main() { string str1 = "A#B#"; string str2 = "A##B"; int m = str1.length(); int n = str2.length(); isItPossible(str1, str2, m, n) ? cout << "Yes\n" : cout << "No\n"; return 0; }
linear
quadratic
// CPP Program to convert str1 to str2 in // exactly k operations #include <bits/stdc++.h> using namespace std; // Returns true if it is possible to convert // str1 to str2 using k operations. bool isConvertible(string str1, string str2, int k) { // Case A (i) if ((str1.length() + str2.length()) < k) return true; // finding common length of both string int commonLength = 0; for (int i = 0; i < min(str1.length(), str2.length()); i++) { if (str1[i] == str2[i]) commonLength++; else break; } // Case A (ii)- if ((k - str1.length() - str2.length() + 2 * commonLength) % 2 == 0) return true; // Case B- return false; } // driver program int main() { string str1 = "geek", str2 = "geek"; int k = 7; if (isConvertible(str1, str2, k)) cout << "Yes"; else cout << "No"; str1 = "geeks", str2 = "geek"; k = 5; cout << endl; if (isConvertible(str1, str2, k)) cout << "Yes"; else cout << "No"; return 0; }
constant
linear
// C++ Program to convert decimal number to // roman numerals #include <bits/stdc++.h> using namespace std; // Function to convert decimal to Roman Numerals int printRoman(int number) { int num[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000}; string sym[] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"}; int i=12; while(number>0) { int div = number/num[i]; number = number%num[i]; while(div--) { cout<<sym[i]; } i--; } } //Driver program int main() { int number = 3549; printRoman(number); return 0; }
constant
linear
// C++ Program for above approach #include <bits/stdc++.h> using namespace std; // Function to calculate roman equivalent string intToRoman(int num) { // storing roman values of digits from 0-9 // when placed at different places string m[] = { "", "M", "MM", "MMM" }; string c[] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; string x[] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; string i[] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; // Converting to roman string thousands = m[num / 1000]; string hundreds = c[(num % 1000) / 100]; string tens = x[(num % 100) / 10]; string ones = i[num % 10]; string ans = thousands + hundreds + tens + ones; return ans; } // Driver program to test above function int main() { int number = 3549; cout << intToRoman(number); return 0; }
constant
linear
// cpp program to check if a string can // be converted to another string by // performing operations #include <bits/stdc++.h> using namespace std; // function to check if a string can be // converted to another string by // performing following operations bool check(string s1, string s2) { // calculates length int n = s1.length(); int m = s2.length(); bool dp[n + 1][m + 1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= m; j++) { dp[i][j] = false; } } // mark 1st position as true dp[0][0] = true; // traverse for all DPi, j for (int i = 0; i < s1.length(); i++) { for (int j = 0; j <= s2.length(); j++) { // if possible for to convert i // characters of s1 to j characters // of s2 if (dp[i][j]) { // if upper_case(s1[i])==s2[j] // is same if (j < s2.length() && (toupper(s1[i]) == s2[j])) dp[i + 1][j + 1] = true; // if not upper then deletion is // possible if (!isupper(s1[i])) dp[i + 1][j] = true; } } } return (dp[n][m]); } // driver code int main() { string s1 = "daBcd"; string s2 = "ABC"; if (check(s1, s2)) cout << "YES"; else cout << "NO"; return 0; }
quadratic
quadratic
// CPP code to transform string #include <bits/stdc++.h> using namespace std; // Function to change // character's case string change_case(string a) { int l = a.length(); for(int i = 0 ; i < l ; i++) { // If character is lowercase // change to uppercase if(a[i] >= 'a' && a[i] <= 'z') a[i] = a[i] - 32; // If character is uppercase // change to lowercase else if(a[i] >= 'A' && a[i] <= 'Z') a[i] = a[i] + 32; } return a; } // Function to delete vowels string delete_vowels(string a) { string temp = ""; int l = a.length(); for(int i = 0 ; i < l ; i++) { //If character is consonant if(a[i] != 'a' && a[i] != 'e' && a[i] != 'i' && a[i] != 'o' && a[i] != 'u' && a[i] != 'A' && a[i] != 'E' && a[i] != 'O' && a[i] != 'U'&& a[i] != 'I') temp += a[i]; } return temp; } // Function to insert "#" string insert_hash(string a) { string temp = ""; int l = a.length(); for(int i = 0 ; i < l ; i++) { // If character is not special if((a[i] >= 'a' && a[i] <= 'z') || (a[i] >= 'A' && a[i] <= 'Z')) temp = temp + '#' + a[i]; else temp = temp + a[i]; } return temp; } // Function to transform string void transformSting(string a) { string b = delete_vowels(a); string c = change_case(b); string d = insert_hash(c); //corner case // when all the words of string are vowel then string empty after deletion if(d=="") cout<<"-1"<<endl; else cout << d<<endl; } // Driver function int main() { string a = "SunshinE!!"; string b = "aeiou"; // Calling function transformSting(a); transformSting(b); return 0; }
linear
linear
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std; // A utility function to swap characters void swap ( char* a, char* b ) { char t = *a; *a = *b; *b = t; } // A utility function to reverse string str[low..high] void reverse ( char* str, int low, int high ) { while ( low < high ) { swap( &str[low], &str[high] ); ++low; --high; } } // Cycle leader algorithm to move all even // positioned elements at the end. void cycleLeader ( char* str, int shift, int len ) { int j; char item; for (int i = 1; i < len; i *= 3 ) { j = i; item = str[j + shift]; do { // odd index if ( j & 1 ) j = len / 2 + j / 2; // even index else j /= 2; // keep the back-up of element at new position swap (&str[j + shift], &item); } while ( j != i ); } } // The main function to transform a string. This function // mainly uses cycleLeader() to transform void moveNumberToSecondHalf( char* str ) { int k, lenFirst; int lenRemaining = strlen( str ); int shift = 0; while ( lenRemaining ) { k = 0; // Step 1: Find the largest prefix // subarray of the form 3^k + 1 while ( pow( 3, k ) + 1 <= lenRemaining ) k++; lenFirst = pow( 3, k - 1 ) + 1; lenRemaining -= lenFirst; // Step 2: Apply cycle leader algorithm // for the largest subarrau cycleLeader ( str, shift, lenFirst ); // Step 4.1: Reverse the second half of first subarray reverse ( str, shift / 2, shift - 1 ); // Step 4.2: Reverse the first half of second sub-string. reverse ( str, shift, shift + lenFirst / 2 - 1 ); // Step 4.3 Reverse the second half of first sub-string // and first half of second sub-string together reverse ( str, shift / 2, shift + lenFirst / 2 - 1 ); // Increase the length of first subarray shift += lenFirst; } } // Driver program to test above function int main() { char str[] = "a1b2c3d4e5f6g7"; moveNumberToSecondHalf( str ); cout<<str; return 0; } // This is code is contributed by rathbhupendra
constant
quadratic
// C++ program to count the distinct transformation // of one string to other. #include <bits/stdc++.h> using namespace std; int countTransformation(string a, string b) { int n = a.size(), m = b.size(); // If b = "" i.e., an empty string. There // is only one way to transform (remove all // characters) if (m == 0) return 1; int dp[m][n]; memset(dp, 0, sizeof(dp)); // Fill dp[][] in bottom up manner // Traverse all character of b[] for (int i = 0; i < m; i++) { // Traverse all characters of a[] for b[i] for (int j = i; j < n; j++) { // Filling the first row of the dp // matrix. if (i == 0) { if (j == 0) dp[i][j] = (a[j] == b[i]) ? 1 : 0; else if (a[j] == b[i]) dp[i][j] = dp[i][j - 1] + 1; else dp[i][j] = dp[i][j - 1]; } // Filling other rows. else { if (a[j] == b[i]) dp[i][j] = dp[i][j - 1] + dp[i - 1][j - 1]; else dp[i][j] = dp[i][j - 1]; } } } return dp[m - 1][n - 1]; } // Driver code int main() { string a = "abcccdf", b = "abccdf"; cout << countTransformation(a, b) << endl; return 0; }
quadratic
quadratic
// C++ program to convert a ternary expression to // a tree. #include<bits/stdc++.h> using namespace std; // tree structure struct Node { char data; Node *left, *right; }; // function create a new node Node *newNode(char Data) { Node *new_node = new Node; new_node->data = Data; new_node->left = new_node->right = NULL; return new_node; } // Function to convert Ternary Expression to a Binary // Tree. It return the root of tree // Notice that we pass index i by reference because we // want to skip the characters in the subtree Node *convertExpression(string str, int & i) { // store current character of expression_string // [ 'a' to 'z'] Node * root =newNode(str[i]); //If it was last character return //Base Case if(i==str.length()-1) return root; // Move ahead in str i++; //If the next character is '?'.Then there will be subtree for the current node if(str[i]=='?') { //skip the '?' i++; // construct the left subtree // Notice after the below recursive call i will point to ':' // just before the right child of current node since we pass i by reference root->left = convertExpression(str,i); //skip the ':' character i++; //construct the right subtree root->right = convertExpression(str,i); return root; } //If the next character is not '?' no subtree just return it else return root; } // function print tree void printTree( Node *root) { if (!root) return ; cout << root->data <<" "; printTree(root->left); printTree(root->right); } // Driver program to test above function int main() { string expression = "a?b?c:d:e"; int i=0; Node *root = convertExpression(expression, i); printTree(root) ; return 0; }
linear
linear
// C++ Program to convert prefix to Infix #include <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 prefix to postfix #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 '*': return true; } return false; } // Convert prefix to Postfix expression string preToPost(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 + op2 + pre_exp[i]; // Push string temp back to stack s.push(temp); } // if symbol is an operand else { // push the operand to the stack s.push(string(1, pre_exp[i])); } } // stack contains only the Postfix expression return s.top(); } // Driver Code int main() { string pre_exp = "*-A/BC-/AKL"; cout << "Postfix : " << preToPost(pre_exp); return 0; }
linear
linear
// CPP Program to convert postfix to prefix #include <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
// CPP program to find infix for // a given postfix. #include <bits/stdc++.h> using namespace std; bool isOperand(char x) { return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'); } // Get Infix for a given postfix // expression string getInfix(string exp) { stack<string> s; for (int i=0; exp[i]!='\0'; i++) { // Push operands if (isOperand(exp[i])) { string op(1, exp[i]); s.push(op); } // We assume that input is // a valid postfix and expect // an operator. else { string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); s.push("(" + op2 + exp[i] + op1 + ")"); } } // There must be a single element // in stack now which is the required // infix. return s.top(); } // Driver code int main() { string exp = "ab*c+"; cout << getInfix(exp); return 0; }
linear
linear
// C++ program for space optimized // solution of Word Wrap problem. #include <bits/stdc++.h> using namespace std; // Function to find space optimized // solution of Word Wrap problem. void solveWordWrap(int arr[], int n, int k) { int i, j; // Variable to store number of // characters in given line. int currlen; // Variable to store possible // minimum cost of line. int cost; // DP table in which dp[i] represents // cost of line starting with word // arr[i]. int dp[n]; // Array in which ans[i] store index // of last word in line starting with // word arr[i]. int ans[n]; // If only one word is present then // only one line is required. Cost // of last line is zero. Hence cost // of this line is zero. Ending point // is also n-1 as single word is // present. dp[n - 1] = 0; ans[n - 1] = n - 1; // Make each word first word of line // by iterating over each index in arr. for (i = n - 2; i >= 0; i--) { currlen = -1; dp[i] = INT_MAX; // Keep on adding words in current // line by iterating from starting // word upto last word in arr. for (j = i; j < n; j++) { // Update number of characters // in current line. arr[j] is // number of characters in // current word and 1 // represents space character // between two words. currlen += (arr[j] + 1); // If limit of characters // is violated then no more // words can be added to // current line. if (currlen > k) break; // If current word that is // added to line is last // word of arr then current // line is last line. Cost of // last line is 0. Else cost // is square of extra spaces // plus cost of putting line // breaks in rest of words // from j+1 to n-1. if (j == n - 1) cost = 0; else cost = (k - currlen) * (k - currlen) + dp[j + 1]; // Check if this arrangement gives // minimum cost for line starting // with word arr[i]. if (cost < dp[i]) { dp[i] = cost; ans[i] = j; } } } // Print starting index and ending index // of words present in each line. i = 0; while (i < n) { cout << i + 1 << " " << ans[i] + 1 << " "; i = ans[i] + 1; } } // Driver function int main() { int arr[] = { 3, 2, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int M = 6; solveWordWrap(arr, n, M); return 0; }
linear
quadratic
// C++ program to print minimum number that can be formed // from a given sequence of Is and Ds #include <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 print shortest possible path to // type all characters of given string using a remote #include <iostream> using namespace std; // Function to print shortest possible path to // type all characters of given string using a remote void printPath(string str) { int i = 0; // start from character 'A' present at position (0, 0) int curX = 0, curY = 0; while (i < str.length()) { // find coordinates of next character int nextX = (str[i] - 'A') / 5; int nextY = (str[i] - 'B' + 1) % 5; // Move Up if destination is above while (curX > nextX) { cout << "Move Up" << endl; curX--; } // Move Left if destination is to the left while (curY > nextY) { cout << "Move Left" << endl; curY--; } // Move down if destination is below while (curX < nextX) { cout << "Move Down" << endl; curX++; } // Move Right if destination is to the right while (curY < nextY) { cout << "Move Right" << endl; curY++; } // At this point, destination is reached cout << "Press OK" << endl; i++; } } // Driver code int main() { string str = "COZY"; printPath(str); return 0; }
constant
quadratic
// C++ program to find minimum number of points // in a given path #include <bits/stdc++.h> using namespace std; // method returns minimum number of points in given path int numberOfPointInPath(string path) { int N = path.length(); // Map to store last occurrence of direction map<char, int> dirMap; // variable to store count of points till now, // initializing from 1 to count first point int points = 1; // looping over all characters of path string for (int i = 0; i < N; i++) { // storing current direction in curDir // variable char curDir = path[i]; // marking current direction as visited dirMap[curDir] = 1; // if at current index, we found both 'L' // and 'R' or 'U' and 'D' then current // index must be a point if ((dirMap['L'] && dirMap['R']) || (dirMap['U'] && dirMap['D'])) { // clearing the map for next segment dirMap.clear(); // increasing point count points++; // revisiting current direction for next segment dirMap[curDir] = 1; } } // +1 to count the last point also return (points + 1); } // Driver code to test above methods int main() { string path = "LLUUULLDD"; cout << numberOfPointInPath(path) << endl; return 0; }
linear
nlogn
// CPP program to check whether second string // can be formed from first string #include <bits/stdc++.h> using namespace std; const int MAX = 256; bool canMakeStr2(string str1, string str2) { // Create a count array and count frequencies // characters in str1. int count[MAX] = {0}; for (int i = 0; i < str1.length(); i++) count[str1[i]]++; // Now traverse through str2 to check // if every character has enough counts for (int i = 0; i < str2.length(); i++) { if (count[str2[i]] == 0) return false; count[str2[i]]--; } return true; } // Driver Code int main() { string str1 = "geekforgeeks"; string str2 = "for"; if (canMakeStr2(str1, str2)) cout << "Yes"; else cout << "No"; return 0; }
constant
linear
// C++ code to find the reverse alphabetical // order from a given position #include <iostream> #include <string> using namespace std; // Function which take the given string // and the position from which the reversing shall // be done and returns the modified string string compute(string str, int n) { // Creating a string having reversed alphabetical order string reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba"; int l = str.length(); // The string up to the point specified in the question, // the string remains unchanged and from the point up to // the length of the string, we reverse the alphabetical // order for (int i = n; i < l; i++) str[i] = reverseAlphabet[str[i] - 'a']; return str; } // Driver function int main() { string str = "pneumonia"; int n = 4; string answer = compute(str, n - 1); cout << answer; return 0; }
constant
linear
// CPP program to find last index of // character x in given string. #include <iostream> using namespace std; // Returns last index of x if it is present. // Else returns -1. int findLastIndex(string& str, char x) { int index = -1; for (int i = 0; i < str.length(); i++) if (str[i] == x) index = i; return index; } // Driver code int main() { // String in which char is to be found string str = "geeksforgeeks"; // char whose index is to be found char x = 'e'; int index = findLastIndex(str, x); if (index == -1) cout << "Character not found"; else cout << "Last index is " << index; return 0; }
constant
linear
// Simple CPP program to find last index of // character x in given string. #include <iostream> using namespace std; // Returns last index of x if it is present. // Else returns -1. int findLastIndex(string& str, char x) { // Traverse from right for (int i = str.length() - 1; i >= 0; i--) if (str[i] == x) return i; return -1; } // Driver code int main() { string str = "geeksforgeeks"; char x = 'e'; int index = findLastIndex(str, x); if (index == -1) cout << "Character not found"; else cout << "Last index is " << index; return 0; }
constant
linear