Skip to content

Instantly share code, notes, and snippets.

@m-khooryani
Created June 9, 2020 16:10
Show Gist options
  • Save m-khooryani/2453b1d1bb6515a7c99689886875504d to your computer and use it in GitHub Desktop.
Save m-khooryani/2453b1d1bb6515a7c99689886875504d to your computer and use it in GitHub Desktop.
Longest substring with K unique characters
This problem was asked by Amazon.
Given an integer k and a string s,
find the length of the longest substring that
contains at most k distinct characters.
For example, given s = "abcba" and k = 2,
the longest substring with k distinct characters is "bcb".
class Program
{
static void Main(string[] args)
{
Console.WriteLine(LongestSubstringWithKUniqueChars("abcba", 2));
}
private static string LongestSubstringWithKUniqueChars(string s, int k)
{
if (k == 0)
{
return string.Empty;
}
Dictionary<char, int> char_count = new Dictionary<char, int>();
int left = 0, maxL = 0, right = -1, maxR = -1;
while (right != s.Length - 1)
{
if (char_count.ContainsKey(s[right + 1]) || char_count.Count < k)
{
right++;
int temp = 1;
if (char_count.ContainsKey(s[right]))
{
temp += char_count[s[right]];
}
char_count[s[right]] = temp;
}
else
{
char_count[s[left]] = char_count[s[left]] - 1;
if (char_count[s[left]] == 0)
{
char_count.Remove(s[left]);
}
left++;
}
if (right - left > maxR - maxL)
{
maxR = right;
maxL = left;
}
}
return s[maxL..++maxR];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment