Prepin
Log in

Smallest Substring Containing All Characters

Approach / Explanation

The Minimum Window Substring problem is categorized as a sliding window problem within the realm of algorithms and data structures. The typical query involves identifying the smallest substring in a specified string that encompasses all the characters of another string. This problem evaluates your understanding of data structures and algorithms, particularly the application of hashtables and the two-pointer or sliding window technique. To tackle this problem, you should follow these steps: First, create a frequency map (hashtable) for the second string, which will help determine the characters needed in our substring. Begin at the start of the string and continuously add characters to our substring until it contains all the characters from the second string. Then, reduce the window size from the beginning until you find the minimum substring that still includes all characters from the second string.

Suggested Answer

In Python, the sliding window technique can be implemented as follows: def min_window ( s , t ) : if not t or not s : return "" t_count_dict = collections . Counter ( t ) required = len ( t_count_dict ) l , r = 0 , 0 formed = 0 window_counts = { } ans = float ( "inf" ) , None , None while r < len ( s ) : char = s [ r ] window_counts [ char ] = window_counts . get ( char , 0 ) + 1 if char in t_count_dict and window_counts [ char ] == t_count_dict [ char ] : formed += 1 while l <= r and formed == required : char = s [ l ] if r - l + 1 < ans [ 0 ] : ans = ( r - l + 1 , l , r ) window_counts [ char ] -= 1 if char in t_count_dict and window_counts [ char ] < t_count_dict [ char ] : formed -= 1 l += 1 r += 1 return "" if ans [ 0 ] == float ( "inf" ) else s [ ans [ 1 ] : ans [ 2 ] + 1 ] In this implementation, "ans" serves as a tuple that holds the length of the substring along with the left and right pointers. Two while loops are utilized; the first loop manages the movement of the right pointer of the window, while the second loop reduces the left pointer once the necessary number of characters in the substring is achieved.

Alternative Answer

In this Java implementation, we create an integer array to keep track of the character frequencies found in the string t . As we expand our window in s and encounter a character that is present in t , we decrease the counter. Once the counter reaches zero, we begin the process of minimizing the window.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Dropbox

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.