![]() |
VOOZH | about |
Given two strings s and p, the task is to find the smallest substring in s that contains all characters of p, including duplicates. If no such substring exists, return "". If multiple substrings of the same length are found, return the one with the smallest starting index.
Examples:
Input: s = "timetopractice", p = "toc"
Output: toprac
Explanation: "toprac" is the smallest substring in which "toc" can be found.Input: s = "zoomlazapzo", p = "oza"
Output: apzo
Explanation: "apzo" is the smallest substring in which "oza" can be found.
Table of Content
The very basic idea to solve this problem is that we can generate all possible substrings of the given string s and checking each substring to see if it contains all characters of string p. This checking can be done by a helper function that counts the frequency of each character in p equals with frequency of the chosen substring. If a substring contains all characters of the p, then its length is compared to the current minimum length and the smallest substring is updated accordingly. The process continues until all substrings have been checked.
toprac
The idea is to check if a window of a certain size "mid" is valid (contains all characters of the p string), then all windows of size greater than "mid" will also be valid. Similarly, if a window of size "mid" is not valid, then all windows of size smaller than "mid" will also not be valid. This property allows us to apply binary search effectively.
Follow the steps below to solve the problem:
toprac
The idea is to use Window Sliding (
startandj) to maintain a sliding window over stringS, while tracking character frequencies with two count arrays.
Steps:
P.S.j pointer through S, updating the window's character counts.P are present in the window, a valid window is found.start pointer right to minimize the window while ensuring all characters from P remain in the window."-1".Illustration:
toprac