Minimum Window Substring

Program for Smallest Substring in a string that contains all the characters of another string Problem

You are given two strings, s and t. Your task is to find the smallest substring in s that contains all the characters of t, including their respective frequencies (i.e., duplicates must also be accounted for).

If no such substring exists, return an empty string (“”). You can assume that, if a valid substring exists, it will always be unique, meaning there won’t be multiple shortest substrings satisfying the condition.

Minimum Sliding Window

Explanation :“YXAZ” is the shortest substring that includes “X”, “Y”, and “Z” from string t.

Explanation: “apzo” is the smallest substring in which “oza” can be found.

Constraints:

  • 1 <= s1.length, s2.length <= 1000

Program for Smallest Substring in a string that contains all the characters of another string Solution

Recommendation for Time and Space Complexity – You should aim for a solution with O(n) time and O(m) space, where n is the length of the string s and m is the number of unique characters in s and t.

Hints for solving problems

Hint 1 :

A brute force solution would involve checking every substring of s against t and returning the minimum length valid substring. This would be an O(n^2) solution. Can you think of a better way? Maybe you should think in terms of frequency of characters.

Hint 2 :

We need to find substrings in s that should have atleast the characters of t. We can use hash maps to maintain the frequencies of characters. It will be O(1) for lookups. Can you think of an algorithm now?

There are mainly 2 approach to solve this problem-

  1. Brute Force Method
  2. Sliding Window Method

1. Brute Force Method

Generate all possible substrings of s and check if each contains all characters of t. Among valid substrings, return the shortest one. This approach is highly inefficient due to its exponential time complexity.

  • Time complexity: O(n^2)
  • Space complexity: O(m)

where n is the length of the string s and m is the total number of unique characters in the strings t and s.

Code

2. Sliding Window Method

Use two pointers to create a dynamic window in s, expanding and contracting it to include all characters of t. Maintain a frequency map to track the characters and efficiently find the smallest valid window.

  • Time complexity: O(n)
  • Space complexity: O(m)

where n is the length of the string s and m is the total number of unique characters in the strings t and s.

Code

More Articles