diff --git a/string_problems/longest_k_distinct.cpp b/string_problems/longest_k_distinct.cpp new file mode 100644 index 0000000..acd6481 --- /dev/null +++ b/string_problems/longest_k_distinct.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; + +int longestKDistinct(string s, int k) { + unordered_map count; + int left = 0, maxLen = 0; + + for (int right = 0; right < s.size(); right++) { + count[s[right]]++; + + while (count.size() > k) { + count[s[left]]--; + if (count[s[left]] == 0) + count.erase(s[left]); + left++; + } + + if (count.size() == k) + maxLen = max(maxLen, right - left + 1); + } + + return maxLen; +} + +int main() { + string s; + int k; + cout << "Enter string: "; + cin >> s; + cout << "Enter K: "; + cin >> k; + + int result = longestKDistinct(s, k); + cout << "Length of longest substring with " << k << " distinct characters is: " << result << endl; + return 0; +}