Balanced Bitstring (Codeforces 1405C)
Tags: Greedy, strings

A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called $$$k$$$-balanced if every substring of size $$$k$$$ of this bitstring has an equal amount of 0 and 1 characters ($$$\frac{k}{2}$$$ of each).You are given an integer $$$k$$$ and a string $$$s$$$ which is composed only of characters 0, 1, and ?. You need to determine whether you can make a $$$k$$$-balanced bitstring by replacing every ? characters in $$$s$$$ with either 0 or 1.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows.The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ is even)  — the length of the string and the parameter for a balanced bitstring.The next line contains the string $$$s$$$ ($$$|s| = n$$$). It is given that $$$s$$$ consists of only 0, 1, and ?.It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

Output: For each test case, print YES if we can replace every ? in $$$s$$$ with 0 or 1 such that the resulting bitstring is $$$k$$$-balanced, or NO if it is not possible.

Note: For the first test case, the string is already a $$$4$$$-balanced bitstring.For the second test case, the string can be transformed into 101.For the fourth test case, the string can be transformed into 0110.For the fifth test case, the string can be transformed into 1100110.

Sample Inputs:
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00

Sample Outputs:
YES
YES
NO
YES
YES
NO
NO
YES
NO

Solution (Python):
import sys
input = sys.stdin.readline

def readList():
    return list(map(int, input().split()))

def readInt():
    return int(input())

def readInts():
    return map(int, input().split())

def readStr():
    return input().strip()

def solve():
    (n, k) = readInts()
    s = readStr()
    (orc, cnt, v) = ([''] * k, 0, 0)
    for i in range(n):
        if s[i] == '?':
            continue
        if orc[i % k] == '':
            orc[i % k] = s[i]
            cnt += 1
            v += int(s[i])
        elif orc[i % k] != s[i]:
            return 'NO'
    return 'YES' if min(v, cnt - v) + k - cnt >= max(v, cnt - v) else 'NO'
for _ in range(int(input())):
    print(solve())

Solution (Python):
""""""
''
import sys
input = sys.stdin.readline
read = lambda : map(int, input().split())

def ceil(x):
    if x != int(x):
        x = int(x) + 1
    return x

def factorial(x, m):
    val = 1
    while x > 0:
        val = val * x % m
        x -= 1
    return val

def fact(x):
    val = 1
    while x > 0:
        val *= x
        x -= 1
    return val

def swaparr(arr, a, b):
    temp = arr[a]
    arr[a] = arr[b]
    arr[b] = temp

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return a * b // gcd(a, b)

def nCr(n, k):
    if k > n:
        return 0
    if k > n - k:
        k = n - k
    res = 1
    for i in range(k):
        res = res * (n - i)
        res = res / (i + 1)
    return int(res)

def upper_bound(a, x, lo=0, hi=None):
    if hi == None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

def primefs(n):
    primes = {}
    while n % 2 == 0 and n > 0:
        primes[2] = primes.get(2, 0) + 1
        n = n // 2
    for i in range(3, int(n ** 0.5) + 2, 2):
        while n % i == 0 and n > 0:
            primes[i] = primes.get(i, 0) + 1
            n = n // i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    return primes

def power(x, y, p):
    res = 1
    x = x % p
    if x == 0:
        return 0
    while y > 0:
        if y & 1 == 1:
            res = res * x % p
        y = y >> 1
        x = x * x % p
    return res

def swap(a, b):
    temp = a
    a = b
    b = temp
    return (a, b)

def find(x, link):
    p = x
    while p != link[p]:
        p = link[p]
    while x != p:
        nex = link[x]
        link[x] = p
        x = nex
    return p

def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        (x, y) = swap(x, y)
    if x != y:
        size[x] += size[y]
        link[y] = x

def sieve(n):
    prime = [True for i in range(n + 1)]
    (prime[0], prime[1]) = (False, False)
    p = 2
    while p * p <= n:
        if prime[p] == True:
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
    return prime

def phi(n):
    result = n
    p = 2
    while p * p <= n:
        if n % p == 0:
            while n % p == 0:
                n = n // p
            result = result * (1.0 - 1.0 / float(p))
        p = p + 1
    if n > 1:
        result = result * (1.0 - 1.0 / float(n))
    return int(result)

def is_prime(n):
    if n == 0:
        return False
    if n == 1:
        return True
    for i in range(2, int(n ** (1 / 2)) + 1):
        if not n % i:
            return False
    return True
MAXN = int(100000.0 + 5)

def spf_sieve():
    spf[1] = 1
    for i in range(2, MAXN):
        spf[i] = i
    for i in range(4, MAXN, 2):
        spf[i] = 2
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i * i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
    res = []
    for i in range(2, int(x ** 0.5) + 1):
        while x % i == 0:
            res.append(i)
            x //= i
    if x != 1:
        res.append(x)
    return res

def factors(n):
    res = []
    for i in range(1, int(n ** 0.5) + 1):
        if n % i == 0:
            res.append(i)
            res.append(n // i)
    return list(set(res))

def int_array():
    return list(map(int, input().strip().split()))

def float_array():
    return list(map(float, input().strip().split()))

def str_array():
    return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
from bisect import bisect_left

def solve():
    (n, k) = read()
    s = list(input().rstrip())
    for i in range(k):
        if s[i] == '?':
            for j in range(i + k, n, k):
                if s[j] != '?':
                    s[i] = s[j]
                    break
    for i in range(k):
        if s[i] != '?':
            for j in range(i + k, n, k):
                if s[j] == '?':
                    s[j] = s[i]
                elif s[j] != s[i]:
                    print('NO')
                    return
    if s[:k].count('1') <= k // 2 and s[:k].count('0') <= k // 2:
        print('YES')
    else:
        print('NO')
if __name__ == '__main__':
    for _ in range(int(input())):
        solve()

Solution (Python):
""""""
''
import sys
input = sys.stdin.readline
read = lambda : map(int, input().split())

def ceil(x):
    if x != int(x):
        x = int(x) + 1
    return x

def factorial(x, m):
    val = 1
    while x > 0:
        val = val * x % m
        x -= 1
    return val

def fact(x):
    val = 1
    while x > 0:
        val *= x
        x -= 1
    return val

def swaparr(arr, a, b):
    temp = arr[a]
    arr[a] = arr[b]
    arr[b] = temp

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def lcm(a, b):
    return a * b // gcd(a, b)

def nCr(n, k):
    if k > n:
        return 0
    if k > n - k:
        k = n - k
    res = 1
    for i in range(k):
        res = res * (n - i)
        res = res / (i + 1)
    return int(res)

def upper_bound(a, x, lo=0, hi=None):
    if hi == None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

def primefs(n):
    primes = {}
    while n % 2 == 0 and n > 0:
        primes[2] = primes.get(2, 0) + 1
        n = n // 2
    for i in range(3, int(n ** 0.5) + 2, 2):
        while n % i == 0 and n > 0:
            primes[i] = primes.get(i, 0) + 1
            n = n // i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    return primes

def power(x, y, p):
    res = 1
    x = x % p
    if x == 0:
        return 0
    while y > 0:
        if y & 1 == 1:
            res = res * x % p
        y = y >> 1
        x = x * x % p
    return res

def swap(a, b):
    temp = a
    a = b
    b = temp
    return (a, b)

def find(x, link):
    p = x
    while p != link[p]:
        p = link[p]
    while x != p:
        nex = link[x]
        link[x] = p
        x = nex
    return p

def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        (x, y) = swap(x, y)
    if x != y:
        size[x] += size[y]
        link[y] = x

def sieve(n):
    prime = [True for i in range(n + 1)]
    (prime[0], prime[1]) = (False, False)
    p = 2
    while p * p <= n:
        if prime[p] == True:
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
    return prime

def phi(n):
    result = n
    p = 2
    while p * p <= n:
        if n % p == 0:
            while n % p == 0:
                n = n // p
            result = result * (1.0 - 1.0 / float(p))
        p = p + 1
    if n > 1:
        result = result * (1.0 - 1.0 / float(n))
    return int(result)

def is_prime(n):
    if n == 0:
        return False
    if n == 1:
        return True
    for i in range(2, int(n ** (1 / 2)) + 1):
        if not n % i:
            return False
    return True
MAXN = int(100000.0 + 5)

def spf_sieve():
    spf[1] = 1
    for i in range(2, MAXN):
        spf[i] = i
    for i in range(4, MAXN, 2):
        spf[i] = 2
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i * i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
    res = []
    for i in range(2, int(x ** 0.5) + 1):
        while x % i == 0:
            res.append(i)
            x //= i
    if x != 1:
        res.append(x)
    return res

def factors(n):
    res = []
    for i in range(1, int(n ** 0.5) + 1):
        if n % i == 0:
            res.append(i)
            res.append(n // i)
    return list(set(res))

def int_array():
    return list(map(int, input().strip().split()))

def float_array():
    return list(map(float, input().strip().split()))

def str_array():
    return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
from bisect import bisect_left

def solve():
    (n, k) = read()
    s = list(input().rstrip())
    for i in range(k):
        if s[i] == '?':
            for j in range(i + k, n, k):
                if s[j] != '?':
                    s[i] = s[j]
                    break
    for i in range(k):
        if s[i] != '?':
            for j in range(i + k, n, k):
                if s[j] == '?':
                    s[j] = s[i]
                elif s[j] != s[i]:
                    print('NO')
                    return
    if s[:k].count('1') <= k // 2 and s[:k].count('0') <= k // 2:
        print('YES')
    else:
        print('NO')
if __name__ == '__main__':
    for _ in range(int(input())):
        solve()