codekofi
← All problems

Problem 149

Hard

1 · Worked examples

0 / 4

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 4 outputs correctly.

The accepted solution

1string solution(const string& text, const string& need) {
2
3 if (need.empty() || text.size() < need.size()) {
4 return "";
5 }
6
7 map<char, int> want;
8
9 for (char c : need) {
10 want[c]++;
11 }
12
13 int missing = need.size();
14 int n = text.size();
15
16 int bestStart = 0;
17 int bestLen = INT_MAX;
18 int left = 0;
19
20 for (int right = 0; right < n; right++) {
21
22 want[text[right]]--;
23
24 if (want[text[right]] >= 0) {
25 missing--;
26 }
27
28 while (missing == 0) {
29
30 int width = right - left + 1;
31
32 if (width < bestLen) {
33 bestLen = width;
34 bestStart = left;
35 }
36
37 want[text[left]]++;
38
39 if (want[text[left]] > 0) {
40 missing++;
41 }
42
43 left++;
44 }
45 }
46
47 if (bestLen == INT_MAX) {
48 return "";
49 }
50
51 return text.substr(bestStart, bestLen);
52}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.