Embercode
✕
Stacks and QueuesQuick quiz

Histograms and daily temperatures

8 questions. Covers Daily temperatures and stock span.

Questions 1 to 5 of 8

  1. 1. What does this program print? ``cpp #include <cstddef> #include <iostream> #include <stack> #include <vector> std::vector<int> daily_temperatures(const std::vector<int>& temp) { std::vector<int> answer(temp.size(), 0); std::stack<std::size_t> waiting; for (std::size_t day = 0; day < temp.size(); ++day) { while (!waiting.empty() && temp[waiting.top()] < temp[day]) { std::size_t cold = waiting.top(); waiting.pop(); answer[cold] = static_cast<int>(day - cold); } waiting.push(day); } return answer; } int main() { auto ans = daily_temperatures({30, 20, 25, 28, 26, 31}); for (std::size_t i = 0; i < ans.size(); ++i) std::cout << (i ? " " : "") << ans[i]; std::cout << '\n'; } ``
  2. 2. What does this program print? ``cpp #include <algorithm> #include <cstddef> #include <iostream> #include <stack> #include <vector> long long largest_rectangle(const std::vector<int>& heights) { const int n = static_cast<int>(heights.size()); std::stack<int> waiting; long long best = 0; for (int i = 0; i <= n; ++i) { const int h = (i == n) ? 0 : heights[i]; while (!waiting.empty() && heights[waiting.top()] >= h) { const int bar = waiting.top(); waiting.pop(); const int left = waiting.empty() ? -1 : waiting.top(); const int width = i - left - 1; best = std::max(best, static_cast<long long>(heights[bar]) * width); } if (i < n) { waiting.push(i); } } return best; } int main() { std::cout << largest_rectangle({6, 2, 5, 4, 5, 1, 6}) << '\n'; } ``
  3. 3. The stack version of daily_temperatures is O(n), even though a while loop sits inside the for loop. Why?
  4. 4. The largest-rectangle stack method runs on a row of 6 bars, followed by the extra bar of height 0 that flushes the stack. How many times in total is pop() called on the stack?

    Type a number.

  5. 5. In the largest-rectangle method, a bar's area is computed when the bar is popped, not when it is pushed. Why?

5 question(s) left on this page.

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