<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>

class Solution:
    def longestSubstring(self, s: str, k: int) -> int:
        state = {}

        # forward = [None] * len(s)
        # for i in range(len(s)):
        #     state[s[i]] = i
        #     forward[i] = state.copy()
        
        state = {}
        backward = [None] * len(s)
        for i in range(len(s) -1, -1, -1):
            state[s[i]] = i
            backward[i] = state.copy()
        
        def calculate_diff(count):
            missing = []
            for char, val in count.items():
                if val < k:
                    missing.append(char)
            
            return missing

        memo = {}

        def calculate(low, hi):
            if hi - low + 1 < k:
                return 0

            if (low, hi) in memo:
                return memo[(low, hi)]

            # print(s[low:hi + 1])
            count = Counter(s[low:hi + 1])
            missing = calculate_diff(count)

            if len(missing) == 0:
                return hi - low + 1

            result = 0
            m = missing[0]
            ll = backward[low].get(m, float('-inf'))

            if ll != float('-inf'):
                result = max(result, calculate(low, ll - 1))
                result = max(result, calculate(ll + 1, hi))
            
            memo[(low, hi)] = result
            return result

        return calculate(0, len(s) - 1)
31233