class Solution(object):
    def longestSubstring(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: int (returns the length of the longest substring)
        """
        i = 0
        max_len = 0
        counts = {} 
        
        for j in range(len(s)):
           
            counts[s[j]] = counts.get(s[j], 0) + 1
            
           
            while max(ord(ch) for ch in counts) - min(ord(ch) for ch in counts) > k:
                counts[s[i]] -= 1
                if counts[s[i]] == 0:
                    del counts[s[i]]  # Remove key so it doesn't affect min/max
                i += 1
            
      
            current_len = j - i + 1
            if current_len > max_len:
                max_len = current_len
                
        return max_len
