Mid From PDF Coding C# Coding Interview

Find the longest substring with exactly two distinct characters?

Short answer: 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:…

Explain a bit more

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

Example code

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.

Real-world example (ShopNest)

In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).

Say this in the interview

  1. Define — one clear sentence (the short answer above).
  2. Example — relate it to a project like ShopNest or your real work.
  3. Trade-off — when you would not use it.
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