The goal of this problem is to find the smallest substring in s that contains all characters of t
, including their
frequencies. To do this, we can use a sliding window approach to dynamically adjust the substring range, ensuring we
capture all characters in `t while minimizing the window length.
- Frequency Maps for Target and Window:
- Create a frequency map for
t
(queryFrequencies
) to track the required count of each character. - Use another map (
windowFrequencies
) to keep track of the character counts in the current window withins
.
- Create a frequency map for
- Sliding Window with Two Pointers:`
- We use two pointers,
i
andj
, wherei
represents the start of the window andj
the end. - Expand the window by moving
j
to the right and updatingwindowFrequencies
. - Whenever a character in
windowFrequencies
reaches the count required byqueryFrequencies
, increase thewindowDistinctCount
.
- We use two pointers,
- Shrinking the Window to Find Minimum Length:
- When the
windowDistinctCount
equals the number of distinct characters int
, check if the current window length is the smallest seen so far. - Try to reduce the window size by incrementing
i
and updatingwindowFrequencies
until the window no longer contains all required characters.
- When the
- Updating the Result: Track the smallest valid window by updating
startWindowIndex
andendWindowIndex
when a smaller valid window is found. - Final Result: If no valid window was found, return an empty string. Otherwise, construct the result substring
using
startWindowIndex
andendWindowIndex
.
- Time Complexity:
O(m + n)
, wherem
is the length ofs
andn
is the length oft
. Each character is processed at most twice—once when expandingj
and once when contractingi
. - Space Complexity:
O(n)
, due to the additional space for frequency maps and counters.
This solution uses a sliding window technique combined with frequency counting to efficiently find the smallest
substring in s that contains all characters of t
. By expanding and contracting the window as needed, we ensure that
the solution meets the O(m + n)
complexity requirement. This approach effectively minimizes the substring length while
guaranteeing that all characters from t are included.