Instructions
You get two strings, s and t. Both contain only English letters.
Find the shortest substring of s that contains every letter of t. A substring is a block of letters that sit next to each other in s.
Repeated letters count. If t has a letter two times, the substring must have that letter at least two times. The substring may also contain letters that are not in t.
Return that substring.
Rules
- If several substrings have the same shortest length, return the one that starts first (the smallest start index).
- If no substring of
scontains all the letters oft, return the empty string"". - Upper case and lower case are different letters:
"A"and"a"do not match.
Hint: keep a window [left, right] and a count of how many letters of t are still missing from it. Move right forward until nothing is missing. Then move left forward as far as you can while nothing is missing, and save the window if it is shorter than the best one so far.
Examples
Example 1
- Input:
- "kmpxkzmp", "kp"
- Output:
- "kmp"
Both "kmp" (index 0 to 2) and "pxk" (index 2 to 4) have a k and a p, and both have length 3. No substring of length 2 has both letters. "kmp" starts first, so it is the answer.
Example 2
- Input:
- "aabxbab", "abb"
- Output:
- "bab"
t needs one a and two b's. "abxb" works but has length 4. "bab" (index 4 to 6) has two b's and one a, and has length 3. No shorter substring has two b's and an a.
Example 3
- Input:
- "Book", "b"
- Output:
- ""
s has a capital "B" but no small "b". Case matters, so no substring works and the answer is the empty string.
Constraints
1 <= s.length <= 601 <= t.length <= 20sandthave only English letters (a-z,A-Z).
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- "kmpxkzmp", "kp"
- Expected:
- "kmp"
- Input:
- "aabxbab", "abb"
- Expected:
- "bab"
- Input:
- "Book", "b"
- Expected:
- ""
Run checks your code against the 3 examples. Submit checks it against all 163 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.