-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
longest_substring_with_k_unique_characters.cpp
81 lines (73 loc) · 2.3 KB
/
longest_substring_with_k_unique_characters.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Longest Substring with k Distinct Characters
* Given a string, print the longest possible substring that
* has exactly K unique characters.
*/
#include <bits/stdc++.h>
using namespace std;
int kUniqueChar(string str, int k)
{
//2 Pointers to point to start and end of current window
int start = 0, end = 0;
int len = str.length();
//Map maintains current count of each letter
map<char, int> charCount;
//Variable ans stores the length of longest possible substring that has exactly n unique characters
int ans = 0;
//Iterate until end of current window reaches end of string
while (end < len) {
//Updating count of current letter
charCount[str[end]]++;
//unique elements less than required increase window size
if (charCount.size() < k)
end++;
/*if unique element equals to required we need to check
if on increasing the window size whether repetitive element is present or not
if present then update it as ans and increase window size*/
else if (charCount.size() == k) {
ans = max(ans, end - start + 1);
end++;
}
else if (charCount.size() > k) {
/*If there are more than k unique characters in
current window, remove element from left side*/
while (charCount.size() > k) {
charCount[str[start]]--;
// If occurence of character becomes 0,then we will remove it from map
if (charCount[str[start]] == 0)
charCount.erase(str[start]);
start++;
}
/*move forward
increment end*/
end++;
}
}
return ans;
}
int main()
{
string str;
int k;
cout << "Enter a string: ";
cin >> str;
cout << "Enter number of distict characters: ";
cin >> k;
cout << "Longest substring with " << k << " distinct characters: ";
cout << kUniqueChar(str, k);
}
/*
Test cases:
INPUT:
Enter a string: aabcbcbcbd
Enter number of distict characters: 3
OUTPUT:
Longest substring with 3 distinct characters: 9
INPUT:
Enter a string: perepeereyjjjjj
Enter number of distict characters: 4
OUTPUT:
Longest substring with 4 distinct characters: 10
Time complexity: O(N)
Space complexity: O(N)
*/