• + 0 comments

    The trickiest part of this problem is that one must use the "rolling sum" trick to obtain an O(N) solution that meets the runtime requirements. Here's a relatively simple Python solution:

    def solve(N, K, S):   
        S = [int(b) for b in S]
        rolling_sum = sum(S[0:K])
        numerator = 0
        for i in range(N):
            if i > K:
                rolling_sum = rolling_sum - S[i-K-1]
            if i < N - K:
                rolling_sum = rolling_sum + S[i+K]
            if S[i]:
                numerator = numerator + rolling_sum
                
        denominator = N**2
        d = math.gcd(numerator, denominator)    
        return f'{numerator//d}/{denominator//d}'