Write a program to find the smallest window that contains all characters of string itself
Pattern: Sliding window: variable size
First count how many different characters the string has. Then grow a window until it holds all of them, and shrink it from the left while it still does.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given a non-empty string, return the length of the shortest block of neighbouring characters that contains every
different character of the whole string at least once. For example, "aabcbcdbca" gives 4 ("dbca"), "aaab" gives 2
("ab"), and "abcd" gives 4.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
findSubString is this guide's own, and it returns the length rather than the block itself.
Think first
- Before looking for windows, what do you need to know about the whole string?
- How can you tell, in O(1), whether the window currently holds every character?
- Once the window holds them all, is it worth growing it further?
Hints
Brute force, and why it fails
From each start, extend until every character is present: O(n²) with a running set. The window is O(n).
The key insight
"Holds every character" only gets easier as the window grows, so this is the shortest-window template. A count array and
the have number keep each step O(1).
Dry run
| distinct | 4 |
|---|
s = aabcbcdbca. It uses 4 different characters (a, b, c, d), so a window must hold all 4.
The plan
distinct = number of different characters in s
count = all zeros, have = 0, left = 0, best = n
for right from 0 to n - 1:
if count[s[right]] == 0: have = have + 1
count[s[right]] = count[s[right]] + 1
while have == distinct:
best = min(best, right - left + 1)
count[s[left]] = count[s[left]] - 1
if count[s[left]] == 0: have = have - 1
left = left + 1
return best
Complexity
- Time
O(n)- Space
O(alphabet)
Each edge moves at most n times. The counts need one slot per possible character.
Edge cases
- One character: 1.
- Every character different: the whole string,
n. - One repeated character with a single other, as in
"zzzzaz": 2.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int findSubString(String s) {
int[] count = new int[128];
int distinct = 0;
for (int i = 0; i < s.length(); i++) {
if (count[s.charAt(i)]++ == 0) distinct++; // how many different characters the window must hold
}
Arrays.fill(count, 0);
int have = 0, left = 0, best = s.length();
for (int right = 0; right < s.length(); right++) {
if (count[s.charAt(right)]++ == 0) have++;
while (have == distinct) { // window holds everything: record it and shrink
best = Math.min(best, right - left + 1);
if (--count[s.charAt(left)] == 0) have--;
left++;
}
}
return best;
}
}C++
class Solution {
public:
int findSubString(string s) {
vector<int> count(128, 0);
int distinct = 0;
for (unsigned char c : s) {
if (count[c]++ == 0) distinct++; // how many different characters the window must hold
}
fill(count.begin(), count.end(), 0);
int have = 0, left = 0, best = static_cast<int>(s.size());
for (int right = 0; right < static_cast<int>(s.size()); right++) {
if (count[static_cast<unsigned char>(s[right])]++ == 0) have++;
while (have == distinct) { // window holds everything: record it and shrink
best = min(best, right - left + 1);
if (--count[static_cast<unsigned char>(s[left])] == 0) have--;
left++;
}
}
return best;
}
};Python
class Solution:
def findSubString(self, s: str) -> int:
distinct = len(set(s)) # how many different characters the window must hold
count = {}
left, best = 0, len(s)
for right, c in enumerate(s):
count[c] = count.get(c, 0) + 1
while len(count) == distinct: # window holds everything: record it and shrink
best = min(best, right - left + 1)
old = s[left]
count[old] -= 1
if count[old] == 0:
del count[old]
left += 1
return bestCommon mistakes
- Using the alphabet size (26) instead of the number of different characters actually in
s. - Recording the length after the shrink step instead of before, which records a window that no longer holds everything.
- Raising
haveon every added character instead of only when its count goes from 0 to 1.