Bear and Steady Gene

  • + 1 comment

    If you imagine us initially having every character in the gene, we can 'reverse' the problem to try and remove the fewest characters possible, while still having the other characters be below the required limit of . This transforms the problem into a classic sliding window, where we need to find the smallest window to 'remove', such that the characters outside of the window are still valid.

    def steadyGene(gene):
        N = len(gene)
        goal = N // 4
        curr = Counter(gene)
        ans = N
        l = 0
        for r in range(N):
            curr[gene[r]] -= 1
            while l < N and max(curr.values()) <= goal:
                ans = min(ans, r - l + 1)
                curr[gene[l]] += 1
                l += 1
        return ans