LeetCode Solutions

340. Longest Substring with At Most K Distinct Characters

Time: $O(n)$

Space: $O(128) = O(1)$

			

class Solution {
 public:
  int lengthOfLongestSubstringKDistinct(string s, int k) {
    int ans = 0;
    int distinct = 0;
    vector<int> count(128);

    for (int l = 0, r = 0; r < s.length(); ++r) {
      if (++count[s[r]] == 1)
        ++distinct;
      while (distinct == k + 1)
        if (--count[s[l++]] == 0)
          --distinct;
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
			

class Solution {
  public int lengthOfLongestSubstringKDistinct(String s, int k) {
    int ans = 0;
    int distinct = 0;
    int[] count = new int[128];

    for (int l = 0, r = 0; r < s.length(); ++r) {
      if (++count[s.charAt(r)] == 1)
        ++distinct;
      while (distinct == k + 1)
        if (--count[s.charAt(l++)] == 0)
          --distinct;
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
			

class Solution:
  def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
    ans = 0
    distinct = 0
    count = Counter()

    l = 0
    for r, c in enumerate(s):
      count[c] += 1
      if count[c] == 1:
        distinct += 1
      while distinct == k + 1:
        count[s[l]] -= 1
        if count[s[l]] == 0:
          distinct -= 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans