[Leetcode] Minimum Window Substring

PHIL
Coding Memo
Published in
1 min readMay 23, 2022

A sliding window problem similar with Longest Repeating Character Replacement while requires more intricate technique.

Description

Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

The testcases will be generated such that the answer is unique.

A substring is a contiguous sequence of characters within the string.

Examples

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.

Example 2:

Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.

Example 3:

Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.

Follow up: Could you find an algorithm that runs in O(m + n) time?

Solution

To efficiently check if substring includes all chars, keep a Counter to increment the count when meeting char. Also, use a variable char_included to keep chars already in substring. When char_included = len(t), a valid solution is found.

To search other solutions, discard one collected char per round so there is room for new char. Restore the count info before shifting left pointer. As char_included becomes < len(t), right pointer is ready to search new char.

  • code

ref: https://blog.csdn.net/fuxuemingzhu/article/details/82931106

--

--

PHIL
Coding Memo

Jotting the ideas down in codes or articles