AlgoMaster Logo

Minimum Window Substring

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

The most straightforward solution is to generate all possible substrings of s, and check if they contain all characters of t. However, this will be highly inefficient due to the large number of potential substrings, especially for long input strings.

Intuition:

  1. Generate all possible substrings of s.
  2. For each substring, count its characters and check if they match those in t.
  3. Track the minimum-length substring that contains all characters of t.

Code:

2. Sliding Window using HashMap

The sliding window technique optimizes the process of finding the minimum window by maintaining two pointers to represent a window and expanding or shrinking it as needed.

Intuition:

  1. Use two pointers: one to expand the window (right), and one to contract it (left).
  2. Use a HashMap to keep track of characters' frequencies in the current window.
  3. When the window contains all characters of t, try to shrink it by moving the left pointer to minimize the window size.
  4. Record the smallest window found.

Code: