Min window substring in JavaScript

We are required to write a JavaScript function that takes in two strings let's call them str1 and str2.

The size of str1 is guaranteed to be greater than that of str2. We are required to find the smallest substring in str1 that contains all the characters contained in str2.

For example ?

If the input strings are ?

const str1 = 'abcdefgh';
const str2 = 'gedcf';

Then the output should be ?

const output = 'cdefg';

because this the smallest consecutive substring of str1 that contains all characters of str2.

Algorithm Overview

The solution uses a brute force approach that generates all possible substrings of str1 and checks if each contains all characters from str2. We track the shortest valid substring found.

Helper Function: subIncludesAll

This function checks if a substring contains all characters from the target string:

const subIncludesAll = (str, str2) => {
    for (let i = 0; i 

true
false

Complete Solution

const str1 = 'abcdefgh';
const str2 = 'gedcf';

const subIncludesAll = (str, str2) => {
    for (let i = 0; i  {
    let shortestString = null;
    
    for (let i = 0; i 

cdefg

How It Works

1. **Outer loop**: Iterates through each starting position in str1

2. **Inner loop**: For each start position, generates substrings of increasing length

3. **Validation**: Uses `subIncludesAll` to check if the current substring contains all characters from str2

4. **Tracking**: Keeps track of the shortest valid substring found so far

Testing with Different Examples

// Test with different inputs
console.log(minWindow('ADOBECODEBANC', 'ABC')); // Expected: 'BANC'
console.log(minWindow('hello world', 'llo'));   // Expected: 'llo'
console.log(minWindow('abcd', 'xyz'));          // Expected: null
BANC
llo
null

Time Complexity

This brute force approach has O(n³) time complexity, where n is the length of str1. For each of the O(n²) substrings, we perform an O(n) check. For large strings, consider using the sliding window technique for O(n) optimization.

Conclusion

The minimum window substring problem can be solved using a brute force approach that checks all possible substrings. While not the most efficient, this solution is easy to understand and works well for smaller strings.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements