How to find smallest substring which contains all characters from a given string?
algorithm, string, substring
Solution
You can do a histogram sweep in `O(N+M)` time and `O(1)` space where `N` is the number of characters in the first string and `M` is the number of characters in the second.
It works like this:
- Make a histogram of the second string's characters (key operation is `hist2[ s2[i] ]++`).
- Make a cumulative histogram of the first string's characters until that histogram contains every character that the second string's histogram contains (which I will call "the histogram condition").
- Then move forwards on the first string, subtracting from the histogram, until it fails to meet the histogram condition. Mark that bit of the first string (before the final move) as your tentative substring.
- Move the front of the substring forwards again until you meet the histogram condition again. Move the end forwards until it fails again. If this is a shorter substring than the first, mark that as your tentative substring.
- Repeat until you've passed through the entire first string.
- The marked substring is your answer.
Note that by varying the check you use on the histogram condition, you can choose either to have the same set of characters as the second string, or at least as many characters of each type. (Its just the difference between `a[i]>0 && b[i]>0` and `a[i]>=b[i]`.)
You can speed up the histogram checks if you keep a track of which condition is not satisfied when you're trying to satisfy it, and checking only the thing that you decrement when you're trying to break it. (On the initial buildup, you count how many items you've satisfied, and increment that count every time you add a new character that takes the condition from false to true.)
Problem
I have recently come across an interesting question on strings. Suppose you are given following: ``` Input string1: "this is a test string" Input string2: "tist" Output string: "t stri" ``` So, given above, how can I approach towards finding smallest substring of string1 that contains all the characters from string 2?