Monday, March 14, 2011

Minimum window that contains all characters

Q: Find the smallest window in a string containing all characters of another string

Given set of characters P and string T find minimum window in T that contains all characters in P. Applicable solution is restricted to O(length(T)) time complexity. For example, given a string T “of characters and as” and set of characters T in a form of a string “aa s” the minimum window will be “and as”.

The problem can be broken into two parts:

  • How to select window?
  • How to check that selected window contains all characters from P?

Selecting every possible window (all unique pairs (i, j) where 0 <= i <= j < length(T)) will lead to solution worse than O(length(T)^2) because you still need to check if all characters from P are within selected window. Instead we will check every possible window ending position. Thus there are at least length(T) windows to consider.

Any feasible window has length equal to or greater than length(P). Performing recheck for any considered window will result in a solution no better than O(length(T)*length(P)). Instead we need to use check results from previous iteration.

Now we need to make sure that checking if a particular character is in P is done in an optimal way. Taking into account that a particular character may appear more than once and window thus must contain appropriate number of characters. We will use hash table to map unique characters from P to their count for fast lookup.

And now let’s tie all things together.

  • Until reached the end of T move by one current window ending position.
  • Append next character to the end of previous window which to this moment doesn’t contain all necessary characters. Char to count map is used to track the number of characters left to find. Basically if character is in P count is decremented. The number may become negative meaning that there are more than required characters.
  • If unmatched character count goes to zero the window contains all required characters. However there may be redundant characters. Thus we try to compact current window. It is ok to do this as we are looking for minimum window and any window that is extended from this one won’t be better.
  • Once window is compacted compare it with the minimum one and updated it if needed.
  • If current window contains all the characters remove from it the first one simply by moving by one starting position to make sure that at each iteration previous window doesn’t contain all the characters (there is no point in appending new characters to a window that already contains all of the required ones).

Working Java code:

public static String findMinWindow(String t, String p)
    {
        // Create char to count mapping for fast lookup
        // as some characters may appear more than once
        HashMap<Character, Integer> charToCount = new HashMap<Character, Integer>();
        for (char c : p.toCharArray())
        {
            if (!charToCount.containsKey(c))
                charToCount.put(c, 0);
            charToCount.put(c, charToCount.get(c)+1);
        }
    
        int unmatchesCount = p.length();
        int minWindowLength = t.length() + 1,minWindowStart = -1;
        int currWindowStart = 0, currWindowEnd = 0;
        for (; currWindowEnd < t.length(); currWindowEnd++)
        {
            char c = t.charAt(currWindowEnd);
            // Skip chars that are not in P
            if (!charToCount.containsKey(c))
                continue;
            // Reduce unmatched characters count
            charToCount.put(c, charToCount.get(c)-1);
            if (charToCount.get(c) >= 0)
                // But do this only while count is positive
                // as count may go negative which means
                // that there are more than required characters
                unmatchesCount--;
    
            // No complete match, so continue searching
            if (unmatchesCount > 0)
                continue;
    
            // Decrease window as much as possible by removing
            // either chars that are not in T or those that
            // are in T but there are too many of them
            c = t.charAt(currWindowStart);
            boolean contains = charToCount.containsKey(c);
            while (!contains || charToCount.get(c) < 0)
            {
                if (contains)
                    // Return character to P
                    charToCount.put(c,charToCount.get(c)+1);
    
                c = t.charAt(++currWindowStart);
                contains = charToCount.containsKey(c);
            }
    
            if (minWindowLength > currWindowEnd - currWindowStart + 1)
            {
                minWindowLength = currWindowEnd - currWindowStart + 1;
                minWindowStart = currWindowStart;
            }
    
            // Remove last char from window - it is definitely in a
            // window because we stopped at it during decrease phase
            charToCount.put(c, charToCount.get(c)+1);
            unmatchesCount++;
            currWindowStart++;
        }
    
        return minWindowStart > -1 ?
               t.substring(minWindowStart, minWindowLength) : "";
    }

Every character is examined at most twice (during appending to the end and during compaction) so the whole solution has O(length(T)) time complexity assuming hash table lookup is O(1) operation.

No comments: