Category: binary-string

Maximum length of consecutive 1s or 0s after flipping at most K characters

#include using namespace std;  int maxLength(string str, int n,              char c, int k){        int ans = -1;          int cnt = 0;          int left = 0;      for (int right = 0; right < n; right++) {          if (str[right] == c) {            cnt++;        }                  while (cnt > k) {            if (str[left] == c) {                cnt–;            }                                      left++;        }                          ans = max(ans, right – left + 1);    }      return ans;}  int maxConsecutiveSegment(string S, int K){    int N = […]

Continue Reading

Minimize count of 0s in Binary String by changing K-size substring to 1s at most Q times

        const INT_MAX = 2147483647;                    const minZeroeCount = (S, K, Q) => {                let N = S.length;                        if (K == 0 || Q == 0) {            let cnt0 = 0;            for (let i = 0; i < N; ++i) {                if (S[i] == '0') cnt0++;            }            return cnt0;        }                        if (Q >= Math.ceil(N / K)) {            return 0;        }                                const dp = new Array(N + 1).fill(INT_MAX).map(() => new Array(Q […]

Continue Reading

Sum of the shortest distance between all 0s to 1 in given binary string

#include using namespace std;void findTotalDistance(string S, int N){            vector prefixDistance(N);    vector suffixDistance(N);            int cnt = 0;        bool haveOne = false;    for (int i = 0; i < N; ++i) {                if (S[i] == '1') {                        haveOne = true;                        cnt = 0;                        prefixDistance[i] = 0;        }                else if (haveOne) {                        cnt++;                        prefixDistance[i] = cnt;        }                        else            prefixDistance[i] = INT_MAX;    }        haveOne = false;    for (int i = N - 1; i >= 0; –i) {                if […]

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