Scrivio Interview library
Sliding windowArrays and stringsReported 31 times · 16 min read · updated 14 November 2026

Find the smallest substring of a string that contains every character of another string.

1What the smallest window containing every character means

Imagine a long market street where every stall sells exactly one kind of thing, and the stalls stand side by side in a fixed order. You have a shopping list: one apple, one bread, one cheese. You want to choose a stretch of neighbouring stalls, as short as possible, that between them sell everything on your list. You may not skip a stall in the middle of your stretch; whatever stands between your first and last stall is part of it. That shortest stretch is what this question asks for.

In the question the street is a string s and the shopping list is a string t. A substring is a run of neighbouring characters of s, our stretch of stalls. We want the shortest substring of s that contains every character of t, and repeats count. If t is AAB, the stretch must contain at least two A characters and one B. We will call the stretch we are looking at the window, because we will look at s through it.

PictureADOBECODEBANC and the smallest window holding A, B and C

Indexes are above the boxes. The marked boxes, 9 to 12, spell BANC, the shortest run of neighbours that contains an A, a B and a C.

  1. A0D1O2B3E4C5O6D7E8B9A10N11C12
    s
    ADOBECODEBANC
    t
    ABC
    expected
    BANC, length 4

    1In ADOBECODEBANC, the run ADOBEC at 0 to 5 already holds A, B and C, but BANC at 9 to 12 holds them in only four characters, so BANC is the answer.

What to assume

Is the match case-sensitive?
We assume yes, with plain ASCII characters.
Must repeats in t be matched as repeats?
Yes. If no window exists we return the empty string, and on a tie the first window found.
And how long can s be?
At 100,000 characters, trying every substring is far too slow, so the interviewer hopes for something better.

Let us keep one example all the way through: s = ADOBECODEBANC and t = ABC. Let us look by hand. Starting from the first A at 0, we must walk to 3 to reach a B and to 5 to reach a C, so ADOBEC, length 6, works. Further along there is another stretch, BANC at 9 to 12, with B, A, N and C. It has all three letters in only four characters. Nothing shorter can work, since we need at least three characters and no run of three or four other than BANC covers A, B and C. So the answer is BANC.

A careful candidate asks a few questions first. Is the match case-sensitive? We assume yes, with plain ASCII characters. Must repeats in t be matched as repeats? Yes. If no window exists we return the empty string, and on a tie the first window found. And how long can s be? At 100,000 characters, trying every substring is far too slow, so the interviewer hopes for something better.

If this looks hard, take heart. Everything we will do is what you just did by hand: walk forward until the list is covered, then see how much you can drop from the back.

2How to recognise a sliding window problem

Reading this question for the first time, most of us think of trying every possible start and end, and checking each substring against t. That is a natural first thought, and we will write it in the next section. But first let us read the question slowly and notice what each phrase is telling us.

The first clue is the word substring. A substring is contiguous, which means its characters stand next to each other with nothing skipped. So every candidate answer is fully described by two positions, where it starts and where it ends. Any problem whose answer is one unbroken stretch is described by two indexes, and that is a hint that we can move those indexes cleverly instead of trying every pair.

The second clue is the word smallest, together with contains every character. The condition, contains all of t, behaves in a very helpful way. If a stretch already contains everything, adding one more stall on the right cannot spoil it. And if a stretch does not contain everything, removing a stall from the left cannot fix it. A condition that only gets easier as the stretch grows lets us grow the stretch until it is satisfied, then shrink it until it is about to break.

These clues point to the sliding window pattern. Picture a frame laid over a strip of film. You can move its right edge forward to show more pictures, and its left edge forward to show fewer, but both edges only move forward, from the start of the strip towards the end. The general rule to carry away is this. When a question asks for the longest or shortest contiguous stretch that satisfies a condition you can update one character at a time, keep a window with two indexes, move the right one to grow it and the left one to shrink it, and keep running counts so each move costs a fixed amount of work.

Some patterns look similar but do not fit. Two pointers moving towards each other from both ends, as in checking a palindrome, need a mirror structure, and a substring search has none. Prefix sums answer questions about totals over ranges, not about which characters a range holds. A hash map alone finds pairs, not stretches; here it only helps, as our table of counts.

3The honest first attempt, checking every start

The brute force is the honest attempt anyone would make, and it already contains a good idea. For every start position i, we grow a window to the right one character at a time, keeping counts of what t still needs, and stop as soon as everything is covered. That window is the shortest one starting at i, so we compare it with the best so far and move on to the next start.

It keeps an array need with one slot per character, holding how many copies of each character are still owed, and a number missing that counts the characters still to be found in total. When missing reaches zero, the window from i to j holds all of t.

Java
static String minWindowBrute(String s, String t) {
if (t.isEmpty()) return "";
String best = "";
for (int i = 0; i < s.length(); i++) { // every start
int[] need = new int[128];
for (char c : t.toCharArray()) need[c]++;
int missing = t.length();
for (int j = i; j < s.length(); j++) { // grow the window from i
char c = s.charAt(j);
if (need[c] > 0) missing--;
need[c]--;
if (missing == 0) { // s[i..j] holds all of t
if (best.isEmpty() || j - i + 1 < best.length()) best = s.substring(i, j + 1);
break; // longer windows from i are no use
}
}
}
return best;
}

Let us count on the example. There are 13 starts. From start 0 the window grows to 5, six steps, before it covers ABC. From start 1 it grows to 10, ten steps, and later starts walk similar distances or run off the end without finding a window. Altogether the inner loop runs 74 times for a string of only 13 characters. For n characters there are n starts, and each can walk up to n characters, so the time is O(n^2), read as order n squared. For 100,000 characters that is up to ten billion steps. The space is small, the 128 counts, which is O(1) for a fixed alphabet.

Now let us find the waste. From start 1 we walked all the way to 10. From start 2 we walk over 2 to 10 again, from start 3 over 3 to 10 again, and so on. Every new start throws away its counts and recounts almost the same characters, though only one character, the one at the old start, has left the window.

So let us ask the question that leads forward. Instead of starting over, could we remove just that one character from our counts and carry on from where the right end already is? We can, and that is the whole sliding window.

4Getting to a window that grows and shrinks

We keep the same two tools as the brute force. need[c] starts as the number of copies of c in t, and from then on it means how many more copies of c the window still owes. A value of 0 means the window has exactly enough, and a negative value means it has spare copies. missing starts at the length of t and counts how many owed characters are still not in the window.

The right index walks through s once, adding one character at a time. When it adds a character c, we first look at need[c]. If it is above zero, this copy was owed, so missing goes down by one. Then we lower need[c] by one either way. That second step matters even for characters not in t, such as D, whose need simply becomes negative and never matters again.

When missing reaches zero, the window holds all of t, and we switch to shrinking. We record the window if it is the shortest so far. Then we drop the character at left: we raise need for it by one, and if need becomes above zero, that copy was required, so missing goes up and the window is no longer valid. Then left moves one step. We repeat this as long as missing stays zero.

Now the question that worries beginners. Why may left only move forward, never back? Suppose the window from left to right was valid and we shrank it until dropping one more character broke it. Could a better answer start before left? Any window starting earlier and ending at right or later contains a window we have already recorded, so it is at least as long. And for any later right, starting earlier only makes the window longer. So nothing behind left can ever give a shorter answer, and left never needs to go back.

The second beginner question is why need may go negative. Look at the B at 9 in our example. When it is added, the B at 3 is still inside, so the new B is a spare and need[B] goes to -1. Later, when left drops the B at 3, need[B] rises only to 0, not above, so missing does not change and the window stays valid, because the B at 9 still covers it. A simple set of required letters could not tell these two copies apart, which is the most common mistake on this problem. Counting copies is what lets the window give up a spare without fuss.

5Watching the window on ADOBECODEBANC

The picture runs the real loop on s = ADOBECODEBANC and t = ABC. The marked boxes are the window, from left to right, and the box right has just added is shown as compared. The panel shows need for A, B and C, missing, the window and the best window recorded so far. Some frames gather several steps where nothing interesting happens, such as adding letters that are not in t.

Watch the rhythm. right moves until missing is 0, then left moves until missing is 1 again, over and over, and both only ever move forward.

Step throughThe window growing and shrinking over ADOBECODEBANC

Marked boxes are the current window, from left to right; the compared box is the character right has just added. need shows what the window still owes for A, B and C; a negative number is a spare copy.

  1. A0D1O2B3E4C5O6D7E8B9A10N11C12left
    need
    A 1, B 1, C 1
    missing
    3
    window
    empty
    best
    none

    1Before the loop, need says the window owes one A, one B and one C, and missing is 3. left is 0 and the window is still empty.

  2. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B 1, C 1
    missing
    2
    window
    A
    best
    none

    2right = 0 adds A. need[A] was 1, so this A was owed: missing drops to 2 and need[A] becomes 0.

  3. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B 0, C 1
    missing
    1
    window
    ADOB
    best
    none

    3D and O are not in t, so they change nothing that matters. right = 3 adds B, which was owed, so missing drops to 1.

  4. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B 0, C 0
    missing
    0, valid
    window
    ADOBEC
    best
    none yet

    4right = 5 adds C, the last owed character, so missing is 0. The window ADOBEC, 0 to 5, holds all of t for the first time.

  5. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 1, B 0, C 0
    missing
    1
    window
    DOBEC
    best
    ADOBEC (6)

    5Valid, so we shrink. We record ADOBEC, length 6, as best, then drop the A at 0. need[A] becomes 1, so missing is 1 and the shrinking stops.

  6. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 1, B -1, C 0
    missing
    1
    window
    DOBECODEB
    best
    ADOBEC (6)

    6right moves over O, D, E and B at 6 to 9. The B is a spare copy, because the B at 3 is still inside, so need[B] goes to -1.

  7. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B -1, C 0
    missing
    0, valid
    window
    DOBECODEBA
    best
    ADOBEC (6)

    7right = 10 adds A, which was owed, so missing is 0 again. The window 1 to 10 is valid, but at length 10 it is no record.

  8. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B 0, C 0
    missing
    0
    window
    CODEBA
    best
    ADOBEC (6)

    8Shrinking drops D, O, B and E. The B was spare, because need[B] was -1, so the window stays valid. left reaches 5, and CODEBA, length 6, does not beat 6.

  9. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B 0, C 1
    missing
    1
    window
    ODEBA
    best
    ADOBEC (6)

    9Dropping the C at 5 makes need[C] 1, so missing is 1 and the window is no longer valid. left is 6 and we go back to growing.

  10. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B 0, C 0
    missing
    0, valid
    window
    ODEBANC
    best
    ADOBEC (6)

    10right adds N, a spare, then C at 12, which was owed. missing is 0, and the window ODEBANC, 6 to 12, is valid again at length 7.

  11. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B 0, C 0
    missing
    0, valid
    window
    BANC
    best
    BANC (4)

    11Shrinking drops O and D, both spare. EBANC, length 5, beats 6 and is recorded; then E is dropped and BANC, length 4, is recorded too.

  12. A0D1O2B3E4C5O6D7E8B9A10N11C12leftright
    need
    A 0, B 1, C 0
    missing
    1
    best
    BANC (4)
    returns
    BANC

    12Dropping the B at 9 makes need[B] 1, so missing is 1 and shrinking stops. right is at the end, so the loop ends and we return BANC.

Let us read the turning points back. In the fourth frame the window first becomes valid at ADOBEC, and in the fifth we record it and drop the A, which breaks it at once. In the sixth frame the B at 9 arrives as a spare, need[B] = -1. That pays off in the eighth frame, when the B at 3 is dropped and the window stays valid.

In the last three frames C at 12 makes the window valid again. Shrinking then drops O and D, records EBANC at length 5, drops E, and records BANC at length 4. Dropping the B at 9 finally breaks it, and since right is at the end, we return BANC. right moved 13 times and left 10 times, 23 moves in all, against 74 inner steps for the brute force.

6The complete Java program

Here is the whole method with a main that runs our example, a case where the whole string is the answer, a case with no answer, and a sentence where t has a repeated letter. Each comment shows what that line prints.

Java
public class MinWindow {
// Smallest substring of s that contains every character of t, counting repeats.
static String minWindow(String s, String t) {
if (t.isEmpty() || s.length() < t.length()) return "";
int[] need = new int[128]; // how many of each char the window still owes
for (char c : t.toCharArray()) need[c]++;
int missing = t.length(); // chars of t not yet covered by the window
int bestStart = 0, bestLen = Integer.MAX_VALUE;
int left = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (need[c] > 0) missing--; // this char was still owed
need[c]--; // negative means a spare copy
while (missing == 0) { // window is valid: try to shrink it
if (right - left + 1 < bestLen) {
bestLen = right - left + 1;
bestStart = left;
}
char out = s.charAt(left);
need[out]++;
if (need[out] > 0) missing++; // we just gave up a required char
left++;
}
}
return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + bestLen);
}
public static void main(String[] args) {
System.out.println(minWindow("ADOBECODEBANC", "ABC")); // BANC
System.out.println(minWindow("aa", "aa")); // aa
System.out.println("[" + minWindow("a", "aa") + "]"); // []
System.out.println(minWindow("this is a test string", "tist")); // t stri
}
}

Let us read minWindow in the order it runs. The first line returns the empty string if t is empty or s is shorter than t, since no window can exist then. need is an int array of 128 slots, one per ASCII character, and the loop over t fills it with the counts. missing starts at t.length(). bestStart and bestLen remember the best window, and bestLen starts at Integer.MAX_VALUE, a value larger than any real length, so the first valid window always beats it.

The for loop moves right over every position. For the character c at right, if (need[c] > 0) missing-- counts it as owed, and need[c]-- records that the window now holds one more. Then while (missing == 0) shrinks. Inside it we first compare right - left + 1, the window length, with bestLen, and record bestStart and bestLen if it is shorter. Then we take out, the character at left, raise need[out], and if need[out] > 0 we have given up a required copy, so missing goes up. Finally left++ moves the left edge.

Notice that we only remember where the best window starts and how long it is, and call s.substring once at the end, so the loop never copies characters. If bestLen is still Integer.MAX_VALUE, no window was valid and we return the empty string. That is why main prints [] for s = a and t = aa: missing never reaches zero.

7How much it costs, and the cases at the edges

Let us count on the example first. right moved 13 times, once per character, and left moved 10 times. Each move did a fixed amount of work, a couple of array updates and comparisons. For a string s of n characters, right moves n times, and left only moves forward and never passes right, so it also moves at most n times across the whole run. That is at most 2n moves. Filling need from t takes m steps, where m is the length of t, so the time is O(n + m).

The space is the need array, 128 ints whatever the input size, so the extra space is O(1) for a fixed alphabet. For full Unicode a HashMap of counts would take its place.

Comparing the approaches
ApproachTimeExtra space
Every substring, counted from scratchO(n^3)O(1) for ASCII
Every start, grown with running countsO(n^2)O(1) for ASCII
Sliding window with need and missingO(n + m)O(1) for ASCII

The edge cases come out of the code. An empty t or an s shorter than t returns the empty string at the first line. A t containing a character that s lacks never brings missing to zero, so bestLen stays at Integer.MAX_VALUE and we return the empty string. Repeated characters in t, such as the two t characters in tist, work because need counts copies, so the answer for this is a test string is t stri, which holds both t characters, an i and an s. When s equals t, as in aa and aa, the whole string is the answer.

The mistake to watch for is updating missing on the wrong side of need. When adding, check need[c] > 0 before lowering it; when dropping, raise need[out] first and then check. Swap either order and spare copies count as required.

8Follow-up questions

Why is a set of required characters not enough?

A set only says whether a character is needed, not how many copies. If t is AAB, a set holds A and B, and a window with one A and one B would wrongly look complete. And even when t has no repeats, the window often holds spare copies, as with the two B characters in our example. With counts, dropping the spare B leaves need[B] at 0 and the window stays valid. With a set, we would have no way to know whether the B we dropped was the last one.

How is this different from the longest substring without repeating characters?

Both use the same window that only moves forward, but the condition is the other way round. There, the window is valid while it has no repeats, and adding a character can break it, so we shrink until it is valid again and record the longest valid window. Here, the window becomes valid by adding characters, so we shrink while it stays valid and record the shortest. A good way to remember it is to ask whether growing the window helps or hurts the condition.

Could you make it faster when s is huge and only a few of its characters appear in t?

Yes. We first collect the positions in s whose character appears in t and run the same window over that shorter list, so both ends jump straight between useful characters. The worst case is still O(n + m), but when most of s is irrelevant the loop runs far fewer times.

9Conclusion

We found the smallest window by growing it with right until it held all of t and shrinking it with left while it stayed valid, with need counting what is owed and missing saying at once when the window is complete, in O(n + m) time and O(1) space for ASCII. The clue to remember is a shortest or longest contiguous stretch under a condition updated one character at a time: walk the market street with a window and a tally, adding stalls on the right and dropping them from the left.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the rules: the match is case-sensitive, repeated characters in t must be matched as repeats, and I return the empty string if no window exists.

Then, if they want more

Trying every start and growing a window from each works, but it recounts almost the same characters for every start, which is O(n squared). Since the answer is a contiguous stretch and containing all of t only gets easier as the stretch grows, I use a sliding window.

I keep need, an int array of 128 counts filled from t, meaning how many of each character the window still owes, and missing, the total still owed. I move right across s; when the added character's need is positive it was owed, so missing goes down, and I decrement need either way, so spare copies go negative.

While missing is zero the window is valid, so I record it if it is the shortest, then drop the character at left by incrementing its need, and if that need becomes positive, missing goes up.

Both indexes only move forward, so it is O(n + m) time and O(1) space for ASCII, and I build the substring once at the end.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 31 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the smallest substring of a string that contains every character of another string.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-smallest-substring-of-a-string-that-contains-every-char-31993c/