Given a string s, find the shortest substring (window) that contains every distinct character that appears in s at least once. Return the substring (or its length).
We can solve this with a sliding-window (two-pointer) technique and a frequency table that tracks how many distinct characters inside the current window have non-zero counts.
If the string has k distinct characters overall, any valid window must contain at least one occurrence of each of those k characters. Expand the right end to include characters until the window contains all k distinct characters, then shrink from the left to remove redundant characters and record the smallest valid window seen.
Precompute k = number of distinct characters in s (by scanning once).
Use an array or map freq to track character counts inside the current window, two pointers l = 0, r = 0, and count = 0 which counts how many distinct characters in the window currently have count >= 1.
Expand r from 0..n-1:
Increment freq[s[r]]; if its new count is 1, increment count.
While count == k, try to shrink the window from the left:
Update best window if current length r-l+1 is smaller.
Decrement freq[s[l]]; if freq[s[l]] becomes 0, decrement count.
Increment l.
At the end best holds the smallest window (or its length).
#include<string>#include<vector>#include<limits>classSolution {
public: std::string smallestWindow(const std::string &s) {
if (s.empty()) return"";
constint ALPHA =256;
std::vector<int> seen(ALPHA, 0);
int distinct =0;
for (unsignedchar c : s) if (seen[c]++==0) ++distinct;
std::vector<int> freq(ALPHA, 0);
int count =0; // distinct characters in window
int l =0;
int bestLen = std::numeric_limits<int>::max();
int bestStart =0;
for (int r =0; r < (int)s.size(); ++r) {
unsignedchar c = s[r];
if (freq[c]++==0) ++count;
while (count == distinct) {
if (r - l +1< bestLen) {
bestLen = r - l +1;
bestStart = l;
}
unsignedchar lc = s[l];
if (--freq[lc] ==0) --count;
++l;
}
}
return bestLen == std::numeric_limits<int>::max() ? std::string() : s.substr(bestStart, bestLen);
}
};
classSolution {
public String smallestWindow(String s) {
if (s ==null|| s.isEmpty()) return"";
finalint ALPHA = 256;
int[] seen =newint[ALPHA];
int distinct = 0;
for (int i = 0; i < s.length(); ++i) if (seen[s.charAt(i)]++== 0) ++distinct;
int[] freq =newint[ALPHA];
int count = 0, l = 0;
int bestLen = Integer.MAX_VALUE, bestStart = 0;
for (int r = 0; r < s.length(); ++r) {
if (freq[s.charAt(r)]++== 0) ++count;
while (count == distinct) {
if (r - l + 1 < bestLen) { bestLen = r - l + 1; bestStart = l; }
if (--freq[s.charAt(l)]== 0) --count;
++l;
}
}
return bestLen == Integer.MAX_VALUE?"" : s.substring(bestStart, bestStart + bestLen);
}
}