Tutorialspoint
Problem
Solution
Submissions

Smallest Window in a String

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Given two strings `s` and `t`, find the minimum window substring of `s` that contains all the characters of `t` (including duplicates). If there is no such substring, return an empty string "".

Example 1
  • Input: s = "ADOBECODEBANC", t = "ABC"
  • Output: "BANC"
  • Explanation:
    • Step 1: We need to find the smallest substring in s that contains all characters in t.
    • Step 2: We can use a sliding window approach to track the characters we need.
    • Step 3: After checking all possible windows, "BANC" is the smallest substring that contains all characters in t (A, B, and C).
    • Step 4: There is no smaller window that contains all the characters of t.
Example 2
  • Input: s = "aaaaaaaaaaaabbbbbcdd", t = "abcdd"
  • Output: "abbbbbcdd"
  • Explanation:
    • Step 1: We need to find the smallest substring in s that contains all characters in t.
    • Step 2: We can use a sliding window approach to track the characters we need.
    • Step 3: After checking all possible windows, "abbbbbcdd" is the smallest substring that contains all characters in t (a, b, c, d, d).
    • Step 4: There is no smaller window that contains all the characters of t.
Constraints
  • 1 ≤ s.length, t.length ≤ 10^5
  • s and t consist of uppercase and lowercase English letters.
  • The answer is guaranteed to be unique.
  • Time Complexity: O(n), where n is the length of string s.
  • Space Complexity: O(k), where k is the size of the character set.
Hash MapPointers and ReferencesGoogleTech Mahindra
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the sliding window technique with two pointers.
  • Use a hash table to keep track of the characters needed from t.
  • Expand the right pointer until all characters of t are found.
  • Contract the left pointer to minimize the window size while maintaining all characters of t.
  • Track the minimum window found so far.

Steps to solve by this approach:

 Step 1: Create hash maps to track character frequencies in string t and the current window

 Step 2: Initialize pointers - left and right - to implement the sliding window technique
 Step 3: Expand the window by moving the right pointer until we find all required characters
 Step 4: Once all required characters are found, try to minimize the window by moving the left pointer
 Step 5: Track the minimum valid window found so far and return it as the result

Submitted Code :