https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/

1. Use Sliding Window & Hashmap:

  1. class Solution {
  2. public:
  3. int lengthOfLongestSubstringKDistinct(string s, int k) {
  4. int n = s.length();
  5. if(n == 0 || k == 0){
  6. return 0;
  7. }
  8. int l = 0, r = 0;
  9. map<char, int> rightmost_pos;
  10. int max_len = 1;
  11. while(r < n) {
  12. rightmost_pos[s[r]] = r;
  13. if(rightmost_pos.size() > k){ //has k + 1 distinct numbers
  14. int lowest_index = INT_MAX;
  15. for(pair<char, int> element : rightmost_pos) {
  16. lowest_index = min(lowest_index, element.second); //find the leftmost index in map
  17. }
  18. rightmost_pos.erase(s[lowest_index]); //erase the left most one
  19. l = lowest_index + 1;
  20. }
  21. max_len = max(max_len, r - l + 1);
  22. r++;
  23. }
  24. return max_len;
  25. }
  26. };

Time Complexity: O(N)
Space Complexity: O(k)