Dashboard Temp Share Shortlinks Frames API

HTMLify

Longest Substring with K Uniques
Views: 6 | Author: prakhardoneria
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def longestKSubstr(self, s, k):
        n = len(s)
        distinct_map = {}
        left = 0
        max_len = -1
        
        for right in range(n):
            char = s[right]
            distinct_map[char] = distinct_map.get(char, 0) + 1
            
            while len(distinct_map) > k:
                left_char = s[left]
                distinct_map[left_char] -= 1
                if distinct_map[left_char] == 0:
                    del distinct_map[left_char]
                left += 1
            
            if len(distinct_map) == k:
                max_len = max(max_len, right - left + 1)
                
        return max_len