Category: lexicographic-ordering

Minimum adjacent swaps required to get Kth smallest number greater than given number

#include using namespace std;  void minSwapsKthLargest(string str, int k){        string res = str;              for (int i = 0; i < k; i++) {        next_permutation(            str.begin(), str.end());    }          int swap_count = 0;              for (int i = 0; i < res.length(); i++) {                  if (res[i] != str[i]) {            int start = i + 1;                          while (res[i] != str[start]) {                                  start++;            }            while (i != start) {                swap(str[start], str[start - 1]);                                                  start--;                swap_count++;            }        }    }          cout

Continue Reading

Lexicographically smallest binary string formed by flipping bits at indices not divisible K1 or K2 such that count of 1s is always greater than 0s from left

  #include using namespace std;  void generateString(int k1, int k2, string s){            int C1s = 0, C0s = 0;    int flag = 0;    vector pos;          for (int i = 0; i < s.length(); i++) {          if (s[i] == '0') {            C0s++;                                      if ((i + 1) % k1 != 0                && (i + 1) % k2 != 0) {                pos.push_back(i);            }        }          else {            C1s++;        }          if (C0s >= C1s) {                                                  if (pos.size() == […]

Continue Reading

Lexicographically smallest string with given string as prefix

Given an array arr[] consisting of N strings and a string S if size M, the task is to find the lexicographically smallest string consisting of the string S as the prefix. If there doesn’t exist any string starting with prefix S then print “-1”.Examples:Input: arr[] = {“apple”, “appe”, “apl”, “aapl”, “appax”}, S = “app”Output: […]

Continue Reading

Lexicographically largest subsequence containing all distinct characters only once

Given a string S, the task is to find the lexicographically largest subsequence that can be formed using all distinct characters only once from the given string.Examples:Input: S = ababcOutput: bacExplanation:All possible subsequences containing all the characters in S exactly once are {“abc”, “bac”}. The lexicograohically maximum among all the subsequences  is “bac”.Input: S = […]

Continue Reading

Sort a string lexicographically by reversing a substring

  #include using namespace std;  bool adjust(string& S, int& i,            int& start, int& end){        int N = S.length();              start = i – 1;              while (i < N && S[i] < S[i - 1]) {                  i++;    }              end = i - 1;          if (start = N)        return true;          if (start >= 1 && i = S[start – 1]                && S[start] = 1) {                  return S[end] >= S[start – 1];    }          if (i […]

Continue Reading