This is one of those problems where the clean idea matters more than the amount of code. For 1115. Print FooBar Alternately, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are foo, bar.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 336 ms, faster than 62.59% of C++ online submissions for Print FooBar Alternately.
02//Memory Usage: 10.5 MB, less than 100.00% of C++ online submissions for Print FooBar Alternately.
03class FooBar {
04private:
05 int n;
06 mutex mtx;
07 condition_variable cv;
08 bool isFoo;
09
10public:
11 FooBar(int n) {
12 this->n = n;
13 this->isFoo = true;
14 }
15
16 void foo(function<void()> printFoo) {
17
18 for (int i = 0; i < n; i++) {
19 unique_lock<mutex> lck(mtx);
20 cv.wait(lck, [this](){return isFoo;});
21 // printFoo() outputs "foo". Do not change or remove this line.
22 printFoo();
23 isFoo = false;
24 cv.notify_all();
25 }
26 }
27
28 void bar(function<void()> printBar) {
29
30 for (int i = 0; i < n; i++) {
31 unique_lock<mutex> lck(mtx);
32 cv.wait(lck, [this](){return !isFoo;});
33 // printBar() outputs "bar". Do not change or remove this line.
34 printBar();
35 isFoo = true;
36 cv.notify_all();
37 }
38 }
39};
Cost