Mid
From PDF
Coding
C# Coding Interview
Find the Smallest Window in String s that Contains?
Short answer: All Characters of String t string MinWindow(string s, string t) return minLen == int.MaxValue ? "" : s.Substring(minLeft, minLen); } Explanation: Sliding window with two pointers keeps track of counts of chars matching the target.
Example code
{
if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t)) return ""; Dictionary<char, int> dictT = new Dictionary<char, int>();
foreach (char c in t)
dictT[c] = dictT.ContainsKey(c) ? dictT[c] + 1 : 1;
int required = dictT.Count;
int formed = 0;
Dictionary<char, int> windowCounts = new Dictionary<char,
int>();
int left = 0, right = 0;
int minLen = int.MaxValue, minLeft = 0; while (right < s.Length) {
char c = s[right]; windowCounts[c] = windowCounts.ContainsKey(c) ? windowCounts[c] + 1 : 1; if (dictT.ContainsKey(c) && windowCounts[c] == dictT[c])
formed++; while (left <= right && formed == required) {
if (right - left + 1 < minLen)
{
minLen = right - left + 1; Follow on: minLeft = left;
}
char leftChar = s[left]; windowCounts[leftChar]--; if (dictT.ContainsKey(leftChar) && windowCounts[leftChar] < dictT[leftChar]) formed--; left++; } right++; }
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
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png