code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// CPP program to count number of substrings // of a string #include <bits/stdc++.h> using namespace std; int countNonEmptySubstr(string str) { int n = str.length(); return n*(n+1)/2; } // driver code int main() { string s = "abcde"; cout << countNonEmptySubstr(s); return 0; }
constant
constant
#include<bits/stdc++.h> using namespace std; int MAX_CHAR = 26; string encodeString(char str[], int m) { // hashEven stores the count of even indexed character // for each string hashOdd stores the count of odd // indexed characters for each string int hashEven[MAX_CHAR]; int hashOdd[MAX_CHAR]; memset(hashEven,0,sizeof(hashEven)); memset(hashOdd,0,sizeof(hashOdd)); // creating hash for each string for (int i = 0; i < m; i++) { char c = str[i]; if ((i & 1) != 0) // If index of current character is odd hashOdd[c-'a']++; else hashEven[c-'a']++; } // For every character from 'a' to 'z', we store its // count at even position followed by a separator, // followed by count at odd position. string encoding = ""; for (int i = 0; i < MAX_CHAR; i++) { encoding += (hashEven[i]); encoding += ('-'); encoding += (hashOdd[i]); encoding += ('-'); } return encoding; } // This function basically uses a hashing based set to // store strings which are distinct according // to criteria given in question. int countDistinct(string input[], int n) { int countDist = 0; // Initialize result // Create an empty set and store all distinct // strings in it. set<string> s; for (int i = 0; i < n; i++) { // If this encoding appears first time, increment // count of distinct encodings. char char_array[input[i].length()]; strcpy(char_array, input[i].c_str()); if (s.find(encodeString(char_array, input[i].length())) == s.end()) { s.insert(encodeString(char_array,input[i].length())); countDist++; } } return countDist; } int main() { string input[] = {"abcd", "acbd", "adcb", "cdba", "bcda", "badc"}; int n = sizeof(input)/sizeof(input[0]); cout << countDistinct(input, n) << "\n"; } // This code is contributed by Harshit Sharma.
constant
linear
// C++ program to find K'th character in // decrypted string #include<bits/stdc++.h> using namespace std; // Function to find K'th character in Encoded String char encodedChar(string str,int k) { // expand string variable is used to // store final string after decompressing string str string expand = ""; string temp; // Current substring int freq = 0; // Count of current substring for (int i=0; str[i]!='\0'; ) { temp = ""; // Current substring freq = 0; // count frequency of current substring // read characters until you find a number // or end of string while (str[i]>='a' && str[i]<='z') { // push character in temp temp.push_back(str[i]); i++; } // read number for how many times string temp // will be repeated in decompressed string while (str[i]>='1' && str[i]<='9') { // generating frequency of temp freq = freq*10 + str[i] - '0'; i++; } // now append string temp into expand // equal to its frequency for (int j=1; j<=freq; j++) expand.append(temp); } // this condition is to handle the case // when string str is ended with alphabets // not with numeric value if (freq==0) expand.append(temp); return expand[k-1]; } // Driver program to test the string int main() { string str = "ab4c12ed3"; int k = 21; cout << encodedChar(str, k) << endl; return 0; }
constant
linear
// C++ program to find number of characters at same // position as in English alphabets #include<bits/stdc++.h> using namespace std; int findCount(string str) { int result = 0; // Traverse input string for (int i = 0 ; i < str.size(); i++) // Check that index of characters of string is // same as of English alphabets by using ASCII // values and the fact that all lower case // alphabetic characters come together in same // order in ASCII table. And same is true for // upper case. if (i == (str[i] - 'a') || i == (str[i] - 'A')) result++; return result; } // Driver code int main() { string str = "AbgdeF"; cout << findCount(str); return 0; }
constant
linear
// C++ program to count words whose ith letter // is either (i-1)th, ith, or (i+1)th letter // of given word. #include<bits/stdc++.h> using namespace std; // Return the count of words. int countWords(char str[], int len) { int count = 1; // If word contain single letter, return 1. if (len == 1) return count; // Checking for first letter. if (str[0] == str[1]) count *= 1; else count *= 2; // Traversing the string and multiplying // for combinations. for (int j=1; j<len-1; j++) { // If all three letters are same. if (str[j] == str[j-1] && str[j] == str[j+1]) count *= 1; // If two letter are distinct. else if (str[j] == str[j-1] || str[j] == str[j+1] || str[j-1] == str[j+1]) count *= 2; // If all three letter are distinct. else count *= 3; } // Checking for last letter. if (str[len - 1] == str[len - 2]) count *= 1; else count *= 2; return count; } // Driven Program int main() { char str[] = "abc"; int len = strlen(str); cout << countWords(str, len) << endl; return 0; }
constant
linear
// CPP Program to find Smallest and // Largest Word in a String #include<iostream> #include<cstring> using namespace std; void minMaxLengthWords(string input, string &minWord, string &maxWord) { // minWord and maxWord are received by reference // and not by value // will be used to store and return output int len = input.length(); int si = 0, ei = 0; int min_length = len, min_start_index = 0, max_length = 0, max_start_index = 0; // Loop while input string is not empty while (ei <= len) { if (ei < len && input[ei] != ' ') ei++; else { // end of a word // find curr word length int curr_length = ei - si; if (curr_length < min_length) { min_length = curr_length; min_start_index = si; } if (curr_length > max_length) { max_length = curr_length; max_start_index = si; } ei++; si = ei; } } // store minimum and maximum length words minWord = input.substr(min_start_index, min_length); maxWord = input.substr(max_start_index, max_length); } // Driver code int main() { string a = "GeeksforGeeks A Computer Science portal for Geeks"; string minWord, maxWord; minMaxLengthWords(a, minWord, maxWord); // to take input in string use getline(cin, a); cout << "Minimum length word: " << minWord << endl << "Maximum length word: " << maxWord << endl; }
linear
linear
// Most efficient C++ program to count all // substrings with same first and last characters. #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // assuming lower case only int countSubstringWithEqualEnds(string s) { int result = 0; int n = s.length(); // Calculating frequency of each character // in the string. int count[MAX_CHAR] = {0}; for (int i=0; i<n; i++) count[s[i]-'a']++; // Computing result using counts for (int i=0; i<MAX_CHAR; i++) result += (count[i]*(count[i]+1)/2); return result; } // Driver function int main() { string s("abcab"); cout << countSubstringWithEqualEnds(s); return 0; }
constant
linear
// C++ code to count total distinct substrings // of a string #include <bits/stdc++.h> using namespace std; // Structure to store information of a suffix struct suffix { int index; // To store original index int rank[2]; // To store ranks and next // rank pair }; // A comparison function used by sort() to compare // two suffixes. Compares two pairs, returns 1 if // first pair is smaller int cmp(struct suffix a, struct suffix b) { return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0); } // This is the main function that takes a string // 'txt' of size n as an argument, builds and return // the suffix array for the given string vector<int> buildSuffixArray(string txt, int n) { // A structure to store suffixes and their indexes struct suffix suffixes[n]; // Store suffixes and their indexes in an array // of structures. The structure is needed to sort // the suffixes alphabetically and maintain their // old indexes while sorting for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank[0] = txt[i] - 'a'; suffixes[i].rank[1] = ((i+1) < n)? (txt[i + 1] - 'a'): -1; } // Sort the suffixes using the comparison function // defined above. sort(suffixes, suffixes+n, cmp); // At his point, all suffixes are sorted according // to first 2 characters. Let us sort suffixes // according to first 4 characters, then first // 8 and so on int ind[n]; // This array is needed to get the // index in suffixes[] from original // index. This mapping is needed to get // next suffix. for (int k = 4; k < 2*n; k = k*2) { // Assigning rank and index values to first suffix int rank = 0; int prev_rank = suffixes[0].rank[0]; suffixes[0].rank[0] = rank; ind[suffixes[0].index] = 0; // Assigning rank to suffixes for (int i = 1; i < n; i++) { // If first rank and next ranks are same as // that of previous suffix in array, assign // the same new rank to this suffix if (suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = rank; } else // Otherwise increment rank and assign { prev_rank = suffixes[i].rank[0]; suffixes[i].rank[0] = ++rank; } ind[suffixes[i].index] = i; } // Assign next rank to every suffix for (int i = 0; i < n; i++) { int nextindex = suffixes[i].index + k/2; suffixes[i].rank[1] = (nextindex < n)? suffixes[ind[nextindex]].rank[0]: -1; } // Sort the suffixes according to first k characters sort(suffixes, suffixes+n, cmp); } // Store indexes of all sorted suffixes in the suffix // array vector<int>suffixArr; for (int i = 0; i < n; i++) suffixArr.push_back(suffixes[i].index); // Return the suffix array return suffixArr; } /* To construct and return LCP */ vector<int> kasai(string txt, vector<int> suffixArr) { int n = suffixArr.size(); // To store LCP array vector<int> lcp(n, 0); // An auxiliary array to store inverse of suffix array // elements. For example if suffixArr[0] is 5, the // invSuff[5] would store 0. This is used to get next // suffix string from suffix array. vector<int> invSuff(n, 0); // Fill values in invSuff[] for (int i=0; i < n; i++) invSuff[suffixArr[i]] = i; // Initialize length of previous LCP int k = 0; // Process all suffixes one by one starting from // first suffix in txt[] for (int i=0; i<n; i++) { /* If the current suffix is at n-1, then we don’t have next substring to consider. So lcp is not defined for this substring, we put zero. */ if (invSuff[i] == n-1) { k = 0; continue; } /* j contains index of the next substring to be considered to compare with the present substring, i.e., next string in suffix array */ int j = suffixArr[invSuff[i]+1]; // Directly start matching from k'th index as // at-least k-1 characters will match while (i+k<n && j+k<n && txt[i+k]==txt[j+k]) k++; lcp[invSuff[i]] = k; // lcp for the present suffix. // Deleting the starting character from the string. if (k>0) k--; } // return the constructed lcp array return lcp; } // method to return count of total distinct substring int countDistinctSubstring(string txt) { int n = txt.length(); // calculating suffix array and lcp array vector<int> suffixArr = buildSuffixArray(txt, n); vector<int> lcp = kasai(txt, suffixArr); // n - suffixArr[i] will be the length of suffix // at ith position in suffix array initializing // count with length of first suffix of sorted // suffixes int result = n - suffixArr[0]; for (int i = 1; i < lcp.size(); i++) // subtract lcp from the length of suffix result += (n - suffixArr[i]) - lcp[i - 1]; result++; // For empty string return result; } // Driver code to test above methods int main() { string txt = "ababa"; cout << countDistinctSubstring(txt); return 0; }
linear
nlogn
// A C++ program to find the count of distinct substring // of a string using trie data structure #include <bits/stdc++.h> #define MAX_CHAR 26 using namespace std; // A Suffix Trie (A Trie of all suffixes) Node class SuffixTrieNode { public: SuffixTrieNode *children[MAX_CHAR]; SuffixTrieNode() // Constructor { // Initialize all child pointers as NULL for (int i = 0; i < MAX_CHAR; i++) children[i] = NULL; } // A recursive function to insert a suffix of the s // in subtree rooted with this node void insertSuffix(string suffix); }; // A Trie of all suffixes class SuffixTrie { SuffixTrieNode *root; int _countNodesInTrie(SuffixTrieNode *); public: // Constructor (Builds a trie of suffies of the given text) SuffixTrie(string s) { root = new SuffixTrieNode(); // Consider all suffixes of given string and insert // them into the Suffix Trie using recursive function // insertSuffix() in SuffixTrieNode class for (int i = 0; i < s.length(); i++) root->insertSuffix(s.substr(i)); } // method to count total nodes in suffix trie int countNodesInTrie() { return _countNodesInTrie(root); } }; // A recursive function to insert a suffix of the s in // subtree rooted with this node void SuffixTrieNode::insertSuffix(string s) { // If string has more characters if (s.length() > 0) { // Find the first character and convert it // into 0-25 range. char cIndex = s.at(0) - 'a'; // If there is no edge for this character, // add a new edge if (children[cIndex] == NULL) children[cIndex] = new SuffixTrieNode(); // Recur for next suffix children[cIndex]->insertSuffix(s.substr(1)); } } // A recursive function to count nodes in trie int SuffixTrie::_countNodesInTrie(SuffixTrieNode* node) { // If all characters of pattern have been processed, if (node == NULL) return 0; int count = 0; for (int i = 0; i < MAX_CHAR; i++) { // if children is not NULL then find count // of all nodes in this subtrie if (node->children[i] != NULL) count += _countNodesInTrie(node->children[i]); } // return count of nodes of subtrie and plus // 1 because of node's own count return (1 + count); } // Returns count of distinct substrings of str int countDistinctSubstring(string str) { // Construct a Trie of all suffixes SuffixTrie sTrie(str); // Return count of nodes in Trie of Suffixes return sTrie.countNodesInTrie(); } // Driver program to test above function int main() { string str = "ababa"; cout << "Count of distinct substrings is " << countDistinctSubstring(str); return 0; }
constant
linear
// C++ program to count number of possible strings // with n characters. #include<bits/stdc++.h> using namespace std; // Function to calculate number of strings int possibleStrings( int n, int r, int b, int g) { // Store factorial of numbers up to n // for further computation int fact[n+1]; fact[0] = 1; for (int i = 1; i <= n; i++) fact[i] = fact[i-1] * i; // Find the remaining values to be added int left = n - (r+g+b); int sum = 0; // Make all possible combinations // of R, B and G for the remaining value for (int i = 0; i <= left; i++) { for (int j = 0; j<= left-i; j++) { int k = left - (i+j); // Compute permutation of each combination // one by one and add them. sum = sum + fact[n] / (fact[i+r]*fact[j+b]*fact[k+g]); } } // Return total no. of strings/permutation return sum; } // Drivers code int main() { int n = 4, r = 2; int b = 0, g = 1; cout << possibleStrings(n, r, b, g); return 0; }
linear
quadratic
// C++ program to count number of strings // of n characters with #include<bits/stdc++.h> using namespace std; // n is total number of characters. // bCount and cCount are counts of 'b' // and 'c' respectively. int countStrUtil(int dp[][2][3], int n, int bCount=1, int cCount=2) { // Base cases if (bCount < 0 || cCount < 0) return 0; if (n == 0) return 1; if (bCount == 0 && cCount == 0) return 1; // if we had saw this combination previously if (dp[n][bCount][cCount] != -1) return dp[n][bCount][cCount]; // Three cases, we choose, a or b or c // In all three cases n decreases by 1. int res = countStrUtil(dp, n-1, bCount, cCount); res += countStrUtil(dp, n-1, bCount-1, cCount); res += countStrUtil(dp, n-1, bCount, cCount-1); return (dp[n][bCount][cCount] = res); } // A wrapper over countStrUtil() int countStr(int n) { int dp[n+1][2][3]; memset(dp, -1, sizeof(dp)); return countStrUtil(dp, n); } // Driver code int main() { int n = 3; // Total number of characters cout << countStr(n); return 0; }
linear
linear
// A O(1) CPP program to find number of strings // that can be made under given constraints. #include<bits/stdc++.h> using namespace std; int countStr(int n){ int count = 0; if(n>=1){ //aaa... count += 1; //b...aaa... count += n; //c...aaa... count += n; if(n>=2){ //bc...aaa... count += n*(n-1); //cc...aaa... count += n*(n-1)/2; if(n>=3){ //bcc...aaa... count += (n-2)*(n-1)*n/2; } } } return count; } // Driver code int main() { int n = 3; cout << countStr(n); return 0; }
constant
constant
// C++ program to find count of substring containing // exactly K ones #include <bits/stdc++.h> using namespace std; // method returns total number of substring having K ones int countOfSubstringWithKOnes(string s, int K) { int N = s.length(); int res = 0; int countOfOne = 0; int freq[N + 1] = {0}; // initialize index having zero sum as 1 freq[0] = 1; // loop over binary characters of string for (int i = 0; i < N; i++) { // update countOfOne variable with value // of ith character countOfOne += (s[i] - '0'); // if value reaches more than K, then // update result if (countOfOne >= K) { // add frequency of indices, having // sum (current sum - K), to the result res += freq[countOfOne - K]; } // update frequency of one's count freq[countOfOne]++; } return res; } // Driver code to test above methods int main() { string s = "10010"; int K = 1; cout << countOfSubstringWithKOnes(s, K) << endl; return 0; }
linear
linear
// C++ program to print all words that have // the same unique character set #include<bits/stdc++.h> using namespace std; #define MAX_CHAR 26 // Generates a key from given string. The key // contains all unique characters of given string in // sorted order consisting of only distinct elements. string getKey(string &str) { bool visited[MAX_CHAR] = { false }; // store all unique characters of current // word in key for (int j = 0; j < str.length(); j++) visited[str[j] - 'a'] = true ; string key = ""; for (int j=0; j < MAX_CHAR; j++) if (visited[j]) key = key + (char)('a'+j); return key; } // Print all words together with same character sets. void wordsWithSameCharSet(string words[], int n) { // Stores indexes of all words that have same // set of unique characters. unordered_map <string, vector <int> > Hash; // Traverse all words for (int i=0; i<n; i++) { string key = getKey(words[i]); Hash[key].push_back(i); } // print all words that have the same unique character set for (auto it = Hash.begin(); it!=Hash.end(); it++) { for (auto v=(*it).second.begin(); v!=(*it).second.end(); v++) cout << words[*v] << ", "; cout << endl; } } // Driver program to test above function int main() { string words[] = { "may", "student", "students", "dog", "studentssess", "god", "cat", "act", "tab", "bat", "flow", "wolf", "lambs", "amy", "yam", "balms", "looped", "poodle"}; int n = sizeof(words)/sizeof(words[0]); wordsWithSameCharSet(words, n); return 0; }
linear
linear
// C++ program to print common characters // of two Strings in alphabetical order #include<bits/stdc++.h> using namespace std; int main() { string s1 = "geeksforgeeks"; string s2 = "practiceforgeeks"; // to store the count of // letters in the first string int a1[26] = {0}; // to store the count of // letters in the second string int a2[26] = {0}; int i , j; char ch; char ch1 = 'a'; int k = (int)ch1, m; // for each letter present, increment the count for(i = 0 ; i < s1.length() ; i++) { a1[(int)s1[i] - k]++; } for(i = 0 ; i < s2.length() ; i++) { a2[(int)s2[i] - k]++; } for(i = 0 ; i < 26 ; i++) { // the if condition guarantees that // the element is common, that is, // a1[i] and a2[i] are both non zero // means that the letter has occurred // at least once in both the strings if (a1[i] != 0 and a2[i] != 0) { // print the letter for a number // of times that is the minimum // of its count in s1 and s2 for(j = 0 ; j < min(a1[i] , a2[i]) ; j++) { m = k + i; ch = (char)(k + i); cout << ch; } } } return 0; }
constant
linear
// CPP Program to find all the common characters // in n strings #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; void commonCharacters(string str[], int n) { // primary array for common characters // we assume all characters are seen before. bool prim[MAX_CHAR]; memset(prim, true, sizeof(prim)); // for each string for (int i = 0; i < n; i++) { // secondary array for common characters // Initially marked false bool sec[MAX_CHAR] = { false }; // for every character of ith string for (int j = 0; str[i][j]; j++) { // if character is present in all // strings before, mark it. if (prim[str[i][j] - 'a']) sec[str[i][j] - 'a'] = true; } // copy whole secondary array into primary memcpy(prim, sec, MAX_CHAR); } // displaying common characters for (int i = 0; i < 26; i++) if (prim[i]) printf("%c ", i + 'a'); } // Driver's Code int main() { string str[] = { "geeksforgeeks", "gemkstones", "acknowledges", "aguelikes" }; int n = sizeof(str)/sizeof(str[0]); commonCharacters(str, n); return 0; }
constant
linear
// C++ implementation to find the uncommon // characters of the two strings #include <bits/stdc++.h> using namespace std; // function to find the uncommon characters // of the two strings void findAndPrintUncommonChars(string str1, string str2) { // to store the answer string ans = ""; // to handle the case of duplicates vector<int> used(26, false); // check first for str1 for (int i = 0; i < str1.size(); i++) { // keeping a flag variable bool found = false; for (int j = 0; j < str2.size(); j++) { // if found change the flag // and break from loop if (str1[i] == str2[j]) { found = true; break; } } // if duplicate character not found // then add it to ans if (!found and !used[str1[i] - 'a']) { used[str1[i] - 'a'] = true; ans += str1[i]; } } // now check for str2 for (int i = 0; i < str2.size(); i++) { // keeping a flag variable bool found = false; for (int j = 0; j < str1.size(); j++) { // if found change the flag // and break from loop if (str2[i] == str1[j]) { found = true; break; } } // if duplicate character not found // then add it to ans if (!found and !used[str2[i] - 'a']) { used[str2[i] - 'a'] = true; ans += str2[i]; } } // to match with output sort(ans.begin(), ans.end()); // if not found any character if (ans.size() == 0) cout << "-1"; // else print the answer else cout << ans << " "; } // Driver program to test above int main() { string str1 = "characters"; string str2 = "alphabets"; findAndPrintUncommonChars(str1, str2); return 0; }
constant
quadratic
// C++ implementation to find the uncommon // characters of the two strings #include <bits/stdc++.h> using namespace std; // size of the hash table const int MAX_CHAR = 26; // function to find the uncommon characters // of the two strings void findAndPrintUncommonChars(string str1, string str2) { // mark presence of each character as 0 // in the hash table 'present[]' int present[MAX_CHAR]; for (int i=0; i<MAX_CHAR; i++) present[i] = 0; int l1 = str1.size(); int l2 = str2.size(); // for each character of str1, mark its // presence as 1 in 'present[]' for (int i=0; i<l1; i++) present[str1[i] - 'a'] = 1; // for each character of str2 for (int i=0; i<l2; i++) { // if a character of str2 is also present // in str1, then mark its presence as -1 if (present[str2[i] - 'a'] == 1 || present[str2[i] - 'a'] == -1) present[str2[i] - 'a'] = -1; // else mark its presence as 2 else present[str2[i] - 'a'] = 2; } // print all the uncommon characters for (int i=0; i<MAX_CHAR; i++) if (present[i] == 1 || present[i] == 2 ) cout << (char(i + 'a')) << " "; } // Driver program to test above int main() { string str1 = "characters"; string str2 = "alphabets"; findAndPrintUncommonChars(str1, str2); return 0; }
constant
linear
#include<bits/stdc++.h> using namespace std; string UncommonChars(string a, string b) { int mp1[26] = {0}, mp2[26] = {0}; int n = a.size(), m = b.size(); for(auto &x: a){ mp1[x-'a'] = 1; } for(auto &x: b){ mp2[x-'a'] = 1; } string chars = ""; for(int i = 0; i < 26; ++i){ if(mp1[i]^mp2[i]) chars+=char(i+'a'); } if(chars == "") return "-1"; else return chars; } int main(){ string a = "geeksforgeeks"; string b = "geeksquiz"; string result = UncommonChars(a,b); cout << result << endl; return 0; }
constant
linear
// C++ program Find concatenated string with // uncommon characters of given strings #include <bits/stdc++.h> using namespace std; string concatenatedString(string s1, string s2) { string res = ""; // result // store all characters of s2 in map unordered_map<char, int> m; for (int i = 0; i < s2.size(); i++) m[s2[i]] = 1; // Find characters of s1 that are not // present in s2 and append to result for (int i = 0; i < s1.size(); i++) { if (m.find(s1[i]) == m.end()) res += s1[i]; else m[s1[i]] = 2; } // Find characters of s2 that are not // present in s1. for (int i = 0; i < s2.size(); i++) if (m[s2[i]] == 1) res += s2[i]; return res; } /* Driver program to test above function */ int main() { string s1 = "abcs"; string s2 = "cxzca"; cout << concatenatedString(s1, s2); return 0; }
linear
linear
// C++ program to remove vowels from a String #include <bits/stdc++.h> using namespace std; string remVowel(string str) { vector<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; for (int i = 0; i < str.length(); i++) { if (find(vowels.begin(), vowels.end(), str[i]) != vowels.end()) { str = str.replace(i, 1, ""); i -= 1; } } return str; } // Driver Code int main() { string str = "GeeeksforGeeks - A Computer" " Science Portal for Geeks"; cout << remVowel(str) << endl; return 0; } // This code is contributed by // sanjeev2552 // and corrected by alreadytaken
constant
linear
// C++ program to remove vowels from a String #include <bits/stdc++.h> using namespace std; string remVowel(string str) { regex r("[aeiouAEIOU]"); return regex_replace(str, r, ""); } // Driver Code int main() { string str = "GeeeksforGeeks - A Computer Science Portal for Geeks"; cout << (remVowel(str)); return 0; } // This code is contributed by Arnab Kundu
constant
linear
// C++ program for printing sentence // without repetitive vowels #include <bits/stdc++.h> using namespace std; // function which returns True or False // for occurrence of a vowel bool is_vow(char c) { // this compares vowel with // character 'c' return (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u'); } // function to print resultant string void removeVowels(string str) { // print 1st character printf("%c", str[0]); // loop to check for each character for (int i = 1; str[i]; i++) // comparison of consecutive characters if ((!is_vow(str[i - 1])) || (!is_vow(str[i]))) printf("%c", str[i]); } // Driver Code int main() { char str[] = " geeks for geeks"; removeVowels(str); } // This code is contributed by Abhinav96
linear
linear
// C++ program to count vowels in a string #include<iostream> using namespace std; // Function to check the Vowel bool isVowel(char ch) { ch = toupper(ch); return (ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U'); } // Returns count of vowels in str int countVowels(string str) { int count = 0; for (int i=0; i<str.length(); i++) if (isVowel(str[i])) // Check for vowel ++count; return count; } // Main Calling Function int main() { //string object string str = "abc de"; // Total numbers of Vowel cout << countVowels(str) << endl; return 0; }
constant
linear
// Recursive C++ program to count the total // number of vowels using recursion #include<iostream> using namespace std; // Function to check the Vowel bool isVowel(char ch) { ch = toupper(ch); return (ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U'); } // to count total number of vowel from 0 to n int countVovels(string str, int n) { if (n == 1) return isVowel(str[n-1]); return countVovels(str, n-1) + isVowel(str[n-1]); } // Main Calling Function int main() { // string object string str = "abc de"; // Total numbers of Vowel cout << countVovels(str, str.length()) << endl; return 0; }
linear
linear
// Iterative CPP program to count total number // of consonants #include <iostream> using namespace std; // Function to check for consonant bool isConsonant(char ch) { // To handle lower case ch = toupper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90; } int totalConsonants(string str) { int count = 0; for (int i = 0; i < str.length(); i++) // To check is character is Consonant if (isConsonant(str[i])) ++count; return count; } // Driver code int main() { string str = "abc de"; cout << totalConsonants(str); return 0; }
constant
linear
// Recursive CPP program to count total number // of consonants #include <iostream> using namespace std; // Function to check for consonant bool isConsonant(char ch) { // To handle lower case ch = toupper(ch); return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90; } // to count total number of consonants from // 0 to n-1 int totalConsonants(string str, int n) { if (n == 1) return isConsonant(str[0]); return totalConsonants(str, n - 1) + isConsonant(str[n-1]); } // Driver code int main() { string str = "abc de"; cout << totalConsonants(str, str.length()); return 0; }
linear
linear
// C++ program to find number of distinct // permutations of a string. #include<bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // Utility function to find factorial of n. int factorial(int n) { int fact = 1; for (int i = 2; i <= n; i++) fact = fact * i; return fact; } // Returns count of distinct permutations // of str. int countDistinctPermutations(string str) { int length = str.length(); int freq[MAX_CHAR]; memset(freq, 0, sizeof(freq)); // finding frequency of all the lower case // alphabet and storing them in array of // integer for (int i = 0; i < length; i++) if (str[i] >= 'a') freq[str[i] - 'a']++; // finding factorial of number of appearances // and multiplying them since they are // repeating alphabets int fact = 1; for (int i = 0; i < MAX_CHAR; i++) fact = fact * factorial(freq[i]); // finding factorial of size of string and // dividing it by factorial found after // multiplying return factorial(length) / fact; } // Driver code int main() { string str = "fvvfhvgv"; printf("%d", countDistinctPermutations(str)); return 0; }
linear
linear
// C++ program to print all permutations with // duplicates allowed using rotate() in STL #include <bits/stdc++.h> using namespace std; // Function to print permutations of string str, // out is used to store permutations one by one void permute(string str, string out) { // When size of str becomes 0, out has a // permutation (length of out is n) if (str.size() == 0) { cout << out << endl; return; } // One be one move all characters at // the beginning of out (or result) for (int i = 0; i < str.size(); i++) { // Remove first character from str and // add it to out permute(str.substr(1), out + str[0]); // Rotate string in a way second character // moves to the beginning. rotate(str.begin(), str.begin() + 1, str.end()); } } // Driver code int main() { string str = "ABC"; permute(str, ""); return 0; }
linear
np
// C++ program to print all permutations with // duplicates allowed using next_permutation #include <bits/stdc++.h> using namespace std; // Function to print permutations of string str // using next_permutation void permute(string str) { // Sort the string in lexicographically // ascending order sort(str.begin(), str.end()); // Keep printing next permutation while there // is next permutation do { cout << str << endl; } while (next_permutation(str.begin(), str.end())); } // Driver code int main() { string str = "CBA"; permute(str); return 0; }
constant
np
// C++ program to check if it is // possible to split string or not #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // function to check if we can split // string or not bool checkCorrectOrNot(string s) { // Counter array initialized with 0 int count1[MAX_CHAR] = {0}; int count2[MAX_CHAR] = {0}; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i=0,j=n-1; i<j; i++,j--) { // First half count1[s[i]-'a']++; // Second half count2[s[j]-'a']++; } // Checking if values are different // set flag to 1 for (int i = 0; i<MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true; } // Driver program to test above function int main() { // String to be checked string s = "abab"; if (checkCorrectOrNot(s)) cout << "Yes\n"; else cout << "No\n"; return 0; }
constant
linear
// C++ program to check if it is // possible to split string or not #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // function to check if we can split // string or not bool checkCorrectOrNot(string s) { // Counter array initialized with 0 int count[MAX_CHAR] = {0}; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i=0,j=n-1; i<j; i++,j--) { // First half count[s[i]-'a']++; // Second half count[s[j]-'a']--; } // Checking if values are different // set flag to 1 for (int i = 0; i<MAX_CHAR; i++) if (count[i] != 0) return false; return true; } // Driver program to test above function int main() { // String to be checked string s = "abab"; if (checkCorrectOrNot(s)) cout << "Yes\n"; else cout << "No\n"; return 0; }
constant
linear
// C++ implementation to find the character in // first string that is present at minimum index // in second string #include <bits/stdc++.h> using namespace std; // function to find the minimum index character void printMinIndexChar(string str, string patt) { // to store the index of character having // minimum index int minIndex = INT_MAX; // lengths of the two strings int m = str.size(); int n = patt.size(); // traverse 'patt' for (int i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (int j = 0; j < m; j++) { // if patt[i] is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt[i] == str[j] && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != INT_MAX) cout << "Minimum Index Character = " << str[minIndex]; // if no character of 'patt' is present in 'str' else cout << "No character present"; } // Driver program to test above int main() { string str = "geeksforgeeks"; string patt = "set"; printMinIndexChar(str, patt); return 0; }
constant
quadratic
// C++ implementation to find the character in first // string that is present at minimum index in second // string #include <bits/stdc++.h> using namespace std; // function to find the minimum index character void printMinIndexChar(string str, string patt) { // unordered_map 'um' implemented as hash table unordered_map<char, int> um; // to store the index of character having // minimum index int minIndex = INT_MAX; // lengths of the two strings int m = str.size(); int n = patt.size(); // store the first index of each character of 'str' for (int i = 0; i < m; i++) { if (um.find(str[i]) == um.end()) um[str[i]] = i; } // traverse the string 'patt' for (int j = 0; j < n; j++) { // if patt[i] is found in 'um', check if // it has the minimum index or not accordingly // update 'minIndex' if (um.find(patt[j]) != um.end() && um[patt[j]] < minIndex) minIndex = um[patt[j]]; } // print the minimum index character if (minIndex != INT_MAX) cout << "Minimum Index Character = " << str[minIndex]; // if no character of 'patt' is present in 'str' else cout << "No character present"; } // Driver program to test above int main() { string str = "geeksforgeeks"; string patt = "set"; printMinIndexChar(str, patt); return 0; }
linear
linear
// C++ implementation of program to find the maximum length // that can be removed #include<bits/stdc++.h> using namespace std; // Function to find the length of longest sub-string that // can me make removed // arr --> pair type of array whose first field store // character in string and second field stores // corresponding index of that character int longestNull(string str) { vector<pair<char,int> > arr; // store {'@',-1} in arr , here this value will // work as base index arr.push_back({'@', -1}); int maxlen = 0; // Initialize result // one by one iterate characters of string for (int i = 0; i < str.length(); ++i) { // make pair of char and index , then store // them into arr arr.push_back({str[i], i}); // now if last three elements of arr[] are making // sub-string "100" or not while (arr.size()>=3 && arr[arr.size()-3].first=='1' && arr[arr.size()-2].first=='0' && arr[arr.size()-1].first=='0') { // if above condition is true then delete // sub-string "100" from arr[] arr.pop_back(); arr.pop_back(); arr.pop_back(); } // index of current last element in arr[] int tmp = arr.back().second; // This is important, here 'i' is the index of // current character inserted into arr[] // and 'tmp' is the index of last element in arr[] // after continuous deletion of sub-string // "100" from arr[] till we make it null, difference // of these to 'i-tmp' gives the length of current // sub-string that can be make null by continuous // deletion of sub-string "100" maxlen = max(maxlen, i - tmp); } return maxlen; } // Driver program to run the case int main() { cout << longestNull("1011100000100"); return 0; }
linear
linear
// CPP program to count the number of pairs #include <bits/stdc++.h> using namespace std; #define MAX 256 // Function to count the number of equal pairs int countPairs(string s) { // Hash table int cnt[MAX] = { 0 }; // Traverse the string and count occurrence for (int i = 0; i < s.length(); i++) cnt[s[i]]++; // Stores the answer int ans = 0; // Traverse and check the occurrence of every character for (int i = 0; i < MAX; i++) ans += cnt[i] * cnt[i]; return ans; } // Driver Code int main() { string s = "geeksforgeeks"; cout << countPairs(s); return 0; }
linear
linear
// CPP Program to count strings with adjacent // characters. #include <bits/stdc++.h> using namespace std; int countStrs(int n) { long int dp[n + 1][27]; // Initializing arr[n+1][27] to 0 memset(dp, 0, sizeof(dp)); // Initialing 1st row all 1 from 0 to 25 for (int i = 0; i <= 25; i++) dp[1][i] = 1; // Begin evaluating from i=2 since 1st row is set for (int i = 2; i <= n; i++) { for (int j = 0; j <= 25; j++) // j=0 is 'A' which can make strings // of length i using strings of length // i-1 and starting with 'B' if (j == 0) dp[i][j] = dp[i - 1][j + 1]; else dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j + 1]); } // Our result is sum of last row. long int sum = 0; for (int i = 0; i <= 25; i++) sum = (sum + dp[n][i]); return sum; } // Driver's Code int main() { int n = 3; cout << "Total strings are : " << countStrs(n); return 0; }
linear
linear
// C++ program to print Number of Words, // Vowels and Frequency of Each Character #include <bits/stdc++.h> using namespace std; void words(string str) { int wcount = 0, ucount = 0, vcount = 0; for (int i = 0; i < str.length(); i++) { char c = str[i]; switch (c) { case ' ': case '.': wcount++; // more delimiters can be given } switch (c) { case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': vcount++; } if (c >= 65 and c <= 90) ucount++; } cout << "Number of words = " << wcount << endl; cout << "Number of vowels = " << vcount << endl; cout << "Number of upper case characters = " << ucount << endl; } // Function to calculate the frequency // of each character in the string void frequency(string str) { // Creates an empty TreeMap map<char, int> hmap; // Traverse through the given array for (int i = 0; i < str.length(); i++) hmap[str[i]]++; // Print result for (auto i : hmap) { cout << "Character = " << i.first; cout << " Frequency = " << i.second << endl; } } // Driver Code int main(int argc, char const *argv[]) { string str = "Geeks for Geeks."; words(str); frequency(str); return 0; } // This code is contributed by // sanjeev2552
constant
linear
// C++ program to Find longest subsequence where // every character appears at-least k times #include<bits/stdc++.h> using namespace std; const int MAX_CHARS = 26; void longestSubseqWithK(string str, int k) { int n = str.size(); // Count frequencies of all characters int freq[MAX_CHARS] = {0}; for (int i = 0 ; i < n; i++) freq[str[i] - 'a']++; // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0 ; i < n ; i++) if (freq[str[i] - 'a'] >= k) cout << str[i]; } // Driver code int main() { string str = "geeksforgeeks"; int k = 2; longestSubseqWithK(str, k); return 0; }
linear
linear
// C++ program to Find longest subsequence where every // character appears at-least k times #include <bits/stdc++.h> using namespace std; void longestSubseqWithK(string str, int k) { int n = str.size(); map<char, int> mp; // Count frequencies of all characters for (int i = 0; i < n; i++) { char t = str[i]; mp[t]++; } // Traverse given string again and print // all those characters whose frequency // is more than or equal to k. for (int i = 0; i < n; i++) { char t = str[i]; if (mp[t] >= k) { cout << t; } } } // Driver code int main() { string str = "geeksforgeeks"; int k = 2; longestSubseqWithK(str, k); return 0; } // This code is contributed by rakeshsahni
linear
nlogn
// Recursive C++ program to check // if a string is subsequence // of another string #include <cstring> #include <iostream> using namespace std; // Returns true if str1[] is a // subsequence of str2[]. m is // length of str1 and n is length of str2 bool isSubSequence(char str1[], char str2[], int m, int n) { // Base Cases if (m == 0) return true; if (n == 0) return false; // If last characters of two // strings are matching if (str1[m - 1] == str2[n - 1]) return isSubSequence(str1, str2, m - 1, n - 1); // If last characters are // not matching return isSubSequence(str1, str2, m, n - 1); } // Driver program to check whether str1 is subsequence of str2 or not. int main() { char str1[] = "gksrek"; char str2[] = "geeksforgeeks"; int m = strlen(str1); int n = strlen(str2); isSubSequence(str1, str2, m, n) ? cout << "Yes " : cout << "No"; return 0; }
linear
linear
/*Iterative C++ program to check If a string is subsequence of another string*/ #include <bits/stdc++.h> using namespace std; /*Returns true if s1 is subsequence of s2*/ bool issubsequence(string& s1, string& s2) { int n = s1.length(), m = s2.length(); int i = 0, j = 0; while (i < n && j < m) { if (s1[i] == s2[j]) i++; j++; } /*If i reaches end of s1,that mean we found all characters of s1 in s2, so s1 is subsequence of s2, else not*/ return i == n; } int main() { string s1 = "gksrek"; string s2 = "geeksforgeeks"; if (issubsequence(s1, s2)) cout << "gksrek is subsequence of geekforgeeks" << endl; else cout << "gksrek is not a subsequence of geekforgeeks" << endl; return 0; }
constant
linear
// C++ program to count subsequences of the // form a^i b^j c^k #include <bits/stdc++.h> using namespace std; // Returns count of subsequences of the form // a^i b^j c^k int countSubsequences(string s) { // Initialize counts of different subsequences // caused by different combination of 'a' int aCount = 0; // Initialize counts of different subsequences // caused by different combination of 'a' and // different combination of 'b' int bCount = 0; // Initialize counts of different subsequences // caused by different combination of 'a', 'b' // and 'c'. int cCount = 0; // Traverse all characters of given string for (unsigned int i = 0; i < s.size(); i++) { /* If current character is 'a', then there are the following possibilities : a) Current character begins a new subsequence. b) Current character is part of aCount subsequences. c) Current character is not part of aCount subsequences. */ if (s[i] == 'a') aCount = (1 + 2 * aCount); /* If current character is 'b', then there are following possibilities : a) Current character begins a new subsequence of b's with aCount subsequences. b) Current character is part of bCount subsequences. c) Current character is not part of bCount subsequences. */ else if (s[i] == 'b') bCount = (aCount + 2 * bCount); /* If current character is 'c', then there are following possibilities : a) Current character begins a new subsequence of c's with bCount subsequences. b) Current character is part of cCount subsequences. c) Current character is not part of cCount subsequences. */ else if (s[i] == 'c') cCount = (bCount + 2 * cCount); } return cCount; } // Driver code int main() { string s = "abbc"; cout << countSubsequences(s) << endl; return 0; }
constant
linear
// C++ program to count subsequences of a // string divisible by n. #include<bits/stdc++.h> using namespace std; // Returns count of subsequences of str // divisible by n. int countDivisibleSubseq(string str, int n) { int len = str.length(); // division by n can leave only n remainder // [0..n-1]. dp[i][j] indicates number of // subsequences in string [0..i] which leaves // remainder j after division by n. int dp[len][n]; memset(dp, 0, sizeof(dp)); // Filling value for first digit in str dp[0][(str[0]-'0')%n]++; for (int i=1; i<len; i++) { // start a new subsequence with index i dp[i][(str[i]-'0')%n]++; for (int j=0; j<n; j++) { // exclude i'th character from all the // current subsequences of string [0...i-1] dp[i][j] += dp[i-1][j]; // include i'th character in all the current // subsequences of string [0...i-1] dp[i][(j*10 + (str[i]-'0'))%n] += dp[i-1][j]; } } return dp[len-1][0]; } // Driver code int main() { string str = "1234"; int n = 4; cout << countDivisibleSubseq(str, n); return 0; }
quadratic
quadratic
// CPP Program to find the "GFG" subsequence in // the given string #include <bits/stdc++.h> using namespace std; #define MAX 100 // Print the count of "GFG" subsequence in the string void countSubsequence(char s[], int n) { int cntG = 0, cntF = 0, result = 0, C=0; // Traversing the given string for (int i = 0; i < n; i++) { switch (s[i]) { // If the character is 'G', increment // the count of 'G', increase the result // and update the array. case 'G': cntG++; result+=C; break; // If the character is 'F', increment // the count of 'F' and update the array. case 'F': cntF++; C+=cntG; break; // Ignore other character. default: continue; } } cout << result << endl; } // Driven Program int main() { char s[] = "GFGFG"; int n = strlen(s); countSubsequence(s, n); return 0; }
constant
linear
// C++ program to print distinct // subsequences of a given string #include <bits/stdc++.h> using namespace std; // Create an empty set to store the subsequences unordered_set<string> sn; // Function for generating the subsequences void subsequences(char s[], char op[], int i, int j) { // Base Case if (s[i] == '\0') { op[j] = '\0'; // Insert each generated // subsequence into the set sn.insert(op); return; } // Recursive Case else { // When a particular character is taken op[j] = s[i]; subsequences(s, op, i + 1, j + 1); // When a particular character isn't taken subsequences(s, op, i + 1, j); return; } } // Driver Code int main() { char str[] = "ggg"; int m = sizeof(str) / sizeof(char); int n = pow(2, m) + 1; // Output array for storing // the generating subsequences // in each call char op[m+1]; //extra one for having \0 at the end // Function Call subsequences(str, op, 0, 0); // Output will be the number // of elements in the set cout << sn.size(); sn.clear(); return 0; // This code is contributed by Kishan Mishra }
linear
np
// C++ program to count number of distinct // subsequences of a given string. #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 256; // Returns count of distinct subsequences of str. int countSub(string str) { // Create an array to store index // of last vector<int> last(MAX_CHAR, -1); // Length of input string int n = str.length(); // dp[i] is going to store count of distinct // subsequences of length i. int dp[n + 1]; // Empty substring has only one subsequence dp[0] = 1; // Traverse through all lengths from 1 to n. for (int i = 1; i <= n; i++) { // Number of subsequences with substring // str[0..i-1] dp[i] = 2 * dp[i - 1]; // If current character has appeared // before, then remove all subsequences // ending with previous occurrence. if (last[str[i - 1]] != -1) dp[i] = dp[i] - dp[last[str[i - 1]]]; // Mark occurrence of current character last[str[i - 1]] = (i - 1); } return dp[n]; } // Driver code int main() { cout << countSub("gfg"); return 0; }
linear
linear
// C++ program for above approach #include <bits/stdc++.h> using namespace std; // Returns count of distinct // subsequences of str. int countSub(string s) { map<char, int> Map; // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { Map[s[i]] = -1; } int allCount = 0; int levelCount = 0; // Iterate from 0 to s.length() for(int i = 0; i < s.length(); i++) { char c = s[i]; // Check if i equal to 0 if (i == 0) { allCount = 1; Map = 1; levelCount = 1; continue; } // Replace levelCount with // allCount + 1 levelCount = allCount + 1; // If map is less than 0 if (Map < 0) { allCount = allCount + levelCount; } else { allCount = allCount + levelCount - Map; } Map = levelCount; } // Return answer return allCount; } // Driver code int main() { string list[] = { "abab", "gfg" }; for(string s : list) { int cnt = countSub(s); int withEmptyString = cnt + 1; cout << "With empty string count for " << s << " is " << withEmptyString << endl; cout << "Without empty string count for " << s << " is " << cnt << endl; } return 0; } // This code is contributed by divyeshrabadiya07
constant
linear
// C++ program to find LCS with permutations allowed #include<bits/stdc++.h> using namespace std; // Function to calculate longest string // str1 --> first string // str2 --> second string // count1[] --> hash array to calculate frequency // of characters in str1 // count[2] --> hash array to calculate frequency // of characters in str2 // result --> resultant longest string whose // permutations are sub-sequence of given two strings void longestString(string str1, string str2) { int count1[26] = {0}, count2[26]= {0}; // calculate frequency of characters for (int i=0; i<str1.length(); i++) count1[str1[i]-'a']++; for (int i=0; i<str2.length(); i++) count2[str2[i]-'a']++; // Now traverse hash array string result; for (int i=0; i<26; i++) // append character ('a'+i) in resultant // string 'result' by min(count1[i],count2i]) // times for (int j=1; j<=min(count1[i],count2[i]); j++) result.push_back('a' + i); cout << result; } // Driver program to run the case int main() { string str1 = "geeks", str2 = "cake"; longestString(str1, str2); return 0; }
constant
linear
// A dynamic programming based C++ program // to find shortest uncommon subsequence. #include<bits/stdc++.h> using namespace std; #define MAX 1005 // Returns length of shortest common subsequence int shortestSeq(char *S, char *T) { int m = strlen(S), n = strlen(T); // declaring 2D array of m + 1 rows and // n + 1 columns dynamically int dp[m+1][n+1]; // T string is empty for (int i = 0; i <= m; i++) dp[i][0] = 1; // S string is empty for (int i = 0; i <= n; i++) dp[0][i] = MAX; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { char ch = S[i-1]; int k; for (k = j-1; k >= 0; k--) if (T[k] == ch) break; // char not present in T if (k == -1) dp[i][j] = 1; else dp[i][j] = min(dp[i-1][j], dp[i-1][k] + 1); } } int ans = dp[m][n]; if (ans >= MAX) ans = -1; return ans; } // Driver program to test the above function int main() { char S[] = "babab"; char T[] = "babba"; int m = strlen(S), n = strlen(T); cout << "Length of shortest subsequence is : " << shortestSeq(S, T) << endl; }
quadratic
cubic
// C++ program to sort a string according to the // order defined by a pattern string #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // Sort str according to the order defined by pattern. void sortByPattern(string& str, string pat) { // Create a count array store count of characters in str. int count[MAX_CHAR] = { 0 }; // Count number of occurrences of each character // in str. for (int i = 0; i < str.length(); i++) count[str[i] - 'a']++; // Traverse the pattern and print every characters // same number of times as it appears in str. This // loop takes O(m + n) time where m is length of // pattern and n is length of str. int index = 0; for (int i = 0; i < pat.length(); i++) for (int j = 0; j < count[pat[i] - 'a']; j++) str[index++] = pat[i]; } // Driver code int main() { string pat = "bca"; string str = "abc"; sortByPattern(str, pat); cout << str; return 0; }
constant
linear
#include <bits/stdc++.h> using namespace std; // Declaring a vector globally that stores which character // is occurring first vector<int> position(26, -1); //Comparator function bool cmp(char& char1, char& char2) { return position[char1 - 'a'] < position[char2 - 'a']; } int main() { // Pattern string pat = "wcyuogmlrdfphitxjakqvzbnes"; for (int i = 0; i < pat.length(); i++) { if (position[pat[i] - 'a'] == -1) position[pat[i] - 'a'] = i; } // String to be sorted string str = "jcdokai"; // Passing a comparator to sort function sort(str.begin(), str.end(), cmp); cout << str; }
constant
nlogn
// C++ program to find largest word in Dictionary // by deleting some characters of given string #include <bits/stdc++.h> using namespace std; // Returns true if str1[] is a subsequence of str2[]. // m is length of str1 and n is length of str2 bool isSubSequence(string str1, string str2) { int m = str1.length(), n = str2.length(); int j = 0; // For index of str1 (or subsequence // Traverse str2 and str1, and compare current // character of str2 with first unmatched char // of str1, if matched then move ahead in str1 for (int i = 0; i < n && j < m; i++) if (str1[j] == str2[i]) j++; // If all characters of str1 were found in str2 return (j == m); } // Returns the longest string in dictionary which is a // subsequence of str. string findLongestString(vector<string> dict, string str) { string result = ""; int length = 0; // Traverse through all words of dictionary for (string word : dict) { // If current word is subsequence of str and is // largest such word so far. if (length < word.length() && isSubSequence(word, str)) { result = word; length = word.length(); } } // Return longest string return result; } // Driver program to test above function int main() { vector<string> dict = { "ale", "apple", "monkey", "plea" }; string str = "abpcplea"; cout << findLongestString(dict, str) << endl; return 0; }
constant
quadratic
// C++ program to check if a string is perfect // reversible or nor #include<bits/stdc++.h> using namespace std; // This function basically checks if string is // palindrome or not bool isReversible(string str) { int i = 0, j = str.length()-1; // iterate from left and right while (i < j) { if (str[i] != str[j]) return false; i++; j--; } return true; } // Driver program to run the case int main() { string str="aba"; if (isReversible(str)) cout << "YES"; else cout << "NO"; return 0; }
constant
linear
// C++ program to reverse an equation #include <bits/stdc++.h> using namespace std; // Function to reverse order of words string reverseEquation(string s) { // Resultant string string result; int j = 0; for (int i = 0; i < s.length(); i++) { // A space marks the end of the word if (s[i] == '+' || s[i] == '-' || s[i] == '/' || s[i] == '*') { // insert the word at the beginning // of the result string result.insert(result.begin(), s.begin() + j, s.begin() + i); j = i + 1; // insert the symbol result.insert(result.begin(), s[i]); } } // insert the last word in the string // to the result string result.insert(result.begin(), s.begin() + j, s.end()); return result; } // driver code int main() { string s = "a+b*c-d/e"; cout << reverseEquation(s) << endl; return 0; }
linear
linear
// C program for Left Rotation and Right // Rotation of a String #include<bits/stdc++.h> using namespace std; // In-place rotates s towards left by d void leftrotate(string &s, int d) { reverse(s.begin(), s.begin()+d); reverse(s.begin()+d, s.end()); reverse(s.begin(), s.end()); } // In-place rotates s towards right by d void rightrotate(string &s, int d) { leftrotate(s, s.length()-d); } // Driver code int main() { string str1 = "GeeksforGeeks"; leftrotate(str1, 2); cout << str1 << endl; string str2 = "GeeksforGeeks"; rightrotate(str2, 2); cout << str2 << endl; return 0; }
constant
linear
// C++ program for Left Rotation and Right // Rotation of a String #include <bits/stdc++.h> using namespace std; // Rotating the string using extended string string leftrotate(string str1, int n) { // creating extended string and index for new rotated // string string temp = str1 + str1; int l1 = str1.size(); string Lfirst = temp.substr(n, l1); // now returning string return Lfirst; } // Rotating the string using extended string string rightrotate(string str1, int n) { return leftrotate(str1, str1.size() - n); } // Driver code int main() { string str1 = leftrotate("GeeksforGeeks", 2); cout << str1 << endl; string str2 = rightrotate("GeeksforGeeks", 2); cout << str2 << endl; return 0; }
linear
linear
// A simple C++ program to generate all rotations // of a given string #include<bits/stdc++.h> using namespace std; // Print all the rotated string. void printRotatedString(char str[]) { int len = strlen(str); // Generate all rotations one by one and print char temp[len]; for (int i = 0; i < len; i++) { int j = i; // Current index in str int k = 0; // Current index in temp // Copying the second part from the point // of rotation. while (str[j] != '\0') { temp[k] = str[j]; k++; j++; } // Copying the first part from the point // of rotation. j = 0; while (j < i) { temp[k] = str[j]; j++; k++; } printf("%s\n", temp); } } // Driven Program int main() { char str[] = "geeks"; printRotatedString(str); return 0; }
linear
quadratic
// An efficient C++ program to print all // rotations of a string. #include<bits/stdc++.h> using namespace std; // Print all the rotated string. void printRotatedString(char str[]) { int n = strlen(str); // Concatenate str with itself char temp[2*n + 1]; strcpy(temp, str); strcat(temp, str); // Print all substrings of size n. // Note that size of temp is 2n for (int i = 0; i < n; i++) { for (int j=0; j != n; j++) printf("%c",temp[i + j]); printf("\n"); } } // Driven Program int main() { char str[] = "geeks"; printRotatedString(str); return 0; }
linear
quadratic
// C++ program to determine minimum number // of rotations required to yield same // string. #include <iostream> using namespace std; // Returns count of rotations to get the // same string back. int findRotations(string str) { // tmp is the concatenated string. string tmp = str + str; int n = str.length(); for (int i = 1; i <= n; i++) { // substring from i index of original // string size. string substring = tmp.substr(i, str.size()); // if substring matches with original string // then we will come out of the loop. if (str == substring) return i; } return n; } // Driver code int main() { string str = "abc"; cout << findRotations(str) << endl; return 0; }
linear
quadratic
// C++ program to determine minimum number // of rotations required to yield same // string. #include <iostream> using namespace std; // Returns count of rotations to get the // same string back. int findRotations(string str) { int ans = 0; //to store the answer int n = str.length(); //length of the string //All the length where we can partition for(int i=1;i<n-1;i++) { //right part + left part = rotated string // we are checking whether the rotated string is equal to //original string if(str.substr(i,n-i) + str.substr(0,i) == str) { ans = i; break; } } if(ans == 0) return n; return ans; } // Driver code int main() { string str = "abc"; cout << findRotations(str) << endl; return 0; }
constant
quadratic
// C++ program to determine minimum // number of rotations required to yield // same string. #include <iostream> using namespace std; // Driver program int main() { string String = "aaaa"; string check = ""; for(int r = 1; r < String.length() + 1; r++) { // checking the input after each rotation check = String.substr(0, r) + String.substr(r, String.length()-r); // following if statement checks if input is // equals to check , if yes it will print r and // break out of the loop if(check == String){ cout<<r; break; } } return 0; } // This code is contributed by shinjanpatra
linear
quadratic
// C++ program to check if // two strings are rotations // of each other #include<bits/stdc++.h> using namespace std; bool isRotation(string a, string b) { int n = a.length(); int m = b.length(); if (n != m) return false; // create lps[] that // will hold the longest // prefix suffix values // for pattern int lps[n]; // length of the previous // longest prefix suffix int len = 0; int i = 1; // lps[0] is always 0 lps[0] = 0; // the loop calculates // lps[i] for i = 1 to n-1 while (i < n) { if (a[i] == b[len]) { lps[i] = ++len; ++i; } else { if (len == 0) { lps[i] = 0; ++i; } else { len = lps[len - 1]; } } } i = 0; // Match from that rotating // point for (int k = lps[n - 1]; k < m; ++k) { if (b[k] != a[i++]) return false; } return true; } // Driver code int main() { string s1 = "ABACD"; string s2 = "CDABA"; cout << (isRotation(s1, s2) ? "1" : "0"); } // This code is contributed by Chitranayal
linear
linear
// C++ program to check if a string is two time // rotation of another string. #include<bits/stdc++.h> using namespace std; // Function to check if string2 is obtained by // string 1 bool isRotated(string str1, string str2) { if (str1.length() != str2.length()) return false; if(str1.length()<2){ return str1.compare(str2) == 0; } string clock_rot = ""; string anticlock_rot = ""; int len = str2.length(); // Initialize string as anti-clockwise rotation anticlock_rot = anticlock_rot + str2.substr(len-2, 2) + str2.substr(0, len-2) ; // Initialize string as clock wise rotation clock_rot = clock_rot + str2.substr(2) + str2.substr(0, 2) ; // check if any of them is equal to string1 return (str1.compare(clock_rot) == 0 || str1.compare(anticlock_rot) == 0); } // Driver code int main() { string str1 = "geeks"; string str2 = "eksge"; isRotated(str1, str2) ? cout << "Yes" : cout << "No"; return 0; }
linear
linear
// C++ program to count all rotation divisible // by 4. #include <bits/stdc++.h> using namespace std; // Returns count of all rotations divisible // by 4 int countRotations(string n) { int len = n.length(); // For single digit number if (len == 1) { int oneDigit = n.at(0)-'0'; if (oneDigit%4 == 0) return 1; return 0; } // At-least 2 digit number (considering all // pairs) int twoDigit, count = 0; for (int i=0; i<(len-1); i++) { twoDigit = (n.at(i)-'0')*10 + (n.at(i+1)-'0'); if (twoDigit%4 == 0) count++; } // Considering the number formed by the pair of // last digit and 1st digit twoDigit = (n.at(len-1)-'0')*10 + (n.at(0)-'0'); if (twoDigit%4 == 0) count++; return count; } //Driver program int main() { string n = "4834"; cout << "Rotations: " << countRotations(n) << endl; return 0; }
constant
linear
// C++ program to check if all rows of a matrix // are rotations of each other #include <bits/stdc++.h> using namespace std; const int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1] // are rotations of each other. bool isPermutedMatrix( int mat[MAX][MAX], int n) { // Creating a string that contains elements of first // row. string str_cat = ""; for (int i = 0 ; i < n ; i++) str_cat = str_cat + "-" + to_string(mat[0][i]); // Concatenating the string with itself so that // substring search operations can be performed on // this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i=1; i<n; i++) { // Store the matrix into vector in the form // of strings string curr_str = ""; for (int j = 0 ; j < n ; j++) curr_str = curr_str + "-" + to_string(mat[i][j]); // Check if the current string is present in // the concatenated string or not if (str_cat.find(curr_str) == string::npos) return false; } return true; } // Drivers code int main() { int n = 4 ; int mat[MAX][MAX] = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; isPermutedMatrix(mat, n)? cout << "Yes" : cout << "No"; return 0; }
linear
cubic
// C++ program to print reverse // of words in a string. #include <iostream> using namespace std; string wordReverse(string str) { int i = str.length() - 1; int start, end = i + 1; string result = ""; while (i >= 0) { if (str[i] == ' ') { start = i + 1; while (start != end) result += str[start++]; result += ' '; end = i; } i--; } start = 0; while (start != end) result += str[start++]; return result; } // Driver code int main() { string str = "I AM A GEEK"; cout << wordReverse(str); return 0; } // This code is contributed // by Imam
linear
linear
#include <algorithm> #include <iostream> #include <string> using namespace std; string reverse_words(string s) { int left = 0, i = 0, n = s.length(); while (s[i] == ' '){ i++; } left = i; while (i < n) { if (i + 1 == n || s[i] == ' ') { int j = i - 1; if (i + 1 == n) j++; reverse(s.begin()+left, s.begin()+j+1); left = i + 1; } if (left < n && s[left] == ' ' && i > left) left = i; i++; } // reversing the string reverse(s.begin(), s.end()); return s; } int main() { string str = "I AM A GEEK"; str = reverse_words(str); cout << str; return 0; // This code is contributed // by Gatea David }
constant
linear
// C++ program to reverse a string using stack #include <bits/stdc++.h> using namespace std; void recursiveReverse(string &str) { stack<char> st; for (int i=0; i<str.length(); i++) st.push(str[i]); for (int i=0; i<str.length(); i++) { str[i] = st.top(); st.pop(); } } // Driver program int main() { string str = "geeksforgeeks"; recursiveReverse(str); cout << str; return 0; }
linear
linear
// A Simple Iterative C++ program to reverse // a string #include <bits/stdc++.h> using namespace std; // Function to reverse a string void reverseStr(string& str) { int n = str.length(); // Swap character starting from two // corners for (int i = 0; i < n / 2; i++) swap(str[i], str[n - i - 1]); } // Driver program int main() { string str = "geeksforgeeks"; reverseStr(str); cout << str; return 0; }
constant
linear
// A Simple Iterative C++ program to reverse // a string #include <bits/stdc++.h> using namespace std; // Function to reverse a string void reverseStr(string& str) { int n = str.length(); // Swap character starting from two // corners for (int i=0, j=n-1; i<j; i++,j--) swap(str[i], str[j]); } // Driver program int main() { string str = "geeksforgeeks"; reverseStr(str); cout << str; return 0; }
constant
linear
// Recursive C++ program to reverse a string #include <bits/stdc++.h> using namespace std; void recursiveReverse(string &str, int i = 0) { int n = str.length(); if (i == n / 2) return; swap(str[i], str[n - i - 1]); recursiveReverse(str, i + 1); } // Driver program int main() { string str = "geeksforgeeks"; recursiveReverse(str); cout << str; return 0; }
linear
linear
// C++ program to reverse string using // reverse() method #include <bits/stdc++.h> using namespace std; int main() { // Given String string str = "geeksforgeeks"; // reverse function in C++ STL reverse(str.begin(), str.end()); // Printing the reversed string cout << str; return 0; } // contributed by akashish__
constant
linear
//C++ program to reverse string without //affecting it's special character #include<bits/stdc++.h> using namespace std; void reverse(string s){ //creating character array of size // equal to length of string char temp[s.length()]; int x=0; for (int i = 0; i < s.length(); i++) { if(s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i]<='Z'){ //storing elements in array temp[x]=s[i]; x++; } } //reversing the character array reverse(temp,temp+x); x=0; for (int i = 0; i < s.length(); i++) { if(s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i]<='Z'){ //updating the original string s[i]=temp[x]; x++; } } cout<<"reversed string is: "<<s; } //driver code int main() { string s="Ab,c,de!$"; //function call reverse(s); return 0; } //this code is contributed by Machhaliya Muhammad
linear
linear
// C++ program to reverse a string with special characters #include <bits/stdc++.h> using namespace std; // Returns true if x is an alphabetic character, false // otherwise bool isAlphabet(char x) { return ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')); } void reverse(char str[]) { // Initialize left and right pointers int r = strlen(str) - 1, l = 0; // Traverse string from both ends until 'l' and 'r' while (l < r) { // Ignore special characters if (!isAlphabet(str[l])) l++; else if (!isAlphabet(str[r])) r--; else // Both str[l] and str[r] are not special { swap(str[l], str[r]); l++; r--; } } } // Driver code int main() { char str[] = "a!!!b.c.d,e'f,ghi"; cout << "Input string: " << str << endl; reverse(str); cout << "Output string: " << str << endl; return 0; } // This code is contributed by Sania Kumari Gupta
constant
linear
// C++ program to reverse a string preserving // spaces. #include <iostream> using namespace std; // Function to reverse the string // and preserve the space position string reverses(string str) { // Mark spaces in result int n = str.size(); string result(n, '\0'); for (int i = 0; i < n; i++) if (str[i] == ' ') result[i] = ' '; // Traverse input string from beginning // and put characters in result from end int j = n - 1; for (int i = 0; i < str.length(); i++) { // Ignore spaces in input string if (str[i] != ' ') { // ignore spaces in result. while(result[j] == ' ') j--; result[j] = str[i]; j--; } } return result; } // Driver code int main() { string str = "internship at geeks for geeks"; cout << reverses(str) << endl; return 0; }
linear
linear
// C++ program to implement // the above approach #include <iostream> using namespace std; void preserveSpace(string &str) { int n = str.length(); // Initialize two pointers as two corners int start = 0; int end = n - 1; // Move both pointers toward each other while (start < end) { // If character at start or end is space, // ignore it if (str[start] == ' ') { start++; continue; } else if (str[end] == ' ') { end--; continue; } // If both are not spaces, do swap else { swap(str[start], str[end]); start++; end--; } } } // Driver code int main() { string str = "internship at geeks for geeks"; preserveSpace(str); cout << str; return 0; }
constant
linear
// C++ Program to reverse a string without // using temp variable #include <bits/stdc++.h> using namespace std; // Function to reverse string and return reversed string string reversingString(string str, int start, int end) { // Iterate loop upto start not equal to end while (start < end) { // XOR for swapping the variable str[start] ^= str[end]; str[end] ^= str[start]; str[start] ^= str[end]; ++start; --end; } return str; } // Driver Code int main() { string s = "GeeksforGeeks"; cout << reversingString(s, 0, 12); return 0; }
constant
linear
// Reversing a string using reverse() #include<bits/stdc++.h> using namespace std; int main() { string str = "geeksforgeeks"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0; }
constant
linear
// CPP Program for removing characters // from reversed string where vowels are // present in original string #include <bits/stdc++.h> using namespace std; // Function for replacing the string void replaceOriginal(string s, int n) { // initialize a string of length n string r(n, ' '); // Traverse through all characters of string for (int i = 0; i < n; i++) { // assign the value to string r // from last index of string s r[i] = s[n - 1 - i]; // if s[i] is a consonant then // print r[i] if (s[i] != 'a' && s[i] != 'e' && s[i] != 'i' && s[i] != 'o' && s[i] != 'u') { cout << r[i]; } } cout << endl; } // Driver function int main() { string s = "geeksforgeeks"; int n = s.length(); replaceOriginal(s, n); return 0; }
linear
linear
// C++ program to reverse order of vowels #include<bits/stdc++.h> using namespace std; // utility function to check for vowel bool isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } // Function to reverse order of vowels string reverseVowel(string str) { int j=0; // Storing the vowels separately string vowel; for (int i=0; str[i]!='\0'; i++) if (isVowel(str[i])) vowel[j++] = str[i]; // Placing the vowels in the reverse // order in the string for (int i=0; str[i]!='\0'; i++) if (isVowel(str[i])) str[i] = vowel[--j] ; return str; } // Driver function int main() { string str = "hello world"; cout << reverseVowel(str); return 0; }
linear
linear
// C++ program to reverse order of vowels #include<bits/stdc++.h> using namespace std; // utility function to check for vowel bool isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } // Function to reverse order of vowels string reverseVowel(string str) { // Start two indexes from two corners // and move toward each other int i = 0; int j = str.length()-1; while (i < j) { if (!isVowel(str[i])) { i++; continue; } if (!isVowel(str[j])) { j--; continue; } // swapping swap(str[i], str[j]); i++; j--; } return str; } // Driver function int main() { string str = "hello world"; cout << reverseVowel(str); return 0; }
constant
linear
// C++ program to reverse string // according to the number of words #include <bits/stdc++.h> using namespace std; // Reverse the letters of the word void reverse(char str[], int start, int end) { // Temporary variable to store character char temp; while (start <= end) { // Swapping the first and last character temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } // This function forms the required string void reverseletter(char str[], int start, int end) { int wstart, wend; for (wstart = wend = start; wend < end; wend++) { if (str[wend] == ' ') continue; // Checking the number of words // present in string to reverse while (str[wend] != ' ' && wend <= end) wend++; wend--; // Reverse the letter // of the words reverse(str, wstart, wend); } } // Driver Code int main() { char str[1000] = "Ashish Yadav Abhishek Rajput Sunil Pundir"; reverseletter(str, 0, strlen(str) - 1); cout << str; return 0; } // This code is contributed by SHUBHAMSINGH10
constant
linear
// C++ program to reverse each word // in a linked list #include <bits/stdc++.h> using namespace std; // Linked list Node structure struct Node { string c; struct Node* next; }; // Function to create newNode // in a linked list struct Node* newNode(string c) { Node* temp = new Node; temp->c = c; temp->next = NULL; return temp; }; // reverse each node data void reverse_word(string& str) { reverse(str.begin(), str.end()); } void reverse(struct Node* head) { struct Node* ptr = head; // iterate each node and call reverse_word // for each node data while (ptr != NULL) { reverse_word(ptr->c); ptr = ptr->next; } } // printing linked list void printList(struct Node* head) { while (head != NULL) { cout << head->c << " "; head = head->next; } } // Driver program int main() { Node* head = newNode("Geeksforgeeks"); head->next = newNode("a"); head->next->next = newNode("computer"); head->next->next->next = newNode("science"); head->next->next->next->next = newNode("portal"); head->next->next->next->next->next = newNode("for"); head->next->next->next->next->next->next = newNode("geeks"); cout << "List before reverse: \n"; printList(head); reverse(head); cout << "\n\nList after reverse: \n"; printList(head); return 0; }
constant
linear
// C++ code to check if cyclic order is possible among strings // under given constraints #include <bits/stdc++.h> using namespace std; #define M 26 // Utility method for a depth first search among vertices void dfs(vector<int> g[], int u, vector<bool> &visit) { visit[u] = true; for (int i = 0; i < g[u].size(); ++i) if(!visit[g[u][i]]) dfs(g, g[u][i], visit); } // Returns true if all vertices are strongly connected // i.e. can be made as loop bool isConnected(vector<int> g[], vector<bool> &mark, int s) { // Initialize all vertices as not visited vector<bool> visit(M, false); // perform a dfs from s dfs(g, s, visit); // now loop through all characters for (int i = 0; i < M; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visit[i]) return false; } // If we reach that means graph is connected return true; } // return true if an order among strings is possible bool possibleOrderAmongString(string arr[], int N) { // Create an empty graph vector<int> g[M]; // Initialize all vertices as not marked vector<bool> mark(M, false); // Initialize indegree and outdegree of every // vertex as 0. vector<int> in(M, 0), out(M, 0); // Process all strings one by one for (int i = 0; i < N; i++) { // Find first and last characters int f = arr[i].front() - 'a'; int l = arr[i].back() - 'a'; // Mark the characters mark[f] = mark[l] = true; // increase indegree and outdegree count in[l]++; out[f]++; // Add an edge in graph g[f].push_back(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for (int i = 0; i < M; i++) if (in[i] != out[i]) return false; return isConnected(g, mark, arr[0].front() - 'a'); } // Driver code to test above methods int main() { // string arr[] = {"abc", "efg", "cde", "ghi", "ija"}; string arr[] = {"ab", "bc", "cd", "de", "ed", "da"}; int N = sizeof(arr) / sizeof(arr[0]); if (possibleOrderAmongString(arr, N) == false) cout << "Ordering not possible\n"; else cout << "Ordering is possible\n"; return 0; }
linear
linear
// C++ program to sort an array of strings // using Trie #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; struct Trie { // index is set when node is a leaf // node, otherwise -1; int index; Trie* child[MAX_CHAR]; /*to make new trie*/ Trie() { for (int i = 0; i < MAX_CHAR; i++) child[i] = NULL; index = -1; } }; /* function to insert in trie */ void insert(Trie* root, string str, int index) { Trie* node = root; for (int i = 0; i < str.size(); i++) { /* taking ascii value to find index of child node */ char ind = str[i] - 'a'; /* making new path if not already */ if (!node->child[ind]) node->child[ind] = new Trie(); // go to next node node = node->child[ind]; } // Mark leaf (end of word) and store // index of word in arr[] node->index = index; } /* function for preorder traversal */ bool preorder(Trie* node, string arr[]) { if (node == NULL) return false; for (int i = 0; i < MAX_CHAR; i++) { if (node->child[i] != NULL) { /* if leaf node then print key*/ if (node->child[i]->index != -1) cout << arr[node->child[i]->index] << endl; preorder(node->child[i], arr); } } } void printSorted(string arr[], int n) { Trie* root = new Trie(); // insert all keys of dictionary into trie for (int i = 0; i < n; i++) insert(root, arr[i], i); // print keys in lexicographic order preorder(root, arr); } // Driver code int main() { string arr[] = { "abc", "xy", "bcd" }; int n = sizeof(arr) / sizeof(arr[0]); printSorted(arr, n); return 0; }
linear
linear
// C++ program to sort a string of characters #include<bits/stdc++.h> using namespace std; // function to print string in sorted order void sortString(string &str) { sort(str.begin(), str.end()); cout << str; } // Driver program to test above function int main() { string s = "geeksforgeeks"; sortString(s); return 0; }
constant
nlogn
// C++ program to sort a string of characters #include<bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // function to print string in sorted order void sortString(string &str) { // Hash array to keep count of characters. // Initially count of all characters is // initialized to zero. int charCount[MAX_CHAR] = {0}; // Traverse string and increment // count of characters for (int i=0; i<str.length(); i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i]-'a']++; // Traverse the hash array and print // characters for (int i=0;i<MAX_CHAR;i++) for (int j=0;j<charCount[i];j++) cout << (char)('a'+i); } // Driver program to test above function int main() { string s = "geeksforgeeks"; sortString(s); return 0; }
constant
linear
// CPP program to sort a string in descending // order using library function #include <bits/stdc++.h> using namespace std; void descOrder(string &s) { sort(s.begin(), s.end(), greater<char>()); } int main() { string s = "geeksforgeeks"; descOrder(s); // function call for(int i = 0; i < s.size(); i++) cout << s[i]; return 0; }
constant
constant
// C++ program to sort a string of characters // in descending order #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // function to print string in sorted order void sortString(string& str) { // Hash array to keep count of characters. // Initially count of all characters is // initialized to zero. int charCount[MAX_CHAR] = { 0 }; // Traverse string and increment // count of characters for (int i = 0; i < str.length(); i++) // 'a'-'a' will be 0, 'b'-'a' will be 1, // so for location of character in count // array we will do str[i]-'a'. charCount[str[i] - 'a']++; // Traverse the hash array and print // characters for (int i = MAX_CHAR - 1; i >= 0; i--) for (int j = 0; j < charCount[i]; j++) cout << (char)('a' + i); } // Driver program to test above function int main() { string s = "alkasingh"; sortString(s); return 0; }
constant
linear
// C++ implementation to print array of strings in sorted // order without copying one string into another #include <bits/stdc++.h> using namespace std; // function to print strings in sorted order void printInSortedOrder(string arr[], int n) { int index[n]; int i, j, min; // Initially the index of the strings // are assigned to the 'index[]' for (i=0; i<n; i++) index[i] = i; // selection sort technique is applied for (i=0; i<n-1; i++) { min = i; for (j=i+1; j<n; j++) { // with the help of 'index[]' // strings are being compared if (arr[index[min]].compare(arr[index[j]]) > 0) min = j; } // index of the smallest string is placed // at the ith index of 'index[]' if (min != i) { int temp = index[min]; index[min] = index[i]; index[i] = temp; } } // printing strings in sorted order for (i=0; i<n; i++) cout << arr[index[i]] << " "; } // Driver program to test above int main() { string arr[] = {"geeks", "quiz", "geeks", "for"}; int n = 4; printInSortedOrder(arr, n); return 0; }
linear
quadratic
// C++ implementation to sort the given string without // using any sorting technique #include <bits/stdc++.h> using namespace std; // function to sort the given string without // using any sorting technique string sortString(string str, int n) { // to store the final sorted string string new_str = ""; // for each character 'i' for (int i = 'a'; i <= 'z'; i++) // if character 'i' is present at a particular // index then add character 'i' to 'new_str' for (int j = 0; j < n; j++) if (str[j] == i) new_str += str[j]; // required final sorted string return new_str; } // Driver program to test above int main() { string str = "geeksforgeeks"; int n = str.size(); cout << sortString(str, n); return 0; }
constant
linear
// C++ implementation to sort the given // string without using any sorting technique #include <iostream> using namespace std; string sortString(string str, int n) { int i; //A character array to store the no.of occurrences of each character //between 'a' to 'z' char arr[26]={0}; //to store the final sorted string string new_str = ""; //To store each occurrence of character by relative indexing for (i = 0; i < n; i++) ++arr[str[i]-'a']; //To traverse the character array and append it to new_str for(i=0;i<26;i++) while(arr[i]--) new_str += i+'a'; return new_str; } // Driver program to test above int main() { string str = "geeksforgeeks"; int n = str.size(); cout << sortString(str, n); return 0; } // This code is contributed by Aravind Alapati
constant
linear
// C++ program for above implementation #include<bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // Function to return string in lexicographic // order followed by integers sum string arrangeString(string str) { int char_count[MAX_CHAR] = {0}; int sum = 0; // Traverse the string for (int i = 0; i < str.length(); i++) { // Count occurrence of uppercase alphabets if (str[i]>='A' && str[i] <='Z') char_count[str[i]-'A']++; //Store sum of integers else sum = sum + (str[i]-'0'); } string res = ""; // Traverse for all characters A to Z for (int i = 0; i < MAX_CHAR; i++) { char ch = (char)('A'+i); // Append the current character // in the string no. of times it // occurs in the given string while (char_count[i]--) res = res + ch; } // Append the sum of integers if (sum > 0) res = res + to_string(sum); // return resultant string return res; } // Driver program int main() { string str = "ACCBA10D2EW30"; cout << arrangeString(str); return 0; }
linear
linear
// C++ program to print all permutations // of a string in sorted order. #include <bits/stdc++.h> using namespace std; // Calculating factorial of a number int factorial(int n) { int f = 1; for (int i = 1; i <= n; i++) f = f * i; return f; } // Method to find total number of permutations int calculateTotal(string temp, int n) { int f = factorial(n); // Building Map to store frequencies of // all characters. map<char, int> hm; for (int i = 0; i < temp.length(); i++) { hm[temp[i]]++; } // Traversing map and // finding duplicate elements. for (auto e : hm) { int x = e.second; if (x > 1) { int temp5 = factorial(x); f /= temp5; } return f; } } static void nextPermutation(string &temp) { // Start traversing from the end and // find position 'i-1' of the first character // which is greater than its successor. int i; for (i = temp.length() - 1; i > 0; i--) if (temp[i] > temp[i - 1]) break; // Finding smallest character after 'i-1' and // greater than temp[i-1] int min = i; int j, x = temp[i - 1]; for (j = i + 1; j < temp.length(); j++) if ((temp[j] < temp[min]) and (temp[j] > x)) min = j; // Swapping the above found characters. swap(temp[i - 1], temp[min]); // Sort all digits from position next to 'i-1' // to end of the string. sort(temp.begin() + i, temp.end()); // Print the String cout << temp << endl; } void printAllPermutations(string s) { // Sorting String string temp(s); sort(temp.begin(), temp.end()); // Print first permutation cout << temp << endl; // Finding the total permutations int total = calculateTotal(temp, temp.length()); for (int i = 1; i < total; i++) { nextPermutation(temp); } } // Driver Code int main() { string s = "AAB"; printAllPermutations(s); } // This code is contributed by // sanjeev2552
linear
quadratic
// C++ program to get minimum cost to sort // strings by reversal operation #include <bits/stdc++.h> using namespace std; // Returns minimum cost for sorting arr[] // using reverse operation. This function // returns -1 if it is not possible to sort. int minCost(string arr[], int cost[], int N) { // dp[i][j] represents the minimum cost to // make first i strings sorted. // j = 1 means i'th string is reversed. // j = 0 means i'th string is not reversed. int dp[N][2]; // initializing dp array for first string dp[0][0] = 0; dp[0][1] = cost[0]; // getting array of reversed strings string revStr[N]; for (int i = 0; i < N; i++) { revStr[i] = arr[i]; reverse(revStr[i].begin(), revStr[i].end()); } string curStr; int curCost; // looping for all strings for (int i = 1; i < N; i++) { // Looping twice, once for string and once // for reversed string for (int j = 0; j < 2; j++) { dp[i][j] = INT_MAX; // getting current string and current // cost according to j curStr = (j == 0) ? arr[i] : revStr[i]; curCost = (j == 0) ? 0 : cost[i]; // Update dp value only if current string // is lexicographically larger if (curStr >= arr[i - 1]) dp[i][j] = min(dp[i][j], dp[i-1][0] + curCost); if (curStr >= revStr[i - 1]) dp[i][j] = min(dp[i][j], dp[i-1][1] + curCost); } } // getting minimum from both entries of last index int res = min(dp[N-1][0], dp[N-1][1]); return (res == INT_MAX)? -1 : res; } // Driver code to test above methods int main() { string arr[] = {"aa", "ba", "ac"}; int cost[] = {1, 3, 1}; int N = sizeof(arr) / sizeof(arr[0]); int res = minCost(arr, cost, N); if (res == -1) cout << "Sorting not possible\n"; else cout << "Minimum cost to sort strings is " << res; }
linear
linear
// CPP program to print all number containing // 1, 2 and 3 in any order. #include <bits/stdc++.h> using namespace std; // convert the number to string and find // if it contains 1, 2 & 3. bool findContainsOneTwoThree(int number) { string str = to_string(number); int countOnes = 0, countTwo = 0, countThree = 0; for (int i = 0; i < str.length(); i++) { if (str[i] == '1') countOnes++; else if (str[i] == '2') countTwo++; else if (str[i] == '3') countThree++; } return (countOnes && countTwo && countThree); } // prints all the number containing 1, 2, 3 string printNumbers(int numbers[], int n) { vector<int> oneTwoThree; for (int i = 0; i < n; i++) { // check if the number contains 1, // 2 & 3 in any order if (findContainsOneTwoThree(numbers[i])) oneTwoThree.push_back(numbers[i]); } // sort all the numbers sort(oneTwoThree.begin(), oneTwoThree.end()); string result = ""; for (auto number : oneTwoThree) { int value = number; if (result.length() > 0) result += ", "; result += to_string(value); } return (result.length() > 0) ? result : "-1"; } // Driver Code int main() { int numbers[] = { 123, 1232, 456, 234, 32145 }; int n = sizeof(numbers) / sizeof(numbers[0]); string result = printNumbers(numbers, n); cout << result; return 0; } // This code is contributed // by Sirjan13
linear
nlogn
// C++ program to implement binary search // in a sparse array. #include <bits/stdc++.h> using namespace std; /* Binary Search in an array with blanks */ int binarySearch(string *arr, int low, int high, string x) { if (low > high) return -1; int mid = (low + high) / 2; /*Modified Part*/ if (arr[mid] == "") { int left = mid - 1; int right = mid + 1; /*Search for both side for a non empty string*/ while (1) { /* No non-empty string on both sides */ if (left < low && right > high) return -1; if (left >= low && arr[left] != "") { mid = left; break; } else if (right <= high && arr[right] != "") { mid = right; break; } left--; right++; } } /* Normal Binary Search */ if (arr[mid] == x) return mid; else if (arr[mid] > x) return binarySearch(arr, low, mid - 1, x); else return binarySearch(arr, mid + 1, high, x); } int sparseSearch(string arr[], string x, int n) { return binarySearch(arr, 0, n - 1, x); } int main() { ios_base::sync_with_stdio(false); string arr[] = {"for", "geeks", "", "", "", "", "ide", "practice", "", "", "", "quiz"}; string x = "geeks"; int n = sizeof(arr) / sizeof(arr[0]); int index = sparseSearch(arr, x, n); if (index != -1) cout << x << " found at index " << index << "\n"; else cout << x << " not found\n"; return 0; }
logn
logn
// C++ program to toggle cases of a given // string. #include <iostream> #include <cstring> using namespace std; // function to toggle cases of a string void toggle(string& str) { int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (islower(c)) str[i] = toupper(c); else if (isupper(c)) str[i] = tolower(c); } } // Driver Code int main() { string str = "GeekS"; toggle(str); cout << str; return 0; }
constant
linear
// C++ program to convert a string from // lower to upper case. #include<stdio.h> const int x = 32; // Converts a string to uppercase char *toUpperCase(char *a) { for (int i=0; a[i]!='\0'; i++) a[i] = a[i] & ~x; return a; } // Driver Code int main() { char str[] = "SanjaYKannA"; //Here it's recommended to use character array //as it's stored in read-write area. //If a pointer is used it's stored //in read-only memory as a string literal. printf("%s", toUpperCase(str)); return 0; }
constant
linear