Problem: Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
Input: s = "ADOBECODEBANC", t = "ABC" Output: "BANC" Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Input: s = "a", t = "a" Output: "a" Explanation: The entire string s is the minimum window.
Input: s = "a", t = "aa" Output: "" Explanation: Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string.
Approach:
- First check if the length of string is less than the length of the given pattern, if yes then return empty string.
- Store the occurrence of characters of the given pattern in a hash.
- Start matching the characters of pattern with the characters of string i.e. increment count if a character matches.
- Check if (count == length of pattern ) this means a window is found.
- If such window found, try to minimize it by removing extra characters from the beginning of the current window.
- Update minWindowLength.
- Return the minimum length window.
Implementation in C#:
    public string MinWindow(string s, string t)
    {
        int sLength = s?.Length ?? 0;
        int tLength = t?.Length ?? 0;
        if (sLength < tLength)
        {
            return "";
        }
        var tCharMap = this.BuildCharMap(t);
        var sCharMap = new Dictionary<char, int>();
        int count = 0;
        int startIndex = -1, start = 0, minLen = int.MaxValue;
        for (int end = 0; end < sLength; ++end)
        {
            if (!sCharMap.ContainsKey(s[end]))
            {
                sCharMap[s[end]] = 0;
            }
            ++sCharMap[s[end]];
            if (tCharMap.ContainsKey(s[end]) && 
                sCharMap[s[end]] <= tCharMap[s[end]])
            {
                ++count;
            }
            if (count == tLength)
            {
                while (!tCharMap.ContainsKey(s[start]) ||
                       tCharMap[s[start]] < sCharMap[s[start]])
                {
                    --sCharMap[s[start]];
                    ++start;
                }
                int currLen = end - start + 1;
                if (currLen < minLen)
                {
                    minLen = currLen;
                    startIndex = start;
                }
            }
        }
        if (startIndex == -1)
        {
            return "";
        }
        return s.Substring(startIndex, minLen);
    }
    private Dictionary<char, int> BuildCharMap(string str)
    {
        var charMap = new Dictionary<char, int>();
        foreach (char ch in str)
        {
            if (!charMap.ContainsKey(ch))
            {
                charMap[ch] = 0;
            }
            ++charMap[ch];
        }
        return charMap;
    }
Complexity: O(n)
 
 
No comments:
Post a Comment