Mid From PDF Coding C# Coding Interview

Find the longest substring with exactly two distinct characters?

public int LengthOfLongestSubstringTwoDistinct(string s) {
int left = 0, right = 0, maxLen = 0;
Dictionary<char, int> map = new Dictionary<char, int>();

while (right < s.Length) {

Follow on:

char c = s[right];
map[c] = right;
if (map.Count > 2) {
int delIndex = map.Values.Min();

map.Remove(s[delIndex]);

left = delIndex + 1;
}
maxLen = Math.Max(maxLen, right - left + 1);

right++;

}
return maxLen;
}

Explanation:

Sliding window with hashmap to track indices of distinct chars, remove the leftmost when

>2.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details