codekofi
← All problems

Problem 116

Medium

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

1struct Store {
2
3 vector<int> values;
4 vector<int> mins;
5
6 void push(int x) {
7
8 values.push_back(x);
9
10 if (mins.empty() || x <= mins.back()) {
11 mins.push_back(x);
12 } else {
13 mins.push_back(mins.back());
14 }
15 }
16
17 void pop() {
18 values.pop_back();
19 mins.pop_back();
20 }
21
22 int top() const {
23 return values.back();
24 }
25
26 int best() const {
27 return mins.back();
28 }
29};
30
31vector<string> solution(const vector<string>& ops,
32 const vector<int>& args) {
33
34 Store s;
35 vector<string> ans;
36
37 int n = ops.size();
38
39 for (int i = 0; i < n; i++) {
40
41 if (ops[i] == "push") {
42 s.push(args[i]);
43 ans.push_back("null");
44
45 } else if (ops[i] == "pop") {
46 s.pop();
47 ans.push_back("null");
48
49 } else if (ops[i] == "top") {
50 ans.push_back(to_string(s.top()));
51
52 } else {
53 ans.push_back(to_string(s.best()));
54 }
55 }
56
57 return ans;
58}

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.