public class Solution { public string MinWindow(string s, string t) { // 1. save t[i] into hash and get count of unique char in t var countT = 0; var hashT = new Dictionary(); for(var i = 0;i < t.Length; i++){ if(!hashT.ContainsKey(t[i])){ hashT.Add(t[i], 1); countT++; } else{ hashT[t[i]]++; } } // 2. init hashS var hashS = new Dictionary (); for(var i = 0;i < s.Length; i++){ if(!hashS.ContainsKey(s[i])){ hashS.Add(s[i], 0); } } var mapped = 0; // without duplicate (say 'bccd' , mapped here means 'bcd') var left = 0; var minLen = s.Length; var result = s; var found = false; for (int i = 0; i < s.Length; i++) { char c = s[i]; if (hashT.ContainsKey(c)) { hashS[c]++; // we have done mapping for s[i], increase mapped count for it if (hashT[c] == hashS[c]) { mapped++; } } if (mapped == countT) { found = true; var leftC = s[left]; // if first char(say c) is not include in t , or count of c in hashS is more than in hashT then: hashS[c] -- // set left++ while (!hashT.ContainsKey(leftC) || hashS[leftC] > hashT[leftC]){ if (hashT.ContainsKey(leftC) && hashS[leftC] > hashT[leftC]){ hashS[leftC]--; } left++; leftC = s[left]; } if (i - left + 1< minLen) { result = s.Substring(left, i - left + 1); minLen = i - left + 1; } } } return !found ? : result; } }