Embercode
✕
Maps and Sets (C++)Quick quiz

Frequency windows

7 questions. Covers Sliding window with a frequency map.

Questions 1 to 5 of 7

  1. 1. What does this program print? ``cpp #include <iostream> #include <string> #include <unordered_map> using namespace std; size_t longestAtMostK(const string& s, size_t k) { unordered_map<char, size_t> count; size_t distinct = 0; size_t best = 0; size_t left = 0; for (size_t right = 0; right < s.size(); ++right) { char c = s[right]; if (count[c] == 0) ++distinct; ++count[c]; while (distinct > k) { char out = s[left]; --count[out]; if (count[out] == 0) --distinct; ++left; } size_t length = right - left + 1; if (length > best) best = length; } return best; } int main() { cout << longestAtMostK("abaccc", 2) << "\n"; } ``
  2. 2. Why does the program keep a separate distinct counter instead of using the size of the map?
  3. 3. What is the name of the counter that tracks how many letters in the window have a count above zero?

    Type your answer.

  4. 4. What does this program print? ``cpp #include <iostream> #include <string> #include <unordered_map> using namespace std; long long countAtMostK(const string& s, size_t k) { unordered_map<char, size_t> count; size_t distinct = 0; size_t left = 0; long long total = 0; for (size_t right = 0; right < s.size(); ++right) { char c = s[right]; if (count[c] == 0) ++distinct; ++count[c]; while (distinct > k) { char out = s[left]; --count[out]; if (count[out] == 0) --distinct; ++left; } total += static_cast<long long>(right - left + 1); } return total; } long long countExactlyK(const string& s, size_t k) { return countAtMostK(s, k) - countAtMostK(s, k - 1); } int main() { cout << countExactlyK("aabbb", 2) << "\n"; } ``
  5. 5. For the text aabacbebebe with k set to 2, which window is the longest valid one?

5 question(s) left on this page.

Typed answers ignore extra spaces and, for most questions, capital letters.