Sort by

recency

|

25 Discussions

|

  • + 0 comments

    Same idea as Daniel_v_oconnor, but the code is a little easier to understand.

      
    	
    long gcd(long a, long b)
    {
      if (b == 0) return a;
      return gcd(b, a % b);
    }
    
    string solve(long n, int k, string s)
    {
      int a=0,b;
      long cnt=0,sum=0;
      for (b = 0; b <= k; b++) 
        if (s[b]=='1') sum++;
      for(a=0,b=k+1;a<n;a++,b++) {
        if (s[a]=='1') cnt+=sum;
        if (a>=k) sum-=s[a-k]=='1';
        if (b<n) sum+=s[b]=='1';
      }
      long nxn = n * n, div = gcd(cnt, nxn);
      cnt /= div, nxn /= div;
      return to_string(cnt) + "/" + to_string(nxn);
    }
    
  • + 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}'
    
  • + 0 comments
    def solve(n, k, s):
        # Write your code here
        valid_pairs = 0
        counter = [0]*(n+1)
        
        # at counter[i] there will be count of 1s upto i
        for i, bit in enumerate(s):
            counter[i + 1] = counter[i] + int(bit)
            
        p = 0
        for i, bit in enumerate(s):
            if bit == "1":
                p += counter[min(n, i + k + 1)] - counter[max(0, i - k)]
                         
        total_pairs = n*n           
        gcd_val = math.gcd(p, total_pairs)
        numerator = p//gcd_val
        denominator = total_pairs//gcd_val
        
        return f"{numerator}/{denominator}"
    
  • + 0 comments
    def solve(n, k, s):
    
        s= [int(x) for x in s]
        rolling_sum=sum(s[:k+1])
     
        num_pairs=0
        for i in range(k,n+k):
            if s[i-k]:
                num_pairs+=2*rolling_sum-1
                rolling_sum-=1
            if i+1<n:
                rolling_sum+=s[i+1]
        
        d=math.gcd(num_pairs, n**2)
        
        return f'{int(num_pairs/d)}/{int(n**2/d)}'  
    
  • + 0 comments

    I had to make code use one loop instead of two loops to avoid TLE in test case 0. Just advice for whoever is getting TLE in test case 0 as well.