<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest substring of</em> <code>s</code> <em>such that the frequency of each character in this substring is greater than or equal to</em> <code>k</code>.</p>

<p data-pm-slice="1 1 []">if no such substring exists, return 0.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;aaabb&quot;, k = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> The longest substring is &quot;aaa&quot;, as &#39;a&#39; is repeated 3 times.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;ababbc&quot;, k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> The longest substring is &quot;ababb&quot;, as &#39;a&#39; is repeated 2 times and &#39;b&#39; is repeated 3 times.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>
	<li><code>s</code> consists of only lowercase English letters.</li>
	<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>

'''

    window(s):
        p1 = 0
        p2 = 0
        repeat_chars = set()
        char_cnt = {}

        add():
            p2 += 1
            new_ch = s[p2]
            char_cnt[new_ch] = char_cnt.get(new_ch, 0) + 1

            if new_ch not in repeat_chars:
                while len(repeat_chars) == k:
                    remove_oldest()
        valid():
            return len(repeat_chars) >= k
'''

from collections import Counter
class Solution:
    def longestSubstring(self, s: str, k: int) -> int:
        
        ctr = Counter(s)

        '''
         aabcc  k = 2
            s_idx  e_idx   ctr 
            0      4       {a : 2 , b : 1, c:2}



        '''

        def solve(s_idx, e_idx, ctr):
            #print(f's = {s_idx} e = {e_idx} c={ctr}')
            so_far = Counter([])
            for idx in range(s_idx, e_idx+1):
                # break it
                this_ch = s[idx]
                if ctr.get(this_ch, 0) < k:
                    other_ctr = ctr - so_far # {this_ch : 1}
                    other_ctr[this_ch] -= 1

                    #print(f'Breaking it this_ch = {this_ch} @idx={idx} {so_far} {other_ctr}')
                    c1 = solve(s_idx, idx-1, so_far)
                    c2 = solve(idx+1, e_idx, other_ctr)
                    # call solve again 
                    return max(c1,c2)
                else:
                    so_far[this_ch] = so_far.get(this_ch, 0) + 1
            
            # a a a  0 , 2  -> 2 + 1 - 0   k = 2
            return e_idx + 1 - s_idx
        
        return solve(0, len(s)-1, ctr)


        
25958