question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
print-foobar-alternately
Easy to understand java solution
easy-to-understand-java-solution-by-ctap-ijtl
\nclass FooBar {\n private int n;\n int bar = 0;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throw
ctapal
NORMAL
2021-03-08T04:17:19.032804+00:00
2021-03-08T04:18:06.224586+00:00
463
false
```\nclass FooBar {\n private int n;\n int bar = 0;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n \n for (int i = 0; i < n; i++) {\n synchronized(this) {\n if(bar == 1) {\n wait();\n }\n\n // printFoo.run() outputs "foo". Do not change or remove this line.\n printFoo.run();\n bar=1;\n notify();\n }\n }\n }\n \n\n public void bar(Runnable printBar) throws InterruptedException {\n \n \n for (int i = 0; i < n; i++) {\n synchronized(this) {\n if(bar==0) {\n wait();\n }\n\n // printBar.run() outputs "bar". Do not change or remove this line.\n printBar.run();\n bar = 0;\n notify();\n }\n }\n }\n}\n```
4
1
['Java']
0
print-foobar-alternately
Using semaphore java
using-semaphore-java-by-parthanemo123-ew2k
class FooBar {\n private int n;\n\n Semaphore s1 = new Semaphore(1);\n Semaphore s2 = new Semaphore(0);\n \n public FooBar(int n) {\n this
parthanemo123
NORMAL
2021-02-22T11:49:25.467732+00:00
2021-02-22T11:49:25.467822+00:00
273
false
class FooBar {\n private int n;\n\n Semaphore s1 = new Semaphore(1);\n Semaphore s2 = new Semaphore(0);\n \n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n s1.acquire();\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n s2.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n s2.acquire();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n s1.release();\n }\n }\n}
4
0
[]
1
print-foobar-alternately
[Java] A few Easy-to-understand Solutions with Explanation
java-a-few-easy-to-understand-solutions-l9cx0
1. Using Semaphore\nA Semaphore manages a set of virtual permits; the initial number of permits is passed to the Semaphore constructor. Activities can acqui
isaacjumac
NORMAL
2020-07-29T10:50:45.710768+00:00
2020-07-29T11:15:03.271467+00:00
277
false
## 1. Using Semaphore\nA `Semaphore` manages a set of virtual permits; the initial number of permits is passed to the Semaphore constructor. Activities can `acquire` permits (as long as some remain) and `release` permits when they are done with them. If no permit is available, acquire blocks until one is (or until interrupted or the operation times out). The `release` method returns a permit to the semaphore. (from the book [Java Concurrency in Practice](https://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601))\n\nWe can use 2 Semaphores, one for each method. Each method will try to acquire its own semaphore permit before it proceed to the actual execution in each iteration. And after each method finishes a iteration, it will release a semaphore permit the other method is waiting for so that the other method can follow its execution.\n\nSolution is like below.\n```\nclass FooBar {\n private int n;\n private static Semaphore s1;\n private static Semaphore s2;\n public FooBar(int n) {\n this.n = n;\n s1 = new Semaphore(1); // give s1 a permit so that foo() can start first\n s2 = new Semaphore(0);\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n s1.acquire();\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n s2.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n s2.acquire();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n s1.release();\n }\n }\n}\n```\n\n## 2. Use Java\'s intrinsic lock (*synchronized*) and a *volatile* flag\nBecause we need alternative execution, we can use the intrinsic lock on the shared obect (`this` in this case) and release the lock to each other in each iteration using `wait()` and `notify()`.\n\nOnly being able to execute alternatively is not enough -- we also need to make sure` foo()` always starts first. Of course, we can use a flag value to control the execution condition and update the value in one thread to satisfy the execution condition of the other. This requries the value update to be visible to both threads. We can simply use the `volatile` keyword to achieve the visibility.\n\nThus, we have the below solution:\n```\nclass FooBar {\n private int n;\n private static volatile int flag;\n public FooBar(int n) {\n this.n = n;\n this.flag = 1;\n }\n\n public synchronized void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n while (flag != 1) {\n wait(); // wait until the flag is 1\n } \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n flag++; // set condition for bar() execution\n notify(); // notify wiating thread (which is bar() thread in this case)\n }\n }\n\n public synchronized void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n while(flag != 2) {\n wait(); // wait until the flag is 2\n }\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n flag--; // set condition for foo() execution\n notify(); // notify wiating thread (which is foo() thread in this case)\n }\n }\n}\n```\n\nActually, we don\'t need to check the execution condition in every iteration, as we only need to make sure `foo()` starts first in the process (which is a one-time event). So, we can change the solution like below to avoid the unnecessary processing for the flag value:\n```\nclass FooBar {\n private int n;\n private static volatile int flag;\n public FooBar(int n) {\n this.n = n;\n this.flag = 1;\n }\n\n public synchronized void foo(Runnable printFoo) throws InterruptedException {\n flag++; // allow bar to execute\n for (int i = 0; i < n; i++) {\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n notify(); // notify bar() thread to proceed\n wait();\n }\n notify(); // allow bar() to exit waiting state and finish\n }\n\n public synchronized void bar(Runnable printBar) throws InterruptedException {\n // This is the condition that must be met when bar executes for the first time\n // In case bar get hold on the intrinsic lock first when the whole process starts,\n // it needs to relinquish the lock for foo to start first\n if(flag != 2){\n notify(); // allow foo() to start asap. makes a difference in the running time (maybe the driver program uses timed waiting to give initial execution some delay so notify() here helps to wake up the thread asap)\n wait(); // relinquish lock for foo() to run first\n }\n for (int i = 0; i < n; i++) {\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n notify(); // notify foo() thread to proceed\n wait(); \n }\n }\n}\n```\n\n## 3. Other Utility Classes\nThere are of course other utility classes you can use to achieve the same effect (`CountDownLatch` `CyclicBarrier`, or even a `Lock` implementation of your own).\n\nJust another solution using `CountDownLatch` below:\n```\nclass FooBar {\n private int n;\n private static CountDownLatch barLatch;\n public FooBar(int n) {\n this.n = n;\n this.barLatch = new CountDownLatch(2);\n }\n\n public synchronized void foo(Runnable printFoo) throws InterruptedException {\n barLatch.countDown(); // count down once at the start\n for (int i = 0; i < n; i++) {\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n notify(); // notify bar() thread to proceed\n wait();\n }\n notify(); // allow bar to exit the final iteration\n }\n\n public synchronized void bar(Runnable printBar) throws InterruptedException {\n\t\tbarLatch.countDown(); // count down once at the start\n barLatch.await(); // wait the latch to count down to 0, i.e., both countDown() happens, which ensures foo() loop to be executed first\n for (int i = 0; i < n; i++) {\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n notify(); // notify foo() thread to proceed\n wait(); \n }\n }\n}\n```
4
0
[]
0
print-foobar-alternately
Python 3 solution using threading.Condition()
python-3-solution-using-threadingconditi-2tv3
The class FooBar is equipped with a threading.Condition() and a flag variable last_printed which is initialized as None. The foo() method waits until last_print
khpeek
NORMAL
2019-08-19T00:02:18.577090+00:00
2019-08-19T00:02:18.577122+00:00
229
false
The class `FooBar` is equipped with a `threading.Condition()` and a flag variable `last_printed` which is initialized as `None`. The `foo()` method waits until `last_printed` is either `None` or `\'bar\'`, while the `bar()` method waits until `last_printed` is `\'foo\'` (cf. https://docs.python.org/3/library/threading.html#condition-objects).\n\n```python\nimport threading\nfrom typing import Callable, Optional\n\n\nclass FooBar:\n def __init__(self, n: int) -> None:\n self.n = n\n self.condition = threading.Condition()\n self.last_printed: Optional[str] = None\n\n def foo(self, printFoo: Callable[[], None]) -> None:\n for i in range(self.n):\n with self.condition:\n self.condition.wait_for(lambda: self.last_printed in (None, \'bar\'))\n printFoo()\n self.last_printed = \'foo\'\n self.condition.notify()\n\n def bar(self, printBar: Callable[[], None]) -> None:\n for i in range(self.n):\n with self.condition:\n self.condition.wait_for(lambda: self.last_printed == \'foo\')\n printBar()\n self.last_printed = \'bar\'\n self.condition.notify()\n```
4
0
[]
1
print-foobar-alternately
Python2 clear
python2-clear-by-my_little_airport-9e42
\nimport threading\nclass FooBar(object):\n def __init__(self, n):\n self.n = n\n self.f = threading.Semaphore()\n self.b = threading.Se
my_little_airport
NORMAL
2019-07-12T01:49:30.732060+00:00
2019-07-12T01:49:30.732095+00:00
721
false
```\nimport threading\nclass FooBar(object):\n def __init__(self, n):\n self.n = n\n self.f = threading.Semaphore()\n self.b = threading.Semaphore()\n self.b.acquire()\n\n def foo(self, printFoo):\n """\n :type printFoo: method\n :rtype: void\n """\n for i in xrange(self.n):\n self.f.acquire()\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.b.release()\n\n\n def bar(self, printBar):\n """\n :type printBar: method\n :rtype: void\n """\n for i in xrange(self.n):\n self.b.acquire()\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.f.release()\n```
4
0
[]
2
print-foobar-alternately
📥 | Simple chanel solution | 100%
simple-chanel-solution-100-by-makarkanan-1xtk
\ntype FooBar struct {\n\tn int\n ch1 chan struct{}\n ch2 chan struct{}\n}\n\nfunc NewFooBar(n int) *FooBar {\n\treturn &FooBar{\n n: n,\n c
makarkananov
NORMAL
2024-06-04T19:23:00.132395+00:00
2024-06-04T19:23:00.132423+00:00
690
false
```\ntype FooBar struct {\n\tn int\n ch1 chan struct{}\n ch2 chan struct{}\n}\n\nfunc NewFooBar(n int) *FooBar {\n\treturn &FooBar{\n n: n,\n ch1: make(chan struct{}, 1),\n ch2: make(chan struct{}, 1),\n }\n}\n\nfunc (fb *FooBar) Foo(printFoo func()) {\n\tfor i := 0; i < fb.n; i++ {\n fb.ch1 <- struct{}{}\n\t\t// printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n fb.ch2 <- struct{}{}\n\t}\n}\n\nfunc (fb *FooBar) Bar(printBar func()) {\n\tfor i := 0; i < fb.n; i++ {\n <-fb.ch2\n\t\t// printBar() outputs "bar". Do not change or remove this line.\n printBar()\n <-fb.ch1\n\t}\n}\n```
3
0
['Concurrency', 'Go']
0
print-foobar-alternately
C# AutoResetEvent
c-autoresetevent-by-abicah-ac89
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
abicah
NORMAL
2023-03-02T13:57:21.591644+00:00
2023-03-02T13:57:21.591707+00:00
261
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nusing System.Threading;\npublic class FooBar {\n private int n;\n\n AutoResetEvent auto=new AutoResetEvent(false);\n AutoResetEvent auto2=new AutoResetEvent(false);\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void Foo(Action printFoo) {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n auto.Set();\n auto2.WaitOne();\n }\n }\n\n public void Bar(Action printBar) {\n \n \n for (int i = 0; i < n; i++) {\n auto.WaitOne();\n // printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n auto2.Set();\n }\n }\n}\n```
3
0
['C#']
0
print-foobar-alternately
🔥 All Language in Leetcode Solution with Mutex
all-language-in-leetcode-solution-with-m-8chn
C++\n\n#include<semaphore.h>\n\nclass FooBar {\nprivate:\n int n;\n sem_t F, B;\n\npublic:\n FooBar(int n) {\n this->n = n;\n sem_init(&F
joenix
NORMAL
2022-05-27T00:46:53.463406+00:00
2022-05-27T00:47:44.026322+00:00
950
false
***C++***\n```\n#include<semaphore.h>\n\nclass FooBar {\nprivate:\n int n;\n sem_t F, B;\n\npublic:\n FooBar(int n) {\n this->n = n;\n sem_init(&F, 0, 0);\n sem_init(&B, 0, 1);\n }\n\n void foo(function<void()> printFoo) {\n for (int i = 0; i < n; i++) {\n sem_wait(&B);\n \tprintFoo();\n sem_post(&F);\n }\n }\n\n void bar(function<void()> printBar) {\n for (int i = 0; i < n; i++) {\n sem_wait(&F);\n printBar();\n sem_post(&B);\n }\n }\n};\n```\n\n***Java***\n```\nclass FooBar {\n private int n;\n\n private Semaphore F = new Semaphore(1);\n private Semaphore B = new Semaphore(0);\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n F.acquire();\n \tprintFoo.run();\n B.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n B.acquire();\n \tprintBar.run();\n F.release();\n }\n }\n}\n```\n\n***Python***\n```\nimport threading\nclass FooBar(object):\n def __init__(self, n):\n self.n = n\n self.F = threading.Semaphore(1)\n self.B = threading.Semaphore(0)\n\n def foo(self, printFoo):\n for i in xrange(self.n):\n self.F.acquire()\n printFoo()\n self.B.release()\n\n def bar(self, printBar):\n for i in xrange(self.n):\n self.B.acquire()\n printBar()\n self.F.release()\n```\n\n***python3***\n```\nimport threading \nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.F = threading.Semaphore(1)\n self.B = threading.Semaphore(0)\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.F.acquire()\n printFoo()\n self.B.release()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.B.acquire()\n printBar()\n self.F.release()\n```\n\n***C***\n```\ntypedef struct {\n int n;\n sem_t F;\n sem_t B;\n} FooBar;\n\nFooBar* fooBarCreate(int n) {\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n obj->n = n;\n sem_init(&(obj->F), 0, 0);\n sem_init(&(obj->B), 0, 1);\n return obj;\n}\n\nvoid foo(FooBar* obj) {\n for (int i = 0; i < obj->n; i++) {\n sem_wait(&(obj->B));\n printFoo();\n sem_post(&(obj->F));\n }\n}\n\nvoid bar(FooBar* obj) {\n for (int i = 0; i < obj->n; i++) {\n sem_wait(&(obj->F));\n printBar();\n sem_post(&(obj->B));\n }\n}\n\nvoid fooBarFree(FooBar* obj) {\n sem_destroy(&(obj->B));\n sem_destroy(&(obj->F));\n free(obj);\n}\n```\n\n***C#***\n```\nusing System.Threading;\npublic class FooBar {\n private int n;\n private SemaphoreSlim F = new SemaphoreSlim(1);\n private SemaphoreSlim B = new SemaphoreSlim(0);\n\n public FooBar(int n)\n {\n this.n = n;\n }\n\n public void Foo(Action printFoo)\n {\n for (int i = 0; i < n; i++)\n {\n F.Wait();\n printFoo();\n B.Release();\n }\n }\n\n public void Bar(Action printBar)\n {\n for (int i = 0; i < n; i++)\n {\n B.Wait();\n printBar();\n F.Release();\n }\n }\n}\n```
3
0
['C', 'Python', 'Java', 'Python3']
0
print-foobar-alternately
[Java] Solution using Semaphore
java-solution-using-semaphore-by-imohann-raas
Using Semaphore, we want two threads to run n times. Each time, the thread \'foo\' will acquire the semaphore and the print foo, then the other thread \'bar\' w
imohannad
NORMAL
2021-04-17T08:25:46.451633+00:00
2021-04-17T08:27:06.305473+00:00
220
false
Using Semaphore, we want two threads to run n times. Each time, the thread \'foo\' will acquire the semaphore and the print foo, then the other thread \'bar\' would acquire the semaphore and print \'bar\'. Once we do this n times, both threads will end at the same time. \n\n\n\n\'\'\'\nclass FooBar \n{\n\n\tprivate int n;\n\tSemaphore s_bar = new Semaphore(0);\n\tSemaphore s_foo = new Semaphore(1);\n\tpublic FooBar(int n) {\n\t\tthis.n = n;\n\t}\n\t\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n s_foo.acquire();\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n s_bar.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n s_bar.acquire();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n s_foo.release();\n }\n }\n}\n
3
0
[]
0
print-foobar-alternately
[Java] Just volatile
java-just-volatile-by-jokersun-0w9w
\nclass FooBar {\n \n\tprivate final int n;\n \n private volatile boolean flag;\n\n public FooBar(int n) {\n this.flag = false;\n this
jokersun
NORMAL
2021-02-15T12:13:32.286425+00:00
2021-02-15T12:13:32.286450+00:00
215
false
```\nclass FooBar {\n \n\tprivate final int n;\n \n private volatile boolean flag;\n\n public FooBar(int n) {\n this.flag = false;\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n while(flag){\n Thread.yield();\n }\n \tprintFoo.run();\n flag = true;\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n while(!flag){\n Thread.yield();\n }\n \tprintBar.run();\n flag = false;\n }\n }\n}\n```
3
0
[]
0
print-foobar-alternately
Java | ReentrantLock with Condition
java-reentrantlock-with-condition-by-one-yqc0
\nclass FooBar {\n private int n;\n \n Lock lock = new ReentrantLock();\n Condition fooCondition = lock.newCondition();\n volatile boolean isFoo
onesubhadip
NORMAL
2020-09-17T11:03:07.101610+00:00
2020-09-17T11:03:07.101655+00:00
184
false
```\nclass FooBar {\n private int n;\n \n Lock lock = new ReentrantLock();\n Condition fooCondition = lock.newCondition();\n volatile boolean isFoo = true;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n lock.lock();\n try{\n while(!isFoo) fooCondition.await();\n // printFoo.run() outputs "foo". Do not change or remove this line.\n \t printFoo.run();\n isFoo = false;\n fooCondition.signal();\n }finally{\n lock.unlock();\n } \n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n lock.lock();\n try{\n while(isFoo) fooCondition.await();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \t printBar.run();\n isFoo = true;\n fooCondition.signal();\n }finally{\n lock.unlock();\n } \n }\n }\n}\n```
3
0
[]
2
print-foobar-alternately
C++ mutex and condition_variable
c-mutex-and-condition_variable-by-ayilma-xzfr
Semaphore implementation with mutex and condition variable from stack overflow. For the people who don\'t want to use posix semaphores.\n\nclass Semaphore {\npu
ayilmaz81
NORMAL
2020-08-26T16:25:41.692687+00:00
2020-08-26T16:25:41.692735+00:00
629
false
Semaphore implementation with mutex and condition variable from stack overflow. For the people who don\'t want to use posix semaphores.\n```\nclass Semaphore {\npublic:\n Semaphore (bool towait_)\n : towait(towait_) {}\n\n inline void notify()\n {\n std::unique_lock<std::mutex> lock(mtx);\n towait = false;\n cv.notify_one();\n }\n\n inline void wait()\n {\n std::unique_lock<std::mutex> lock(mtx);\n cv.wait(lock,[&](){return !towait;});\n towait = true;\n }\n\nprivate:\n std::mutex mtx;\n std::condition_variable cv;\n bool towait;\n};\n\nclass FooBar {\nprivate:\n int n;\n Semaphore semFoo{false};\n Semaphore semBar{true}; \npublic:\n FooBar(int n) {\n this->n = n;\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n semFoo.wait();\n printFoo();\n semBar.notify();\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n semBar.wait(); \n \tprintBar();\n semFoo.notify();\n }\n }\n};\n```
3
0
['C']
1
print-foobar-alternately
C# Using Interlocked and SpinWait faster than 100.00% less than 85.61% memory
c-using-interlocked-and-spinwait-faster-bjnf9
Runtime: 44 ms\nMemory Usage: 16.7 MB\n\n\nusing System.Threading;\npublic class FooBar\n{\n private readonly int n;\n volatile int foo = 0;\n volatile
arslang
NORMAL
2020-08-16T14:55:39.650189+00:00
2020-08-16T15:04:56.814545+00:00
408
false
Runtime: 44 ms\nMemory Usage: 16.7 MB\n\n```\nusing System.Threading;\npublic class FooBar\n{\n private readonly int n;\n volatile int foo = 0;\n volatile int bar = 1;\n SpinWait spinWait = new SpinWait();\n\n public FooBar(int n)\n {\n this.n = n;\n }\n\n public void Foo(Action printFoo)\n {\n for (int i = 0; i < n; i++)\n {\n while (Interlocked.CompareExchange(ref foo, 1, 0) != 0) {spinWait.SpinOnce();}\n printFoo();\n Interlocked.Exchange(ref bar, 0);\n }\n }\n\n public void Bar(Action printBar)\n {\n for (int i = 0; i < n; i++)\n {\n while (Interlocked.CompareExchange(ref bar, 1, 0) != 0) {spinWait.SpinOnce();}\n printBar();\n Interlocked.Exchange(ref foo, 0);\n }\n }\n}\n```\n
3
0
[]
3
print-foobar-alternately
Using simple semaphores in Java
using-simple-semaphores-in-java-by-naman-jljj
\nclass FooBar {\n private int n;\n private Semaphore foo_s = new Semaphore(1);\n private Semaphore bar_s = new Semaphore(0); \n \n\n public FooB
namandeept
NORMAL
2020-03-18T12:51:18.279529+00:00
2020-03-18T12:51:18.279563+00:00
133
false
```\nclass FooBar {\n private int n;\n private Semaphore foo_s = new Semaphore(1);\n private Semaphore bar_s = new Semaphore(0); \n \n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n foo_s.acquire();\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n bar_s.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n bar_s.acquire(); \n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n foo_s.release();\n }\n }\n}\n```
3
0
[]
1
print-foobar-alternately
Easy C# Solution with 2 AutoResetEvents
easy-c-solution-with-2-autoresetevents-b-mdti
\nusing System.Threading; \n\npublic class FooBar\n {\n private int n;\n private readonly AutoResetEvent _fooEventWaitHandle;\n priva
maxpushkarev
NORMAL
2020-01-11T06:00:34.973935+00:00
2020-01-11T06:54:54.729369+00:00
246
false
```\nusing System.Threading; \n\npublic class FooBar\n {\n private int n;\n private readonly AutoResetEvent _fooEventWaitHandle;\n private readonly AutoResetEvent _barEventWaitHandle;\n\n public FooBar(int n)\n {\n this.n = n;\n _fooEventWaitHandle = new AutoResetEvent(true);\n _barEventWaitHandle = new AutoResetEvent(false);\n }\n\n public void Foo(Action printFoo)\n {\n\n for (int i = 0; i < n; i++)\n {\n _fooEventWaitHandle.WaitOne();\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n _barEventWaitHandle.Set();\n }\n }\n\n public void Bar(Action printBar)\n {\n\n for (int i = 0; i < n; i++)\n {\n _barEventWaitHandle.WaitOne();\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n _fooEventWaitHandle.Set();\n }\n }\n }\n```
3
0
[]
2
print-foobar-alternately
Simple Java Solution with two Semaphores, beat 100%
simple-java-solution-with-two-semaphores-wvu9
\nclass FooBar {\n private int n;\n \n private Semaphore fooSem;\n \n private Semaphore barSem;\n\n public FooBar(int n) {\n this.n = n
yizeliu
NORMAL
2019-12-27T15:13:02.236746+00:00
2019-12-27T15:13:02.236799+00:00
308
false
```\nclass FooBar {\n private int n;\n \n private Semaphore fooSem;\n \n private Semaphore barSem;\n\n public FooBar(int n) {\n this.n = n;\n this.fooSem = new Semaphore(1);\n this.barSem = new Semaphore(0);\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n this.fooSem.acquire();\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n this.barSem.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n this.barSem.acquire();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n this.fooSem.release();\n }\n }\n}\n```
3
0
[]
0
print-foobar-alternately
C# 56ms Using Semaphore
c-56ms-using-semaphore-by-deleted_user-3ri2
\nusing System;\nusing System.Threading;\n\npublic class FooBar {\n private int n;\n private Semaphore semFoo;\n private Semaphore semBar;\n \n\
deleted_user
NORMAL
2019-11-21T07:12:44.370338+00:00
2019-11-21T07:12:44.370371+00:00
168
false
```\nusing System;\nusing System.Threading;\n\npublic class FooBar {\n private int n;\n private Semaphore semFoo;\n private Semaphore semBar;\n \n\n public FooBar(int n) {\n this.n = n;\n this.semFoo = new Semaphore(initialCount: 0, maximumCount: 1);\n this.semBar = new Semaphore(initialCount: 1, maximumCount: 1);\n }\n\n public void Foo(Action printFoo) {\n for (int i = 0; i < n; i++) {\n \n \t// printFoo() outputs "foo". Do not change or remove this line.\n semBar.WaitOne();\n \tprintFoo();\n semFoo.Release(1);\n }\n }\n\n public void Bar(Action printBar) {\n \n for (int i = 0; i < n; i++) {\n \n // printBar() outputs "bar". Do not change or remove this line.\n semFoo.WaitOne();\n \tprintBar();\n semBar.Release(1);\n }\n }\n}\n```
3
0
[]
0
print-foobar-alternately
C++ Semaphore solution
c-semaphore-solution-by-plateofpasta-jlzi
c++\n#include <semaphore.h> // from POSIX\n\nclass FooBar \n{\npublic:\n FooBar(int n) \n {\n this->n = n;\n sem_init(&foo_, 0, 1);\n sem_init(&bar_,
plateofpasta
NORMAL
2019-11-09T06:05:14.876364+00:00
2019-11-09T16:54:03.699112+00:00
885
false
```c++\n#include <semaphore.h> // from POSIX\n\nclass FooBar \n{\npublic:\n FooBar(int n) \n {\n this->n = n;\n sem_init(&foo_, 0, 1);\n sem_init(&bar_, 0, 0);\n }\n \n ~FooBar()\n {\n sem_destroy(&foo_); \n sem_destroy(&bar_); \n }\n\n void foo(function<void()> printFoo) \n {\n for (int i = 0; i < n; i++) \n {\n sem_wait(&foo_);\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n sem_post(&bar_);\n std::this_thread::yield();\n }\n }\n\n void bar(function<void()> printBar) \n {\n for (int i = 0; i < n; i++) \n {\n sem_wait(&bar_);\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n sem_post(&foo_);\n std::this_thread::yield(); \n }\n }\n \nprivate:\n int n;\n sem_t foo_;\n sem_t bar_; \n};\n```\n\n<br />\n\n*edit:*\nSemaphores, along with other threading primitives, are a confirmed C++2a library feature ([feature list on cppreference](https://en.cppreference.com/w/cpp/compiler_support), [thread support library on cppreference](https://en.cppreference.com/w/cpp/thread), and [latest published proposal on synchronization primitives](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1135r6.html)). For reference, leetcode compiles with "g++ 8.2 using the latest C++ 17 standard" at the time of writing. With this in mind, I wanted to modify the previous solution to be more C++ idiomatic and applicable to future versions of C++.\n\n```c++\n#include <semaphore.h> // from POSIX\n\n// RAII class for POSIX semaphore.\nclass counting_semaphore\n{\npublic:\n counting_semaphore(unsigned int start)\n {\n sem_init(&sem_, 0, start);\n }\n \n ~counting_semaphore()\n {\n sem_destroy(&sem_);\n }\n \n void acquire()\n {\n sem_wait(&sem_);\n }\n \n void release()\n {\n sem_post(&sem_);\n }\n \nprivate:\n sem_t sem_;\n};\n\nclass FooBar \n{\npublic:\n FooBar(int n) \n {\n this->n = n;\n }\n \n void foo(function<void()> printFoo) \n {\n for (int i = 0; i < n; i++) \n {\n foo_.acquire();\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n bar_.release();\n std::this_thread::yield();\n }\n }\n\n void bar(function<void()> printBar) \n {\n for (int i = 0; i < n; i++) \n {\n bar_.acquire();\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n foo_.release();\n std::this_thread::yield(); \n }\n }\n \nprivate:\n int n;\n counting_semaphore foo_{1};\n counting_semaphore bar_{0}; \n};\n```
3
0
['C']
0
print-foobar-alternately
Simple java solution with explanation
simple-java-solution-with-explanation-by-7qr3
Simple Java solution with two Semaphores.\n\nimport java.util.concurrent.*;\nclass FooBar {\n private int n;\n private Semaphore one, two; //Declaring two
malex
NORMAL
2019-08-27T18:29:41.971836+00:00
2019-08-27T18:29:41.971868+00:00
423
false
Simple Java solution with two Semaphores.\n```\nimport java.util.concurrent.*;\nclass FooBar {\n private int n;\n private Semaphore one, two; //Declaring two Semaphores.\n\n public FooBar(int n) {\n this.n = n;\n one = new Semaphore(1); //First semaphore initialized with one permit available\n two = new Semaphore(0); //Second Semaphore initialized with no permits\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n one.acquire(); // Acquire first semaphore wich have one permit, no permits remaining\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n two.release(); //Add one permit to second semaphore\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n two.acquire(); //Waits till one permit will be added in foo method, then acquire it\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n one.release(); // add one permit to first Semaphore\n }\n }\n}\n```
3
0
[]
0
print-foobar-alternately
Simple Python Solution
simple-python-solution-by-simonkocurek-nsda
python\nfrom threading import Lock\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_lock = Lock()\n self.bar_lock = Loc
simonkocurek
NORMAL
2019-07-25T18:58:17.357211+00:00
2019-07-25T18:58:17.357246+00:00
393
false
```python\nfrom threading import Lock\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.foo_lock = Lock()\n self.bar_lock = Lock()\n \n # Don\'t start with bar\n self.bar_lock.acquire()\n\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n \n for i in range(self.n):\n self.foo_lock.acquire()\n printFoo()\n self.bar_lock.release()\n\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n \n for i in range(self.n):\n self.bar_lock.acquire()\n printBar()\n self.foo_lock.release()\n```
3
1
[]
2
print-foobar-alternately
posix thread C solution
posix-thread-c-solution-by-xuchen321-rcvx
the similar problem like 1114,using posix thread tools to solve this\n\n#include <pthread.h>\n\n/*\n 1.we need two thread do not interrupt with each other\n
xuchen321
NORMAL
2019-07-15T00:12:28.339793+00:00
2019-07-15T00:12:28.339833+00:00
349
false
the similar problem like 1114,using posix thread tools to solve this\n```\n#include <pthread.h>\n\n/*\n 1.we need two thread do not interrupt with each other\n means when one thread is outputing, the other one don\'t do that\n 2.we have the preference in 1\'s basis, one need to do first \n ====> for mutual exclusive, need a mutex,also a condition variable\n to save cpu cycles\n\t\t\t because this mutual exclusive has some kind of "preference",\n\t\t\t so setup a global variable to tell two thread,who can print now\n\n*/\npthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\npthread_cond_t cond = PTHREAD_COND_INITIALIZER;\nint who=1;\ntypedef struct {\n int n;\n} FooBar;\n\nFooBar* fooBarCreate(int n) {\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n obj->n = n;\n return obj;\n}\n\nvoid foo(FooBar* obj) {\n \n for (int i = 0; i < obj->n; i++) {\n pthread_mutex_lock(&mutex);\n // printFoo() outputs "foo". Do not change or remove this line.\n while(who==2){\n pthread_cond_wait(&cond,&mutex);\n }\n printFoo();\n who=2;\n pthread_cond_broadcast(&cond);\n pthread_mutex_unlock(&mutex);\n }\n}\n\nvoid bar(FooBar* obj) {\n \n for (int i = 0; i < obj->n; i++) {\n pthread_mutex_lock(&mutex);\n // printBar() outputs "bar". Do not change or remove this line.\n while(who==1){\n pthread_cond_wait(&cond,&mutex);\n }\n printBar();\n who=1;\n pthread_cond_broadcast(&cond);\n pthread_mutex_unlock(&mutex);\n }\n}\n\nvoid fooBarFree(FooBar* obj) {\n \n}\n```
3
0
[]
1
print-foobar-alternately
[Cpp] Mutex solution
cpp-mutex-solution-by-insanecoder-bw5p
```\nclass FooBar {\n mutex m1,m2;\nprivate:\n int n;\n\npublic:\n FooBar(int n) {\n this->n = n;\n\t\tm1.lock();\n }\n\n void foo(functio
insanecoder
NORMAL
2019-07-13T12:26:27.278713+00:00
2019-07-13T16:49:25.967377+00:00
1,174
false
```\nclass FooBar {\n mutex m1,m2;\nprivate:\n int n;\n\npublic:\n FooBar(int n) {\n this->n = n;\n\t\tm1.lock();\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo() outputs "foo". Do not change or remove this line.\n m2.lock();\n \tprintFoo();\n m1.unlock();\n \n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n \n \t// printBar() outputs "bar". Do not change or remove this line.\n m1.lock();\n \tprintBar();\n m2.unlock();\n \n }\n }\n};
3
0
['C', 'C++']
5
print-foobar-alternately
[C++] Using std::condition_variable
c-using-stdcondition_variable-by-mhelven-ggt7
C++\nclass FooBar {\nprivate:\n int n;\n bool fooTime;\n std::mutex mtx;\n std::condition_variable cv;\n\npublic:\n FooBar(
mhelvens
NORMAL
2019-07-12T19:44:52.621051+00:00
2019-07-17T07:02:54.431174+00:00
1,117
false
```C++\nclass FooBar {\nprivate:\n int n;\n bool fooTime;\n std::mutex mtx;\n std::condition_variable cv;\n\npublic:\n FooBar(int n) : n(n), fooTime(true) {}\n \n void setFooTime(bool ft, std::unique_lock<std::mutex>& lock) {\n fooTime = ft;\n lock.unlock();\n cv.notify_one();\n lock.lock();\n }\n\n void foo(function<void()> printFoo) {\n std::unique_lock<std::mutex> lock(mtx);\n for (int i = 0; i < n; i++) {\n cv.wait(lock, [this]{ return fooTime; });\n printFoo();\n setFooTime(false, lock);\n }\n }\n\n void bar(function<void()> printBar) {\n std::unique_lock<std::mutex> lock(mtx);\n for (int i = 0; i < n; i++) {\n cv.wait(lock, [this]{ return !fooTime; });\n printBar();\n setFooTime(true, lock);\n }\n }\n};\n```
3
0
['C']
3
print-foobar-alternately
Python Codintion
python-codintion-by-alexfvo-kilp
python\nfrom threading import Condition\nfrom typing import Callable\n\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.cv = Condi
alexfvo
NORMAL
2019-07-12T08:52:18.287956+00:00
2019-07-12T08:52:18.287989+00:00
330
false
```python\nfrom threading import Condition\nfrom typing import Callable\n\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.cv = Condition()\n self.printed_foo = False\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n\n for i in range(self.n):\n # printFoo() outputs "foo". Do not change or remove this line.\n with self.cv:\n self.cv.wait_for(lambda: self.printed_foo is False)\n printFoo()\n self.printed_foo = True\n self.cv.notify()\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n\n for i in range(self.n):\n # printBar() outputs "bar". Do not change or remove this line.\n with self.cv:\n self.cv.wait_for(lambda: self.printed_foo is True)\n printBar()\n self.printed_foo = False\n self.cv.notify()\n```
3
0
[]
0
print-foobar-alternately
Easy Beginner Friendly Solution 😊
easy-beginner-friendly-solution-by-praga-kppy
Code
pragadeeshxenocrate
NORMAL
2025-01-24T11:40:54.826971+00:00
2025-01-24T11:40:54.826971+00:00
726
false
# Code ```java [] class FooBar { private int n; boolean flag = true; // set flag to alternate between foo and bar public FooBar(int n) { this.n = n; } public synchronized void foo(Runnable printFoo) throws InterruptedException { for (int i = 0; i < n; i++) { while(!flag) { try{ wait(); } catch(InterruptedException e){ } } System.out.print("foo"); flag = false; notify(); // printFoo.run() outputs "foo". Do not change or remove this line. printFoo.run(); } } public synchronized void bar(Runnable printBar) throws InterruptedException { for (int i = 0; i < n; i++) { while(flag) { try{ wait(); } catch(InterruptedException e){ } } System.out.print("bar"); flag = true; notify(); // printBar.run() outputs "bar". Do not change or remove this line. printBar.run(); } } } ```
2
0
['Java']
1
print-foobar-alternately
Simple & clean solution in C++ beats 82%!!!!
simple-clean-solution-in-c-beats-82-by-r-japo
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nUsing 2 semaphores\n- s
RacheliBoyer
NORMAL
2024-08-05T11:42:38.054519+00:00
2024-08-05T11:42:38.054564+00:00
43
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing 2 semaphores\n- smph1 starts at 1: It allows the foo method to run first. When foo is called, it prints "foo" and releases smph2.\n- smph2 starts at 0: It blocks the bar method until foo releases it. When bar is called, it prints "bar" and releases smph1.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(2n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass FooBar {\nprivate:\n int n;\n binary_semaphore smph1{1};\n binary_semaphore smph2{0};\n\npublic:\n FooBar(int n) {\n this->n = n;\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n smph1.acquire();\n \t// printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n smph2.release();\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n smph2.acquire();\n \t// printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n smph1.release();\n }\n }\n};\n```
2
0
['Concurrency', 'C++']
0
print-foobar-alternately
The most simple solution in C++ beats 82%!!
the-most-simple-solution-in-c-beats-82-b-77vp
Intuition\n Describe your first thoughts o/ how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nUsing 2 semaphores.\n-
RacheliBoyer
NORMAL
2024-08-05T11:40:03.008613+00:00
2024-08-05T11:40:03.008636+00:00
31
false
# Intuition\n<!-- Describe your first thoughts o/ how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing 2 semaphores.\n- smph1 starts at 1: It allows the foo method to run first. When foo is called, it prints "foo" and releases smph2.\n- smph2 starts at 0: It blocks the bar method until foo releases it. When bar is called, it prints "bar" and releases smph1.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(2n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass FooBar {\nprivate:\n int n;\n binary_semaphore smph1{1};\n binary_semaphore smph2{0};\n\npublic:\n FooBar(int n) {\n this->n = n;\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n smph1.acquire();\n \t// printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n smph2.release();\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n smph2.acquire();\n \t// printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n smph1.release();\n }\n }\n};\n```
2
0
['Concurrency', 'C++']
0
print-foobar-alternately
C++ EASY AND CLEAN CODE
c-easy-and-clean-code-by-arpiii_7474-tnlp
Code\n\nclass FooBar {\nprivate:\n int n;\n mutex m1,m2;\npublic:\n FooBar(int n) {\n this->n = n;\n m2.lock();\n }\n void foo(func
arpiii_7474
NORMAL
2023-09-29T13:18:10.367261+00:00
2023-09-29T13:18:10.367280+00:00
418
false
# Code\n```\nclass FooBar {\nprivate:\n int n;\n mutex m1,m2;\npublic:\n FooBar(int n) {\n this->n = n;\n m2.lock();\n }\n void foo(function<void()> printFoo) {\n for (int i = 0; i < n; i++) {\n m1.lock();\n \tprintFoo();\n m2.unlock();\n }\n }\n void bar(function<void()> printBar) {\n for (int i = 0; i < n; i++) {\n m2.lock();\n \tprintBar();\n m1.unlock();\n }\n }\n};\n```
2
0
['C++']
0
print-foobar-alternately
[Beats 100%] Using 2 semaphores - easy to understand
beats-100-using-2-semaphores-easy-to-und-s82n
Full code with test suite\nhttps://github.com/Freeze777/SDE-Interviewer-Notes/blob/main/LeetCodeJava/src/main/java/leetcode/concurrency/FooBar.java\n\n# Code\n\
freeze_francis
NORMAL
2023-09-01T17:17:13.479793+00:00
2023-09-01T17:17:13.479811+00:00
73
false
# Full code with test suite\nhttps://github.com/Freeze777/SDE-Interviewer-Notes/blob/main/LeetCodeJava/src/main/java/leetcode/concurrency/FooBar.java\n\n# Code\n```\nclass FooBar {\n private final int n;\n private final Semaphore foo = new Semaphore(1);\n private final Semaphore bar = new Semaphore(0);\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n foo.acquire();\n \tprintFoo.run();\n bar.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n bar.acquire();\n \tprintBar.run();\n foo.release();\n }\n }\n}\n```
2
0
['Java']
0
print-foobar-alternately
Python with two Events
python-with-two-events-by-trpaslik-rrvr
Intuition\nTwo events: "ready for foo" and "ready for bar". \n\n# Approach\nCreate two events. Just set and clear each in proper moment.\nSee the comments in th
trpaslik
NORMAL
2022-12-28T22:44:13.207379+00:00
2022-12-28T22:44:45.668028+00:00
744
false
# Intuition\nTwo events: "ready for foo" and "ready for bar". \n\n# Approach\nCreate two events. Just set and clear each in proper moment.\nSee the comments in the code.\n\nIf you like it, plese up-vote. Thank you!\n\n\n# Code\n```\nfrom threading import Event, Barrier\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.canBar = Event()\n self.canBar.clear() # not yet ready for bar\n self.canFoo = Event()\n self.canFoo.set() # ready for foor\n\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.canFoo.wait() # wait until ready for foo\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.canFoo.clear() # that foo is printed\n self.canBar.set() # now, ready for bar\n\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.canBar.wait() # wait until ready for bar \n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.canBar.clear() # that bar is printed\n self.canFoo.set() # now, ready for foo\n```
2
0
['Concurrency', 'Python', 'Python3']
1
print-foobar-alternately
Python with one Barrier
python-with-one-barrier-by-trpaslik-0s0k
Intuition\nOne Barrier should be enough to synch each iteration\n\n# Approach\nUse single barrier to sync AFTER foo and BEFORE the bar in each iteration on both
trpaslik
NORMAL
2022-12-28T22:38:10.332539+00:00
2022-12-28T22:38:10.332569+00:00
1,014
false
# Intuition\nOne Barrier should be enough to synch each iteration\n\n# Approach\nUse single barrier to sync AFTER foo and BEFORE the bar in each iteration on both threads.\n\nIf you like it, plese up-vote. Thank you!\n\n\n# Code\n```\nfrom threading import Event, Barrier\n\nclass FooBar:\n def __init__(self, n):\n self.n = n\n self.canBar = Barrier(2) # two parties involved\n\n def foo(self, printFoo: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n # printFoo() outputs "foo". Do not change or remove this line.\n printFoo()\n self.canBar.wait() # we both sync here\n\n def bar(self, printBar: \'Callable[[], None]\') -> None:\n for i in range(self.n):\n self.canBar.wait() # we both sync here\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.canBar.reset() # replay the sync game\n\n```
2
1
['Concurrency', 'Python', 'Python3']
2
print-foobar-alternately
Java Solution
java-solution-by-rishi_rajj-egin
\nclass FooBar {\n private int n;\n boolean l = true;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public synchronized void foo(Runnab
rishi_rajj
NORMAL
2022-09-19T06:11:45.355363+00:00
2022-09-19T06:11:45.355401+00:00
1,282
false
```\nclass FooBar {\n private int n;\n boolean l = true;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public synchronized void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(!l)\n {\n wait();\n }\n \tprintFoo.run();\n l = false;\n notify();\n }\n }\n\n public synchronized void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \twhile(l)\n {\n wait();\n }\n \tprintBar.run();\n l = true;\n notify();\n }\n }\n}\n```
2
0
[]
1
print-foobar-alternately
Java | Beat 80% simple semaphore solution
java-beat-80-simple-semaphore-solution-b-b7sg
\nprivate int n;\n private Semaphore sem1;\n private Semaphore sem2;\n public FooBar(int n) {\n this.n = n;\n //as foo print need happen
enjoy209
NORMAL
2022-09-05T02:26:32.320479+00:00
2022-09-05T02:26:32.320528+00:00
924
false
```\nprivate int n;\n private Semaphore sem1;\n private Semaphore sem2;\n public FooBar(int n) {\n this.n = n;\n //as foo print need happen first, thus Semaphore need to be 1.\n sem1 = new Semaphore(1);\n sem2 = new Semaphore(0);\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n sem1.acquire();\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n sem2.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n sem2.acquire();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n sem1.release();\n }\n }\n```
2
0
['Java']
0
print-foobar-alternately
Simple JAVA semaphore solution
simple-java-semaphore-solution-by-db16-cnt8
\nclass FooBar {\n private int n;\n Semaphore fooSemaphore;\n Semaphore barSemaphore;\n\n public FooBar(int n) {\n this.n = n;\n fooSe
db16
NORMAL
2022-05-06T18:57:30.113640+00:00
2022-05-06T18:57:30.113684+00:00
237
false
```\nclass FooBar {\n private int n;\n Semaphore fooSemaphore;\n Semaphore barSemaphore;\n\n public FooBar(int n) {\n this.n = n;\n fooSemaphore = new Semaphore(1);\n barSemaphore = new Semaphore(0);\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n fooSemaphore.acquire();\n \tprintFoo.run();\n barSemaphore.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n barSemaphore.acquire();\n \tprintBar.run();\n fooSemaphore.release();\n }\n }\n}\n```
2
0
[]
0
print-foobar-alternately
Java synchronized version
java-synchronized-version-by-albertguosg-v01s
\nclass FooBar {\n private int n;\n private Object lock;\n private int count;\n\n public FooBar(int n) {\n this.n = n;\n this.lock = n
albertguosgp
NORMAL
2022-01-27T22:43:39.806649+00:00
2022-01-27T22:43:39.806677+00:00
289
false
```\nclass FooBar {\n private int n;\n private Object lock;\n private int count;\n\n public FooBar(int n) {\n this.n = n;\n this.lock = new Object();\n this.count = 1;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n synchronized (lock) {\n while(count != 1) {\n lock.wait();\n }\n printFoo.run();\n count = 0;\n lock.notifyAll();\n }\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n synchronized(lock) {\n while(count != 0) {\n lock.wait();\n }\n printBar.run();\n count = 1;\n lock.notifyAll();\n }\n\n }\n }\n}\n\n```
2
0
[]
1
print-foobar-alternately
[C#] AutoResetEvent solution
c-autoresetevent-solution-by-basmus-87za
\nusing System;\nusing System.Threading;\n\npublic class FooBar \n{\n private int n;\n\n private AutoResetEvent fooEvent = new AutoResetEvent(true);\n
basmus
NORMAL
2022-01-20T19:52:20.017021+00:00
2022-01-20T19:52:54.934675+00:00
99
false
```\nusing System;\nusing System.Threading;\n\npublic class FooBar \n{\n private int n;\n\n private AutoResetEvent fooEvent = new AutoResetEvent(true);\n private AutoResetEvent barEvent = new AutoResetEvent(false);\n \n public FooBar(int n) \n {\n this.n = n;\n }\n\n public void Foo(Action printFoo) \n { \n for (int i = 0; i < n; i++) \n {\n fooEvent.WaitOne();\n \tprintFoo();\n barEvent.Set();\n }\n }\n\n public void Bar(Action printBar) \n {\n for (int i = 0; i < n; i++) \n {\n barEvent.WaitOne();\n \tprintBar();\n fooEvent.Set();\n }\n }\n}\n```
2
0
[]
0
print-foobar-alternately
SImple Java Solution
simple-java-solution-by-aruslans-nzmx
\nclass FooBar {\n private int n;\n private volatile boolean isFoo = true;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void fo
aruslans
NORMAL
2021-12-15T20:56:39.045358+00:00
2021-12-15T20:56:39.045390+00:00
269
false
```\nclass FooBar {\n private int n;\n private volatile boolean isFoo = true;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n while (!isFoo);\n \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n \n isFoo = false;\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException { \n for (int i = 0; i < n; i++) {\n while (isFoo);\n \n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n \n isFoo = true;\n }\n }\n}\n```
2
0
[]
2
print-foobar-alternately
Java ReentrantLock + Condition + Volatile
java-reentrantlock-condition-volatile-by-tjom
Please check my solution, simple to understand~ (faster than 99.43%, less than 96.24% memory)\nJava\nimport java.util.*;\n\nclass FooBar {\n \n private i
arthas-wu
NORMAL
2021-11-28T05:15:36.696476+00:00
2021-12-02T13:55:35.189423+00:00
305
false
Please check my solution, simple to understand~ (faster than 99.43%, less than 96.24% memory)\n```Java\nimport java.util.*;\n\nclass FooBar {\n \n private int n;\n private volatile boolean invokeFoo;\n private final Lock lock = new ReentrantLock();\n private Condition fooC = lock.newCondition();\n private Condition barC = lock.newCondition();\n \n\n public FooBar(int n) {\n this.n = n;\n this.invokeFoo = true;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n try {\n lock.lock();\n if (!this.invokeFoo) {\n fooC.await();\n }\n printFoo.run();\n this.invokeFoo = false;\n barC.signal();\n } finally {\n lock.unlock();\n }\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n try {\n lock.lock();\n if (this.invokeFoo) {\n barC.await();\n }\n printBar.run();\n this.invokeFoo = true;\n fooC.signal();\n } finally {\n lock.unlock();\n }\n }\n }\n}\n```\n\nUsing ReentrantLock + condition instead of synchronized to give the go signal partitcular thread. This will be better than wait and notifyAll~
2
0
['Java']
2
print-foobar-alternately
[Java] Simple solution using synchronised and wait
java-simple-solution-using-synchronised-wrvkw
\nclass FooBar {\n private int n;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedExcep
phoenix_007
NORMAL
2021-05-31T12:25:40.957631+00:00
2021-05-31T12:25:40.957662+00:00
286
false
```\nclass FooBar {\n private int n;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n synchronized(this) {\n \n printFoo.run();\n \n wait();\n \n }\n \t\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n // printBar.run() outputs "bar". Do not change or remove this line.\n synchronized(this) {\n \n notify();\n printBar.run();\n \n }\n \t\n }\n }\n}\n```
2
1
[]
1
print-foobar-alternately
Java very easy Semaphore Solution
java-very-easy-semaphore-solution-by-sha-vkh4
class FooBar {\n private int n;\n\n public FooBar(int n) {\n this.n = n;\n }\n \n Semaphore sem1 = new Semaphore(0);\n Semaphore sem2 =
shadersy
NORMAL
2021-04-08T12:54:56.120391+00:00
2021-04-08T12:54:56.120425+00:00
215
false
class FooBar {\n private int n;\n\n public FooBar(int n) {\n this.n = n;\n }\n \n Semaphore sem1 = new Semaphore(0);\n Semaphore sem2 = new Semaphore(0);\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n \tsem1.acquire();\n \tprintFoo.run();\n sem2.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n sem1.release();\n \tprintBar.run();\n sem2.acquire();\n }\n }\n}
2
1
[]
0
print-foobar-alternately
C++ Ultra Simple Solution with Mutexes
c-ultra-simple-solution-with-mutexes-by-gmv2n
\nclass FooBar {\nprivate:\n int n;\n \n std::mutex foo_gate;\n std::mutex bar_gate;\n\npublic:\n FooBar(int new_n) : n(new_n) {\n bar_gat
chaflan
NORMAL
2021-03-13T00:06:47.884596+00:00
2021-03-13T04:45:53.577814+00:00
201
false
```\nclass FooBar {\nprivate:\n int n;\n \n std::mutex foo_gate;\n std::mutex bar_gate;\n\npublic:\n FooBar(int new_n) : n(new_n) {\n bar_gate.lock();\n }\n\n void foo(function<void()> printFoo) {\n for (int i = 0; i < n; i++) {\n foo_gate.lock();\n \tprintFoo();\n bar_gate.unlock();\n }\n }\n\n void bar(function<void()> printBar) {\n for (int i = 0; i < n; i++) {\n bar_gate.lock();\n \tprintBar();\n foo_gate.unlock();\n }\n }\n};\n```
2
0
[]
0
print-foobar-alternately
C# using AutoResetEvent. Clean codes
c-using-autoresetevent-clean-codes-by-wm-df2o
\nusing System.Threading;\n\npublic class FooBar {\n private int n;\n private AutoResetEvent printFooEvent;\n private AutoResetEvent printBarEvent;\n
wmjbandara
NORMAL
2021-03-06T07:25:38.948764+00:00
2021-03-06T07:25:38.948809+00:00
98
false
```\nusing System.Threading;\n\npublic class FooBar {\n private int n;\n private AutoResetEvent printFooEvent;\n private AutoResetEvent printBarEvent;\n public FooBar(int n) {\n printFooEvent = new AutoResetEvent(true);\n printBarEvent = new AutoResetEvent(false);\n this.n = n;\n }\n\n public void Foo(Action printFoo) {\n \n for (int i = 0; i < n; i++) {\n printFooEvent.WaitOne();\n \t// printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n printBarEvent.Set();\n }\n }\n\n public void Bar(Action printBar) {\n \n for (int i = 0; i < n; i++) {\n printBarEvent.WaitOne();\n // printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n printFooEvent.Set();\n }\n }\n}\n```
2
0
[]
0
print-foobar-alternately
Double Semaphore Solution
double-semaphore-solution-by-gbajorin-dqjk
\nimport java.util.concurrent.Semaphore;\n\n\nclass FooBar {\n private int n;\n private static Semaphore foo = new Semaphore(0);\n private static Semap
gbajorin
NORMAL
2021-01-15T05:12:23.886729+00:00
2021-01-15T05:12:23.886770+00:00
130
false
```\nimport java.util.concurrent.Semaphore;\n\n\nclass FooBar {\n private int n;\n private static Semaphore foo = new Semaphore(0);\n private static Semaphore bar = new Semaphore(0);\n public FooBar(int n) {\n this.n = n;\n }\n \n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n foo.release();\n bar.acquire();\n\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n // printBar.run() outputs "bar". Do not change or remove this line.\n foo.acquire();\n \tprintBar.run();\n bar.release();\n }\n }\n}\n```
2
0
[]
0
print-foobar-alternately
Java old school wait/notify solution
java-old-school-waitnotify-solution-by-a-593y
counter variable can be replaced with boolean type but if you want to track the number of invocation it is worth keeping int\n\nclass FooBar {\n private int
aleksgladun4
NORMAL
2021-01-13T08:06:36.450887+00:00
2021-01-13T08:06:36.450914+00:00
225
false
`counter` variable can be replaced with `boolean` type but if you want to track the number of invocation it is worth keeping `int`\n```\nclass FooBar {\n private int n;\n private volatile int counter = 1;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n\n public void foo(Runnable printFoo) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n\n synchronized (this) {\n while (counter % 2 == 0) {\n wait();\n }\n // printFoo.run() outputs "foo". Do not change or remove this line.\n printFoo.run();\n counter++;\n notify();\n }\n }\n }\n\n\n public void bar(Runnable printBar) throws InterruptedException {\n\n for (int i = 0; i < n; i++) {\n\n synchronized (this) {\n while (counter % 2 != 0) {\n wait();\n }\n // printBar.run() outputs "bar". Do not change or remove this line.\n printBar.run();\n counter++;\n notify();\n }\n }\n }\n}\n```
2
1
[]
0
print-foobar-alternately
Java semaphore solution - easy to understand
java-semaphore-solution-easy-to-understa-w9yz
\nclass FooBar {\n private int n;\n private Semaphore sem1, sem2;\n\n public FooBar(int n) {\n this.n = n;\n this.sem1 = new Semaphore(1)
tankztc
NORMAL
2020-12-24T04:01:25.074302+00:00
2020-12-24T04:01:25.074344+00:00
182
false
```\nclass FooBar {\n private int n;\n private Semaphore sem1, sem2;\n\n public FooBar(int n) {\n this.n = n;\n this.sem1 = new Semaphore(1);\n this.sem2 = new Semaphore(0);\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n sem1.acquire();\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n sem2.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n sem2.acquire();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n sem1.release();\n }\n }\n}\n```
2
0
[]
0
print-foobar-alternately
Java Solution with simple atomic boolean
java-solution-with-simple-atomic-boolean-qerw
Simple AtomicBoolean. However, while loops will eat out CPU cycles.\n\nclass FooBar {\n private int n;\n private AtomicBoolean acquire;\n \n public
farruh
NORMAL
2020-11-28T06:01:01.816551+00:00
2020-11-28T06:01:01.816582+00:00
168
false
Simple AtomicBoolean. However, while loops will eat out CPU cycles.\n```\nclass FooBar {\n private int n;\n private AtomicBoolean acquire;\n \n public FooBar(int n) {\n this.n = n;\n acquire = new AtomicBoolean(true);\n\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n while (!acquire.get()){ }\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n acquire.compareAndSet(true, false);\n }\n\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n while (acquire.get()){}\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n acquire.compareAndSet(false, true);\n }\n }\n}\n```
2
0
[]
1
print-foobar-alternately
C++ RAII Styled Locking 12ms faster than 99.60
c-raii-styled-locking-12ms-faster-than-9-fc6a
We only use cond notify one to reduce contention grabbing the mutex lock. Makes use of raii locking. \n\nOther alternatives:\n- use a binary sempahore for signa
advra
NORMAL
2020-11-27T01:23:24.820430+00:00
2020-11-28T21:37:23.187838+00:00
116
false
We only use cond notify one to reduce contention grabbing the mutex lock. Makes use of raii locking. \n\nOther alternatives:\n- use a binary sempahore for signaling. \n- without mutex and cond you can do spin lock with atomic bool\n\n```\nclass FooBar {\nprivate:\n int n;\n mutex m;\n condition_variable cond;\n bool isFoo;\n\npublic:\n FooBar(int n) {\n this->n = n;\n isFoo = true;\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n \n {\n unique_lock<mutex> lk(m);\n cond.wait(lk, [this] { return isFoo; });\n \t // printFoo() outputs "foo". Do not change or remove this line.\n \t printFoo();\n isFoo = false;\n }\n cond.notify_one();\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n \n {\n unique_lock<mutex> lk(m);\n cond.wait(lk, [this] { return isFoo==false; });\n \t // printBar() outputs "bar". Do not change or remove this line.\n \t printBar();\n isFoo = true;\n }\n cond.notify_one();\n }\n }\n};\n```
2
0
[]
0
print-foobar-alternately
Java Solution using only shared global variable.(Using Yield)
java-solution-using-only-shared-global-v-jl8z
\nclass FooBar {\n private int n;\n Boolean flag;\n\n public FooBar(int n) {\n this.n = n;\n flag = true;\n }\n\n public void foo(R
theBeardGuy
NORMAL
2020-08-14T08:11:39.951996+00:00
2020-08-14T08:11:39.952036+00:00
109
false
```\nclass FooBar {\n private int n;\n Boolean flag;\n\n public FooBar(int n) {\n this.n = n;\n flag = true;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(flag!=true)\n Thread.yield();\n printFoo.run();\n flag = false; \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(flag!=false)\n Thread.yield();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run(); \n flag = true;\n }\n }\n}\n```
2
0
[]
0
print-foobar-alternately
C++ condition variable
c-condition-variable-by-leolounz-liw3
class FooBar {\nprivate:\n int n;\n std::mutex m;\n std::condition_variable cv;\n bool flag = false;\n\npublic:\n FooBar(int n) {\n this->
leolounz
NORMAL
2020-07-04T10:18:06.712949+00:00
2020-07-04T10:18:06.712997+00:00
196
false
class FooBar {\nprivate:\n int n;\n std::mutex m;\n std::condition_variable cv;\n bool flag = false;\n\npublic:\n FooBar(int n) {\n this->n = n;\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo() outputs "foo". Do not change or remove this line.\n std::unique_lock<std::mutex> lock(m);\n cv.wait(lock,[this]{ return !flag;});\n printFoo();\n flag = true;\n cv.notify_one();\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n \n \t// printBar() outputs "bar". Do not change or remove this line.\n std::unique_lock<std::mutex> lock(m);\n cv.wait(lock,[this]{ return flag;});\n \tprintBar();\n flag = false;\n cv.notify_one();\n \n }\n }\n};
2
0
[]
1
print-foobar-alternately
C# faster than 90.67%, less then 100% Mem
c-faster-than-9067-less-then-100-mem-by-t1fys
Runtime: 52 ms\nMemory Usage: 16.8 MB\n```\npublic class FooBar {\n private int n;\n\n private System.Threading.AutoResetEvent fooReady;\n private Syst
ve7545
NORMAL
2020-05-31T18:16:50.950043+00:00
2020-05-31T18:17:29.935556+00:00
236
false
Runtime: 52 ms\nMemory Usage: 16.8 MB\n```\npublic class FooBar {\n private int n;\n\n private System.Threading.AutoResetEvent fooReady;\n private System.Threading.AutoResetEvent barReady;\n \n public FooBar(int n) {\n this.n = n;\n fooReady = new System.Threading.AutoResetEvent(true);\n barReady = new System.Threading.AutoResetEvent(false);\n }\n\n public void Foo(Action printFoo) {\n \n for (int i = 0; i < n; i++) {\n fooReady.WaitOne();\n \t// printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n barReady.Set();\n }\n }\n\n public void Bar(Action printBar) {\n \n for (int i = 0; i < n; i++) {\n barReady.WaitOne();\n // printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n fooReady.Set();\n }\n }\n \n ~FooBar()\n {\n try\n {\n fooReady.Dispose();\n barReady.Dispose();\n } catch(Exception ex) {}\n }
2
0
[]
0
print-foobar-alternately
Java Volatile flag and Thread.sleep(1) to skip TLE
java-volatile-flag-and-threadsleep1-to-s-9k1p
\nclass FooBar {\n private int n;\n private volatile boolean flag = true;\n\n \n public FooBar(int n) {\n this.n = n;\n }\n\n public vo
mastercaca
NORMAL
2020-05-18T15:28:56.550965+00:00
2020-05-19T00:18:16.954112+00:00
131
false
```\nclass FooBar {\n private int n;\n private volatile boolean flag = true;\n\n \n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(!flag){\n // w/o this line "Submit" return Time Limit Exceeded, idk why\n Thread.sleep(1);\n }\n \tprintFoo.run();\n this.flag=false;\n \n \n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(flag){\n // w/o this line "Submit" return Time Limit Exceeded, idk why\n Thread.sleep(1);\n }\n \tprintBar.run();\n this.flag=true;\n \n \n }\n }\n}\n```
2
0
[]
0
print-foobar-alternately
Synchronized With Wait & Notify [JAVA]
synchronized-with-wait-notify-java-by-dv-n1ou
\nclass FooBar {\n private int n;\n boolean fooPrinted = false;\n public FooBar(int n) {\n this.n = n;\n }\n\n public synchronized void fo
dvvalabs
NORMAL
2020-04-28T08:17:56.623661+00:00
2020-04-28T08:17:56.623715+00:00
353
false
```\nclass FooBar {\n private int n;\n boolean fooPrinted = false;\n public FooBar(int n) {\n this.n = n;\n }\n\n public synchronized void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n if(fooPrinted) this.wait();\n printFoo.run();\n fooPrinted = true;\n this.notify();\n\n } \n }\n\n public synchronized void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n if(!fooPrinted) this.wait();\n \tprintBar.run();\n fooPrinted = false;\n this.notify();\n }\n }\n}\n```
2
1
['Java']
1
print-foobar-alternately
C : simply sema
c-simply-sema-by-universalcoder12-dz2t
\ntypedef struct {\n sem_t fsema, bsema;\n int n;\n} FooBar;\n\nFooBar* fooBarCreate(int n) {\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n se
universalcoder12
NORMAL
2020-03-25T05:54:16.655697+00:00
2020-03-25T05:54:58.676813+00:00
289
false
```\ntypedef struct {\n sem_t fsema, bsema;\n int n;\n} FooBar;\n\nFooBar* fooBarCreate(int n) {\n FooBar* obj = (FooBar*) malloc(sizeof(FooBar));\n sem_init(&obj->fsema, 0, 1);\n sem_init(&obj->bsema, 0, 0);\n obj->n = n;\n return obj;\n}\n\nvoid foo(FooBar* obj) {\n for (int i = 0; i < obj->n; i++) {\n sem_wait(&obj->fsema); \n printFoo();\n sem_post(&obj->bsema);\n }\n}\n\nvoid bar(FooBar* obj) {\n for (int i = 0; i < obj->n; i++) {\n sem_wait(&obj->bsema); \n printBar();\n sem_post(&obj->fsema);\n }\n}\n\nvoid fooBarFree(FooBar* obj) {\n sem_destroy(&obj->fsema);\n sem_destroy(&obj->bsema);\n free(obj);\n}\n```
2
0
['C']
0
print-foobar-alternately
python, classic Semaphore based solution explained
python-classic-semaphore-based-solution-aa7pl
class FooBar:\n\n def __init__(self, n):\n self.n = n\n self.foo_lock = threading.Semaphore(1)\n self.bar_lock = threading.Semaphore(0)\
rmoskalenko
NORMAL
2020-03-17T23:34:42.743437+00:00
2020-03-17T23:35:42.451586+00:00
149
false
```class FooBar:\n\n def __init__(self, n):\n self.n = n\n self.foo_lock = threading.Semaphore(1)\n self.bar_lock = threading.Semaphore(0)\n\n def foo(self, printFoo):\n for i in range(self.n):\n self.foo_lock.acquire()\n printFoo()\n self.bar_lock.release()\n\n def bar(self, printBar):\n for i in range(self.n):\n self.bar_lock.acquire()\n printBar()\n self.foo_lock.release()\n```\n\t\nThink about semaphore as a count of available instance of a given resource. The `acquire()` reduces that number and `release()` increases.\n\t\nSo when we initialize class, we set `foo_lock` to 1, meaning it is ready to be printed, while `bar_lock` to 0 - meaning it has to wait.\n\nThen in both foo() and bar() we wait to acquire resource before we print and we release the other resource once we printed out string. \n\n
2
0
[]
1
print-foobar-alternately
Easy C++ using condition variable and two atomic counters [16 ms, 99.78%]
easy-c-using-condition-variable-and-two-hdole
Each thread increases a counter of how many times it has printed.\nEach thread also checks the other thread\'s counter to see whether it is high enough for this
ahcox
NORMAL
2020-01-21T23:20:05.256831+00:00
2020-01-21T23:20:05.256882+00:00
1,189
false
Each thread increases a counter of how many times it has printed.\nEach thread also checks the other thread\'s counter to see whether it is high enough for this thread to go ahead and print another time. If it isn\'t high enough, the thread waits until it is signalled by the other thread through their shared condition var to tell it that the count now is high enough.\nWhen a thread has finished its print and inced its counter, it uses the condition variable to wake up the other thread if it was sleeping.\nMost of the time the single mutex is not locked. It only gets locked to protect the condition varible as a wait is started.\nIf we had hardware concurrency > 1 a simple busy loop would win but since we don\'t, waiting and signalling is a better choice.\n\n# Code\n```c++\n class FooBar {\n const unsigned n;\n atomic<unsigned> foosDone = 0;\n atomic<unsigned> barsDone = 0;\n mutex m;\n condition_variable cv;\n\t\t\n public:\n FooBar(unsigned n_) : n(n_){\n }\n\n void foo(function<void()> printFoo) {\n\n for (int i = 0; i < n; i++) {\n {\n unique_lock l(m);\n cv.wait(l, [this, &i]{return barsDone >= i;});\n }\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n ++foosDone;\n cv.notify_one();\n }\n }\n\n void bar(function<void()> printBar) {\n\n for (int i = 0; i < n; i++) {\n {\n unique_lock l(m);\n cv.wait(l, [this, &i]{return foosDone > i;});\n }\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n ++barsDone;\n cv.notify_one();\n }\n }\n };\n```\n\n# Results\nFirst run:\n>Runtime: 16 ms, faster than 99.78% of C++ online submissions for Print FooBar Alternately.\n>Memory Usage: 10.6 MB, less than 100.00% of C++ online submissions for Print FooBar Alternately.\n\nSecond run (WTF):\n\n>Runtime: 344 ms, faster than 64.05% of C++ online submissions for Print FooBar Alternately.\n>Memory Usage: 10.5 MB, less than 100.00% of C++ online submissions for Print FooBar Alternately.
2
0
['C']
3
print-foobar-alternately
c++ semaphore
c-semaphore-by-tensor-flower-vut2
\n#include<semaphore.h>\nclass FooBar {\nprivate:\n int n;\n\tsem_t s1,s2;\n\npublic:\n FooBar(int n) {\n this->n = n;\n sem_init(&s1,0,0);\
tensor-flower
NORMAL
2019-12-19T01:17:19.045425+00:00
2019-12-19T01:28:43.936872+00:00
368
false
```\n#include<semaphore.h>\nclass FooBar {\nprivate:\n int n;\n\tsem_t s1,s2;\n\npublic:\n FooBar(int n) {\n this->n = n;\n sem_init(&s1,0,0);\n sem_init(&s2,0,1);\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n sem_wait(&s2);\n \t// printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n sem_post(&s1);\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n sem_wait(&s1);\n \t// printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n sem_post(&s2);\n }\n }\n};\n```
2
0
['C']
0
print-foobar-alternately
python solution with threading.Events
python-solution-with-threadingevents-by-3t34g
Simple Python solution:\n\n\nimport threading\nclass FooBar(object):\n def __init__(self, n):\n self.n = n\n self.foo_event = threading.Event()
vkaplarevic
NORMAL
2019-12-09T21:21:17.432617+00:00
2019-12-09T21:21:17.432650+00:00
169
false
Simple Python solution:\n\n```\nimport threading\nclass FooBar(object):\n def __init__(self, n):\n self.n = n\n self.foo_event = threading.Event()\n self.bar_event = threading.Event()\n\n\n def foo(self, printFoo):\n """\n :type printFoo: method\n :rtype: void\n """\n for i in xrange(self.n):\n # printFoo() outputs "foo". Do not change or remove this line.\n self.foo_event.wait()\n printFoo()\n self.foo_event.clear()\n self.bar_event.set()\n\n\n def bar(self, printBar):\n """\n :type printBar: method\n :rtype: void\n """\n\n self.foo_event.set()\n\n for i in xrange(self.n): \n self.bar_event.wait()\n # printBar() outputs "bar". Do not change or remove this line.\n printBar()\n self.bar_event.clear()\n self.foo_event.set()\n\n```
2
1
[]
1
print-foobar-alternately
Java Solution - BlockingQueue-s
java-solution-blockingqueue-s-by-akazlou-dy32
Using 2 separate blocking queues each of capacity of 1. \n\n\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\n\ncla
akazlou
NORMAL
2019-11-27T12:21:12.326116+00:00
2019-11-27T12:21:23.304744+00:00
435
false
Using 2 separate blocking queues each of capacity of 1. \n\n```\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\n\nclass FooBar {\n private int n;\n final BlockingQueue<Boolean> queue1 = new ArrayBlockingQueue<>(1);\n final BlockingQueue<Boolean> queue2 = new ArrayBlockingQueue<>(1);\n\n public FooBar(int n) {\n this.n = n; \n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n queue1.offer(Boolean.TRUE);\n queue2.take();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n queue1.take();\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n queue2.offer(Boolean.TRUE);\n \n }\n }\n}\n```
2
0
['Java']
0
print-foobar-alternately
Go
go-by-npx88-fx0g
go\t\npackage main\n\nimport (\n\t"fmt"\n\t"time"\n)\n\nvar (\n\tsignal = make(chan struct{})\n)\n\nfunc foo(n int) {\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Print
npx88
NORMAL
2019-10-10T16:48:49.309694+00:00
2019-10-10T16:48:49.309743+00:00
271
false
```go\t\npackage main\n\nimport (\n\t"fmt"\n\t"time"\n)\n\nvar (\n\tsignal = make(chan struct{})\n)\n\nfunc foo(n int) {\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Print("foo")\n\t\tsignal <- struct{}{}\n\t}\n}\n\nfunc bar(n int) {\n\tfor i := 0; i < n; i++ {\n\t\t<-signal\n\t\tfmt.Print("bar")\n\n\t}\n}\n\nfunc main() {\n\tn := 5\n\tgo foo(n)\n\tgo bar(n)\n\n\ttime.Sleep(2 * time.Second)\n}\n\n```
2
1
[]
2
print-foobar-alternately
Java Solution beats 100% time and space
java-solution-beats-100-time-and-space-b-00mk
Make each thread wait on a mutex using the state of a counter.\n\nclass FooBar {\n private int n; \n volatile int ctr;\n \n Object mutex;\n \n
shreytrivedi007
NORMAL
2019-09-13T01:03:23.589254+00:00
2019-09-13T01:05:03.364568+00:00
555
false
Make each thread wait on a mutex using the state of a counter.\n```\nclass FooBar {\n private int n; \n volatile int ctr;\n \n Object mutex;\n \n public FooBar(int n) {\n this.n = n;\n ctr=1;\n \n mutex = new Object();\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n synchronized(mutex)\n {\n while(ctr%2==0)\n mutex.wait();\n \n // printFoo.run() outputs "foo". Do not change or remove this line.\n printFoo.run();\n\n ctr++;\n mutex.notifyAll();\n }\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n synchronized(mutex)\n {\n while(ctr%2==1)\n mutex.wait();\n \n // printBar.run() outputs "bar". Do not change or remove this line.\n printBar.run();\n\n ctr++;\n mutex.notifyAll();\n }\n }\n }\n}\n```
2
0
['Java']
1
print-foobar-alternately
0 ms 🔥Intuitive | Two Mutex Only | C++ | C
0-ms-beats-10000-users-two-mutex-only-c-6tb4a
🚀 Approach We start with two mutexes (m1 and m2). m1 is open (unlocked) because foo gets to go first. m2 is locked because bar needs to wait its turn. Thre
nitinranjan
NORMAL
2025-01-28T21:22:09.956454+00:00
2025-01-28T21:25:43.774678+00:00
546
false
# 🚀 Approach 1. We start with two mutexes (`m1` and `m2`). - `m1` is open (unlocked) because `foo` gets to go first. - `m2` is locked because `bar` needs to wait its turn. 2. Thread 1 (`foo`): - It grabs `m1`, prints `"foo"`, and then signals (unlocks) `m2` to let `bar` take over. 3. Thread 2 (`bar`): - It grabs `m2`, prints `"bar"`, and then signals (unlocks) `m1` so `foo` can go again. # Code ```cpp [] class FooBar { private: int n; mutex m1, m2; public: FooBar(int n) { this->n = n; m2.lock(); } void foo(function<void()> printFoo) { for (int i = 0; i < n; i++) { m1.lock(); // printFoo() outputs "foo". Do not change or remove this line. printFoo(); m2.unlock(); } } void bar(function<void()> printBar) { for (int i = 0; i < n; i++) { m2.lock(); // printBar() outputs "bar". Do not change or remove this line. printBar(); m1.unlock(); } } }; ```
1
0
['C', 'Concurrency', 'C++']
1
print-foobar-alternately
Intuitive | Simple
intuitive-simple-by-richardleee-9n4l
IntuitionApproachComplexity Time complexity: Space complexity: Code
RichardLeee
NORMAL
2024-12-29T22:13:19.619568+00:00
2024-12-29T22:13:19.619568+00:00
336
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; class FooBar { private int n; //0: to print foo //1: to rpint bar private volatile int flag = 0; private final ReentrantLock lock = new ReentrantLock(); private final Condition fooNotPrinted = lock.newCondition(); private final Condition barNotPrinted = lock.newCondition(); public FooBar(int n) { this.n = n; } public void foo(Runnable printFoo) throws InterruptedException { for (int i = 0; i < n; i++) { // printFoo.run() outputs "foo". Do not change or remove this line. try { lock.lock(); while (flag != 0) { fooNotPrinted.await(); } printFoo.run(); flag = 1; barNotPrinted.signalAll(); } catch (InterruptedException e) { } finally { lock.unlock(); } } } public void bar(Runnable printBar) throws InterruptedException { for (int i = 0; i < n; i++) { try { lock.lock(); while (flag != 1) { barNotPrinted.await(); } printBar.run(); flag = 0; fooNotPrinted.signal(); } finally { lock.unlock(); } // printBar.run() outputs "bar". Do not change or remove this line. } } } ```
1
0
['Java']
0
print-foobar-alternately
Go - 3 solutions (Channels, Mutex and Atomic Operations)
go-3-solutions-channels-mutex-and-atomic-9fot
Channels vs Mutex vs Atomic Operations\n\nChannels : When goroutines needs to communicate.\n\nMutex : When goroutines needs shared variable.\n\nAtomic operation
fnf47
NORMAL
2024-11-14T16:11:34.070892+00:00
2024-11-14T16:11:34.070935+00:00
202
false
# Channels vs Mutex vs Atomic Operations\n\nChannels : When goroutines needs to communicate.\n\nMutex : When goroutines needs shared variable.\n\nAtomic operations : When it\'s known that lock will be quickly released and acquired. So your process remains in CPU (wasting CPU cycle) instead of getting removed back and forth (so saves on context switching).\n\n# Channels\n\nRuntime : 4 ms\n```golang []\ntype FooBar struct {\n\tn int\n\tchA chan struct{}\n\tchB chan struct{}\n}\n\nfunc NewFooBar(n int) *FooBar {\n\tf := FooBar{n: n}\n\tf.chA = make(chan struct{}, 1)\n\tf.chB = make(chan struct{}, 1)\n\treturn &f\n}\n\nfunc (fb *FooBar) Foo(printFoo func()) {\n\tfor i := 0; i < fb.n; i++ {\n\t\t// printFoo() outputs "foo". Do not change or remove this line.\n\t\tif i > 0 {\n\t\t\t<-fb.chB\n\t\t}\n\t\tprintFoo()\n\t\tfb.chA <- struct{}{}\n\t}\n}\n\nfunc (fb *FooBar) Bar(printBar func()) {\n\tfor i := 0; i < fb.n; i++ {\n\t\t// printBar() outputs "bar". Do not change or remove this line.\n\t\t<-fb.chA\n\t\tprintBar()\n\t\tfb.chB <- struct{}{}\n\t}\n\n}\n```\n\n# Mutex\nRuntime : 29 ms\n```golang []\n\ntype FooBar struct {\n\tn int\n\tm sync.Mutex\n\taTurn bool\n}\n\nfunc NewFooBar(n int) *FooBar {\n\tf := FooBar{n: n, aTurn: true}\n\treturn &f\n}\n\nfunc (fb *FooBar) Foo(printFoo func()) {\n\tfor i := 0; i < fb.n; {\n\t\t// printFoo() outputs "foo". Do not change or remove this line.\n\t\tfb.m.Lock()\n\t\tif fb.aTurn {\n\t\t\tprintFoo()\n\t\t\tfb.aTurn = false\n i++\n\t\t}\n\t\tfb.m.Unlock()\n\t}\n}\n\nfunc (fb *FooBar) Bar(printBar func()) {\n\tfor i := 0; i < fb.n; {\n\t\t// printBar() outputs "bar". Do not change or remove this line.\n\t\tfb.m.Lock()\n\t\tif !fb.aTurn {\n\t\t\tprintBar()\n\t\t\tfb.aTurn = true\n i++\n\t\t}\n\t\tfb.m.Unlock()\n\t}\n\n}\n```\n\n# Atomic Operations\nRuntime : 23 ms\n```golang []\n\ntype FooBar struct {\n\tn int\n\taTurn int32\n}\n\nfunc NewFooBar(n int) *FooBar {\n\tf := FooBar{n: n, aTurn: 0}\n\treturn &f\n}\n\nfunc (fb *FooBar) Foo(printFoo func()) {\n\tfor i := 0; i < fb.n; i++ {\n\t\t// printFoo() outputs "foo". Do not change or remove this line.\n\t\tfor !atomic.CompareAndSwapInt32(&fb.aTurn, 0, 0) {\n\t\t}\n\t\tprintFoo()\n\t\tatomic.StoreInt32(&fb.aTurn, 1)\n\t}\n}\n\nfunc (fb *FooBar) Bar(printBar func()) {\n\tfor i := 0; i < fb.n; i++ {\n\t\t// printBar() outputs "bar". Do not change or remove this line.\n\t\tfor !atomic.CompareAndSwapInt32(&fb.aTurn, 1, 1) {\n\t\t}\n\t\tprintBar()\n\t\tatomic.StoreInt32(&fb.aTurn, 0)\n\t}\n\n}\n```
1
0
['Concurrency', 'Go']
1
print-foobar-alternately
C++ CV + Mutex
c-cv-mutex-by-breakbadsp-dm0v
\n\n# Code\n\nclass FooBar {\nprivate:\n int n;\n\npublic:\n FooBar(int n) {\n this->n = n;\n }\n\n void foo(function<void()> printFoo) {\n
breakbadsp
NORMAL
2024-07-16T11:54:54.305763+00:00
2024-07-16T11:54:54.305794+00:00
547
false
\n\n# Code\n```\nclass FooBar {\nprivate:\n int n;\n\npublic:\n FooBar(int n) {\n this->n = n;\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n {\n std::unique_lock lg(mut);\n while(foo_done)\n cv.wait(lg);\n\n \t // printFoo() outputs "foo". Do not change or remove this line.\n \t printFoo();\n foo_done = true;\n }\n cv.notify_one();\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n \n {\n std::unique_lock ul(mut);\n while(!foo_done)\n cv.wait(ul);\n \t // printBar() outputs "bar". Do not change or remove this line.\n \t printBar();\n foo_done = false;\n }\n cv.notify_one();\n }\n }\n\nprivate:\n bool foo_done = false;\n std::mutex mut;\n std::condition_variable cv;\n};\n```
1
0
['C++']
1
print-foobar-alternately
Solution
solution-by-suraj_singh_rajput-2rdx
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Suraj_singh_rajput
NORMAL
2023-12-23T14:52:34.567612+00:00
2023-12-23T14:52:34.567629+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FooBar {\n private int n;\n private Semaphore fooSemaphore;\n private Semaphore barSemaphore;\n\n public FooBar(int n) {\n this.n = n;\n fooSemaphore = new Semaphore(1); \n barSemaphore = new Semaphore(0); \n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n fooSemaphore.acquire(); \n printFoo.run();\n barSemaphore.release(); \n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n barSemaphore.acquire(); \n printBar.run();\n fooSemaphore.release(); \n }\n }\n}\n\n```
1
0
['Java']
0
print-foobar-alternately
Solution
solution-by-suraj_singh_rajput-8y56
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Suraj_singh_rajput
NORMAL
2023-12-22T07:32:00.731235+00:00
2023-12-22T07:32:00.731272+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.concurrent.Semaphore;\n\nclass FooBar {\n private int n;\n private Semaphore fooSemaphore;\n private Semaphore barSemaphore;\n\n public FooBar(int n) {\n this.n = n;\n fooSemaphore = new Semaphore(1); \n barSemaphore = new Semaphore(0); \n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n fooSemaphore.acquire(); \n printFoo.run();\n barSemaphore.release(); \n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n for (int i = 0; i < n; i++) {\n barSemaphore.acquire(); \n printBar.run();\n fooSemaphore.release(); \n }\n }\n}\n\n```
1
0
['Java']
0
print-foobar-alternately
✅Using Mutex ✅|| Lock || 🏆Easy to understand 🏆
using-mutex-lock-easy-to-understand-by-r-37l8
\n\n# Code\n\nclass FooBar {\nprivate:\n int n;\n std:: mutex m ;\n std:: condition_variable cv;\n bool turn;\npublic:\n FooBar(int n) {\n
rajh_3399
NORMAL
2023-10-12T10:56:14.018416+00:00
2023-10-12T10:56:14.018443+00:00
886
false
\n\n# Code\n```\nclass FooBar {\nprivate:\n int n;\n std:: mutex m ;\n std:: condition_variable cv;\n bool turn;\npublic:\n FooBar(int n) {\n this->n = n;\n turn = 0 ;\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n std:: unique_lock<std:: mutex > lock(m);\n while(turn ==1){\n cv.wait(lock);\n }\n \t// printFoo() outputs "foo". Do not change or remove this line.\n \tprintFoo();\n turn = 1;\n cv.notify_all();\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n std::unique_lock< std:: mutex> lock(m);\n while(turn == 0){\n cv.wait(lock);\n }\n \t// printBar() outputs "bar". Do not change or remove this line.\n \tprintBar();\n turn = 0;\n cv.notify_all();\n }\n }\n};\n```
1
0
['C++']
1
print-foobar-alternately
[JAVA] CAS + volatile
java-cas-volatile-by-datou12138-rycp
Intuition\n Describe your first thoughts on how to solve this problem. \nUsing CAS + volatile\n# Approach\n Describe your approach to solving the problem. \n\n#
datou12138
NORMAL
2023-08-30T12:30:57.168701+00:00
2023-08-30T12:30:57.168741+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing CAS + volatile\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FooBar {\n private int n;\n private volatile boolean state;\n public FooBar(int n) {\n this.n = n;\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(state) {\n continue;\n }\n \t// printFoo.run() outputs "foo". Do not change or remove this line.\n \tprintFoo.run();\n state = true;\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n while(!state) {\n continue;\n }\n // printBar.run() outputs "bar". Do not change or remove this line.\n \tprintBar.run();\n state = false;\n }\n }\n}\n\n```
1
0
['Java']
0
print-foobar-alternately
C# solution using Monitor.Wait() and Monitor.PulseAll()
c-solution-using-monitorwait-and-monitor-s107
Intuition\nThread Signalling\n\n# Code\n\nusing System.Threading;\n\npublic class FooBar {\n private int n;\n\n private readonly object mutex = new object
deto
NORMAL
2023-07-06T11:21:53.044177+00:00
2023-07-06T11:21:53.044205+00:00
225
false
# Intuition\nThread Signalling\n\n# Code\n```\nusing System.Threading;\n\npublic class FooBar {\n private int n;\n\n private readonly object mutex = new object();\n private bool foo = false;\n private bool bar = true;\n\n public FooBar(int n) {\n this.n = n;\n }\n\n public void Foo(Action printFoo) {\n \n for (int i = 0; i < n; i++) {\n lock (mutex)\n {\n while (bar is false) Monitor.Wait(mutex);\n bar = false;\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n foo = true;\n Monitor.PulseAll(mutex);\n }\n }\n }\n\n public void Bar(Action printBar) {\n \n for (int i = 0; i < n; i++) {\n lock (mutex)\n {\n while (foo is false) Monitor.Wait(mutex);\n foo = false;\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n bar = true;\n Monitor.PulseAll(mutex);\n }\n }\n }\n}\n```
1
0
['C#']
0
print-foobar-alternately
C++ | 2 Codes | Trick | conditional variable |
c-2-codes-trick-conditional-variable-by-mzgs1
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition is to use a condition_variable and a boolean flag (isFooTurn) to determin
animeshgurjar
NORMAL
2023-06-15T17:55:07.439813+00:00
2023-06-30T12:31:53.227087+00:00
1,187
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition is to use a **condition_variable** and a **boolean** **flag** (**isFooTurn**) to determine which thread\'s turn it is. The threads acquire a unique lock on a mutex before performing their operations. If it\'s not their turn, they wait on the condition_variable until it\'s signaled by the other thread. Once it\'s their turn, they perform their operation (printing) and change the flag to indicate the other thread\'s turn. Finally, they notify one waiting thread to proceed.\n\n \n\n# Code 1\n``` \n \n\nclass FooBar {\nprivate:\n int n;\n std::condition_variable turn;\n std::mutex m;\n std::atomic<bool> isFooTurn;\n\npublic:\n FooBar(int n) {\n this->n = n;\n isFooTurn.store(true); // Start with foo\'s turn\n }\n\n void foo(std::function<void()> printFoo) {\n std::unique_lock<std::mutex> lock(m);\n for (int i = 0; i < n; i++) {\n // Wait until it\'s foo\'s turn\n turn.wait(lock, [this]() { return isFooTurn.load(); });\n // Print "foo"\n printFoo();\n // Change the turn to bar\n isFooTurn.store(false);\n // Notify one waiting thread (bar) to proceed\n turn.notify_one();\n }\n }\n\n void bar(std::function<void()> printBar) {\n std::unique_lock<std::mutex> lock(m);\n for (int i = 0; i < n; i++) {\n // Wait until it\'s bar\'s turn\n turn.wait(lock, [this]() { return !isFooTurn.load(); });\n // Print "bar"\n printBar();\n // Change the turn to foo\n isFooTurn.store(true);\n // Notify one waiting thread (foo) to proceed\n turn.notify_one();\n }\n }\n};\n\n```\n\n# Code 2\n```\n \n\nclass FooBar {\nprivate:\n int n;\n std::mutex m1, m2; // Two mutexes to synchronize foo and bar\n\npublic:\n FooBar(int n) {\n this->n = n;\n m2.lock(); // Lock m2 initially to ensure foo starts first\n }\n\n void foo(function<void()> printFoo) {\n for (int i = 0; i < n; i++) {\n m1.lock(); // Acquire lock on m1\n // printFoo() outputs "foo". Do not change or remove this line.\n printFoo();\n m2.unlock(); // Release lock on m2 to allow bar to proceed\n }\n }\n\n void bar(function<void()> printBar) {\n for (int i = 0; i < n; i++) {\n m2.lock(); // Acquire lock on m2\n // printBar() outputs "bar". Do not change or remove this line.\n printBar();\n m1.unlock(); // Release lock on m1 to allow foo to proceed\n }\n }\n};\n\n```\n\n
1
0
['C++']
3
print-foobar-alternately
C#, Semaphores, faster than 100%
c-semaphores-faster-than-100-by-bikbov-3ejs
Code\n\nusing System.Threading;\npublic class FooBar \n{\n private Semaphore fooSem, barSem; \n private int n;\n public FooBar(int n) \n {\n
bikbov
NORMAL
2023-01-22T19:38:37.747304+00:00
2023-01-22T19:38:37.747336+00:00
792
false
# Code\n```\nusing System.Threading;\npublic class FooBar \n{\n private Semaphore fooSem, barSem; \n private int n;\n public FooBar(int n) \n {\n this.n = n;\n fooSem = new Semaphore(1, 1);\n barSem = new Semaphore(0, 1);\n }\n\n public void Foo(Action printFoo) \n {\n for (int i = 0; i < n; i++) \n {\n fooSem.WaitOne();\n \tprintFoo();\n barSem.Release();\n }\n }\n\n public void Bar(Action printBar) \n {\n for (int i = 0; i < n; i++) \n {\n barSem.WaitOne();\n \tprintBar();\n fooSem.Release();\n }\n }\n}\n```
1
0
['C#']
1
print-foobar-alternately
C++ (atomic bool w/ yield)
c-atomic-bool-w-yield-by-dakre-e336
\nclass FooBar {\nprivate:\n atomic<bool> alt;\n int n;\n\npublic:\n FooBar(int n) {\n this->n = n;\n alt = true;\n }\n\n void foo(
dakre
NORMAL
2022-08-02T15:42:36.606534+00:00
2022-08-02T15:42:36.606565+00:00
347
false
```\nclass FooBar {\nprivate:\n atomic<bool> alt;\n int n;\n\npublic:\n FooBar(int n) {\n this->n = n;\n alt = true;\n }\n\n void foo(function<void()> printFoo) {\n for (int i = 0; i < n; i++) {\n while (!alt) this_thread::yield();\n printFoo();\n alt = false;\n }\n }\n\n void bar(function<void()> printBar) {\n for (int i = 0; i < n; i++) {\n while (alt) this_thread::yield();\n printBar();\n alt = true;\n }\n }\n};\n```
1
0
['C']
0
print-foobar-alternately
java solution using concurrency
java-solution-using-concurrency-by-sachi-51oe
class FooBar {\n private int n;\n Semaphore foo;\n Semaphore bar;\n public FooBar(int n) {\n this.n = n;\n foo=new Semaphore(1);\n
sachinsingh1451
NORMAL
2022-05-28T10:02:56.259347+00:00
2022-05-28T10:02:56.259390+00:00
233
false
class FooBar {\n private int n;\n Semaphore foo;\n Semaphore bar;\n public FooBar(int n) {\n this.n = n;\n foo=new Semaphore(1);\n bar =new Semaphore (0);\n }\n\n public void foo(Runnable printFoo) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n foo.acquire();\n \tprintFoo.run();\n bar.release();\n }\n }\n\n public void bar(Runnable printBar) throws InterruptedException {\n \n for (int i = 0; i < n; i++) {\n \n bar.acquire();\n \tprintBar.run();\n foo.release();\n }\n }\n}
1
0
['Java']
0
print-foobar-alternately
C++ || SEMAPHORE || EXTREMELY SHORT ANSWER || EXPLANATION GIVEN
c-semaphore-extremely-short-answer-expla-ej3x
\n#include <semaphore.h>\nclass FooBar {\nprivate:\n int n;\n sem_t f;\n sem_t b;\n\npublic:\n FooBar(int n) {\n this->n = n;\n sem_in
AlexHewJW
NORMAL
2022-05-23T15:57:25.938076+00:00
2022-05-23T15:57:25.938104+00:00
160
false
```\n#include <semaphore.h>\nclass FooBar {\nprivate:\n int n;\n sem_t f;\n sem_t b;\n\npublic:\n FooBar(int n) {\n this->n = n;\n sem_init(&f, 0, 1); //foo goes first, so this is set to true\n sem_init(&b, 0, 0); //bar comes later, so init as false.\n }\n\n void foo(function<void()> printFoo) {\n \n for (int i = 0; i < n; i++) {\n sem_wait(&f); //wait for bar, or first time straight come in to print\n \tprintFoo();\n sem_post(&b); //afer print foo, then print bar\n }\n }\n\n void bar(function<void()> printBar) {\n \n for (int i = 0; i < n; i++) {\n sem_wait(&b); //wait for foo\n \tprintBar();\n sem_post(&f); //after print bar then print foo\n }\n }\n};\n\n\n\n```
1
0
['C']
0
minimum-score-triangulation-of-polygon
C++ with picture
c-with-picture-by-votrubac-08h6
Intuition\nIf we pick a side of our polygon, it can form n - 2 triangles. Each such triangle breaks our polygon into 2 sub-polygons. We can analyze n - 2 triang
votrubac
NORMAL
2019-05-05T04:54:33.525793+00:00
2022-01-03T17:11:42.571742+00:00
22,500
false
# Intuition\nIf we pick a side of our polygon, it can form ```n - 2``` triangles. Each such triangle breaks our polygon into 2 sub-polygons. We can analyze ```n - 2``` triangles, and get the minimum score for sub-polygons using the recursion.\n![image](https://assets.leetcode.com/users/votrubac/image_1557470819.png)\nThis is how this procedure looks for a sub-polygon (filled with diagonal pattern above).\n\n![image](https://assets.leetcode.com/users/votrubac/image_1557471328.png)\n# Top-Down Solution\n\u2022\tFix one side of the polygon i, j and move k within (i, j).\n\u2022\tCalculate score of the i, k, j "orange" triangle.\n\u2022\tAdd the score of the "green" polygon i, k using recursion.\n\u2022\tAdd the score of the "blue" polygon k, j using recursion.\n\u2022\tUse memoisation to remember minimum scores for each sub-polygons.\n```\nint dp[50][50] = {};\nint minScoreTriangulation(vector<int>& A, int i = 0, int j = 0, int res = 0) {\n if (j == 0) j = A.size() - 1;\n if (dp[i][j] != 0) return dp[i][j];\n for (auto k = i + 1; k < j; ++k) {\n res = min(res == 0 ? INT_MAX : res, \n minScoreTriangulation(A, i, k) + A[i] * A[k] * A[j] + minScoreTriangulation(A, k, j));\n }\n return dp[i][j] = res;\n}\n```\n# Bottom-Up Solution\nAt this point, it should not be hard to come up with a bottom-up solution. The only trick here is to move ```i``` backward. This ensures "green" and "blue" sub-polygons are processed before calculating min value for the entire polygon. It happens this way naturally with the recursive solution.\n```\nint minScoreTriangulation(vector<int>& A) {\n int dp[50][50] = {};\n for (int i = A.size() - 1; i >= 0; --i)\n for (int j = i + 1; j < A.size(); ++j)\n for (auto k = i + 1; k < j; ++k)\n dp[i][j] = min(dp[i][j] == 0 ? INT_MAX : dp[i][j], dp[i][k] + A[i] * A[k] * A[j] + dp[k][j]);\n return dp[0][A.size() - 1];\n} \n```\n# Complexity Analysis\nRuntime: O(n ^ 3). This can be easily seen from the bottom-up solution.\nMemory: O(n ^ 2). We use a square matrix to store DP results.
611
0
[]
56
minimum-score-triangulation-of-polygon
Python In-depth Explanation DP For Beginners
python-in-depth-explanation-dp-for-begin-gur8
First, I feel like this was a hard problem. This problem is very similar to Burst Ballons (https://leetcode.com/problems/burst-balloons/), which is labeled as a
rosemelon
NORMAL
2019-05-18T02:11:36.797672+00:00
2019-05-18T02:28:01.977453+00:00
5,954
false
First, I feel like this was a hard problem. This problem is very similar to Burst Ballons (https://leetcode.com/problems/burst-balloons/), which is labeled as a hard. They are almost the exact same problem, so I don\'t understand why this is medium. Now, moving on to the explanation. \n\nThe problem asks what is the minimum amount we can get from triangulating. Once you pick your 3 points, you\'ll need to throw out the middle point (the one between 2 other values in your array) because you have sliced the triangle off the polygon. Once we have triangulated the triangle, the midpoint dissapears from our array. If you need to imagine what this looks like in your head, imagine a triangle being sliced off the polygon with each iteration. This post has a great picture of what the slicing would look like. https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/286754/C%2B%2BPython-O(n3)-DP-explanation-%2B-diagrams.\n\nFor a beginner, it is NOT a good idea to start off by thinking how to solve the problem just by using dynamic programming. You\'re going to get very confused. You\'re going to see a few dynamic programming questions and somehow memorize the tables invovled, then not understand how to solve another one. You\'re going to think you can solve a DP problem, but your brain is tricking yourself. Trust me, after I watched Tushar Roy\'s videos, I thought I could solve DP problems, but all I was doing was subconciously memorizing solutions and not understanding them. \n\nHere are the steps you should consider BEFORE coming up with the dynamic programming solution: \n**1. Recursive solution**\n**2. Memoize the recursive solution (top-down)**\n**3. Subproblem Order for DP (bottom-up)**\n\nThere are debates on whether recursion or DP is better, and it might be good for you to mention that you know this in an interview.\n\nLet\'s say you have an array or a bunch of data. \n\nIn problems where the base case is an empty string once you have processed everything in your array, dynamic programming is the best solution because you need to go all the way to an empty string in order to get an answer. If you have a question where the base case is when your array is 9/10 full and you don\'t need to know the answer to subproblems (ie you never need to go all the way down to an empty string), a recursive memoized solution might be faster. However, most of the problems I\'ve seen on leetcode you need to go all the way down to an empty string or very close. In this case you can only have 3 points left, which means you need to go all the way down.\n\n**Step 1: Recursion**\n\nHere is our recursive solution. Notice that we have defined our "subproblems" to be the length of array. For each recursive call, we shorten our array by 1 value. This is the value we have picked to triangulate. Below is our recursive function. For fun, I submitted it and of course got TLE. It failed on a test case of length 20. Pretty bad right? It is because we\'re solving the same subproblems over and over. \n\nNote our base case is when we have an array of length 2. This is because we need at least 3 points to triangulate in order to get points. We set a variable `minnum` to float("Inf") as a pseudo-max. The `left` and `right` variables are the two other corners of the triangle. `k` is the other corner. I write `left` and `right` because it is left and right of k in our array. Note that dfs(left,k) and dfs(right,k) are the points you get for the triangluation BETWEEN, ie NOT INCLUDING, left, k and right. This means it defines points you get from left+1 -> k-1 and k+1 -> right -1. \n\nThis is what each section of points should be imagined as:\n**[left]** [left +1 -> k - 1] **[K]** [k + 1 -> right - 1] **[right]**\n\nYou are choosing points K, left, and right as the corners of your triangle. So you need to know how many points you got from [left +1 -> k - 1] and [k + 1 -> right - 1]. Since you have recursed on all of [left +1 -> k - 1] and [k + 1 -> right - 1] to find the minimum number of points you can get, you know this. \n\nDo you see how you are doing the same subproblem over and over and what it is? It\'s the length of the subarray. In order to do this via dynamic programming, we need to first start with an array of length 1, find it\'s minimum points (only 1 answer there) and then keep building with arrays of size 2, 3, ... n-1. \n\n```\nclass Solution(object):\n def minScoreTriangulation(self, A):\n\t\tdef dfs(left, right):\n if right - left + 1 < 3:\n return 0\n minnum = float("Inf")\n for k in range(left+1, right):\n minnum = min(minnum, A[left]*A[right]*A[k] + dfs(left, k) + dfs(k, right))\n return minnum\n return dfs(0, len(A) - 1)\n```\n\n**Step 2: Memoization**\n\nPython 3 has an lru cache, which is pretty useful, so that\'s already memoized. I\'ll have to add an actual memo 2D array later if this is not ok. \n\n```\nfrom functools import lru_cache\nclass Solution(object):\n def minScoreTriangulation(self, A):\n\t@lru_cache(None)\n\t\tdef dfs(left, right):\n if right - left + 1 < 3:\n return 0\n minnum = float("Inf")\n for k in range(left+1, right):\n minnum = min(minnum, A[left]*A[right]*A[k] + dfs(left, k) + dfs(k, right))\n return minnum\n return dfs(0, len(A) - 1)\n```\n\n**Step 3: Dynamic Programming**\n\nHere is where we get to dynamic programming. Do I think in an interview they might be ok with you jumping directly to DP if you know what you\'re doing and can solve the problem that way? Sure, but you might get asked a random question you\'ve never seen before so it\'s a good idea to do these steps. \n\nSo as we discussed above in the recursive section, the 1st subproblem we\'re solving is if our array is only length 3. This means we only have one triangle left to triangulate, so that\'s pretty easy right? If you are thinking about it logically, we start from the end of the game, where you have only 3 points left. This is the base case in our recursive function (well in our recursive function, it\'s if our array has less than 3 points, but we could rewrite it to return the product of the 3 last elements in our array). \n\nThis means that our dp table will be filled up in order of LENGTH of subproblems. We will first go over all the subproblems of an array of length 3. Once we know all that, we can do subproblems with arrays of length 4, and so on until we get our answer. Our answer should be dp[0][-1] because we want to know the minimum amount of points we can score if we use EVERYTHING in the array. \n\nIn case you are confused about the order of things getting filled out in the array: you can see that we fill out the array diagonally. I have numbered the order we fill out things in our dp array from 1 -> 10. This is what the order would look like for the [1,3,1,4,1,5] test case. You\'ll notice in each dp array that we don\'t fill out the 1st 2 columns. This is because there will always be at least 3 points left, so we start in col 3. \n\n[0, 0, **1, 5, 8,10]**\n[0, 0, 0, **2, 6, 9]**\n[0, 0, 0, 0, **3, 7]**\n[0, 0, 0, 0, 0, **4]**\n[0, 0, 0, 0, 0, 0]\n[0, 0, 0, 0, 0, 0]\n\nBelow is the code. Our first for loop `for l in xrange(2, n):` is written so we can solve the smallest subproblems first. We start from 2 because our subproblem must be at LEAST length 3 so we have 3 points in our triangle. Our 2nd for loop is a corner we use and call left. We then create our right corner by adding the length of our subproblem to left. Our k is the middle point in our triangle and must fall between left and right (so for left we do left + 1, remember in python that ranges do not include the last value, so we only go up to right - 1 for k). \n\nYou can make your dp table n*(n-2) length, but that\'s going to get confusing on indexes during your interview probably. It\'s going to require you check if you are out of bounds. and random -2 in certain indexes. \n\nWe set dp[left][right] to float("Inf") as a pseudomin since every value must be smaller. \n\n```\nclass Solution(object):\n def minScoreTriangulation(self, A):\n """\n :type A: List[int]\n :rtype: int\n """\n n = len(A)\n dp = [[0]*n for i in xrange(n)]\n for l in xrange(2, n):\n for left in xrange(0, n - l):\n right = left + l\n dp[left][right] = float("Inf")\n for k in xrange(left + 1, right):\n dp[left][right] = min(dp[left][right], dp[left][k] + dp[k][right] + A[left]*A[right]*A[k])\n return dp[0][-1]\n```\n\nComplexity: Runtime: O(N^3), Space: O(N^2) \n\n\nLast words: I wrote this all out so I could be sure I understood it in case it comes up in an interview. Do I think I could have gotten the DP in 45 minutes for an interview? Before this problem: absolutely not. After it: I still don\'t know. Honestly not sure. Hoping that the more I practice, the more I\'ll be able to see this faster. The recursive solution was reasonably simply, but that\'s brute force and got TLE with only 20 elements! I got confused on the 3 for loops in my DP solution when I was writing it. I had to print out the dp array to see how it was getting filled out and tried a bunch of different loops in order to get it correct. I should also note it took a few days of passive thinking on it (like when I\'m in the subway listening to music) for all 3 steps (recursion, memoization, DP) to finally click, so if you read this and don\'t understand it, just come back to it another day. Maybe your brain needs to sleep on it like mine did.
188
1
[]
12
minimum-score-triangulation-of-polygon
[Java/C++/Python] DP
javacpython-dp-by-lee215-z29z
Intuition\n\nThe connected two points in polygon shares one common edge,\nthese two points must be one and only one triangles.\n\n\n\n## Explanation\n\ndp[i][j]
lee215
NORMAL
2019-05-05T04:10:01.628050+00:00
2019-05-06T02:17:06.750368+00:00
17,140
false
## **Intuition**\n\nThe connected two points in polygon shares one common edge,\nthese two points must be one and only one triangles.\n\n<br>\n\n## **Explanation**\n\n`dp[i][j]` means the minimum score to triangulate `A[i] ~ A[j]`,\nwhile there is edge connect `A[i]` and `A[j]`.\n\nWe enumerate all points `A[k]` with `i < k < j` to form a triangle.\n\nThe score of this triangulation is `dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[j] * A[k]`\n\n<br>\n\n**Java, bottom-up:**\n```\n public int minScoreTriangulation(int[] A) {\n int n = A.length;\n int[][] dp = new int[n][n];\n for (int d = 2; d < n; ++d) {\n for (int i = 0; i + d < n; ++i) {\n int j = i + d;\n dp[i][j] = Integer.MAX_VALUE;\n for (int k = i + 1; k < j; ++k)\n dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[j] * A[k]);\n }\n }\n return dp[0][n - 1];\n }\n```\n\n**Java, bottom-up, another loop version**\n```\n public int minScoreTriangulation(int[] A) {\n int n = A.length;\n int[][] dp = new int[n][n];\n for (int j = 2; j < n; ++j) {\n for (int i = j - 2; i >= 0; --i) {\n dp[i][j] = Integer.MAX_VALUE;\n for (int k = i + 1; k < j; ++k)\n dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[j] * A[k]);\n }\n }\n return dp[0][n - 1];\n }\n```\n\n**C++, bottom-up:**\n```\n int minScoreTriangulation(vector<int>& A) {\n int n = A.size();\n vector<vector<int>> dp(n, vector<int>(n));\n for (int j = 2; j < n; ++j) {\n for (int i = j - 2; i >= 0; --i) {\n dp[i][j] = INT_MAX;\n for (int k = i + 1; k < j; ++k)\n dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[j] * A[k]);\n }\n }\n return dp[0][n - 1];\n }\n```\n\n**Python, bottom-up**\n```\n def minScoreTriangulation(self, A):\n n = len(A)\n dp = [[0] * n for i in xrange(n)]\n for d in xrange(2, n):\n for i in xrange(n - d):\n j = i + d\n dp[i][j] = min(dp[i][k] + dp[k][j] + A[i] * A[j] * A[k] for k in xrange(i + 1, j))\n return dp[0][n - 1]\n```\n\n**Python, top-down:**\n```\n def minScoreTriangulation(self, A):\n memo = {}\n def dp(i, j):\n if (i, j) not in memo:\n memo[i, j] = min([dp(i, k) + dp(k, j) + A[i] * A[j] * A[k] for k in range(i + 1, j)] or [0])\n return memo[i, j]\n return dp(0, len(A) - 1)\n```\n\n
186
8
[]
25
minimum-score-triangulation-of-polygon
[C++/Python] O(n^3) DP explanation + diagrams
cpython-on3-dp-explanation-diagrams-by-k-pvxg
Explanation: \n\nIn any valid triangulation, every edge of the polygon must be a part of exactly one triangle:\n If it werent part of a triangle, the polygon wo
karutz
NORMAL
2019-05-05T04:57:00.219269+00:00
2020-09-10T12:26:26.974406+00:00
4,891
false
**Explanation**: \n\nIn any valid triangulation, every edge of the polygon must be a part of exactly one triangle:\n* If it werent part of a triangle, the polygon wouldnt be fully triangulated.\n* If it were part of more than one triangle, those triangles would have to be overlapping.\n\nConsider the edge between the first and last vertices:\n![image](https://assets.leetcode.com/users/karutz/image_1557029962.png)\n\nIn general, there are `n - 2` choices of triangle for a polygon with `n` vertices.\nWe can try every triangle and solve the resulting subproblems recursively:\n\n![image](https://assets.leetcode.com/users/karutz/image_1557030892.png)\n\nUse dynamic programming to avoid recomputation and build smaller solutions into bigger ones.\n\n**Complexity**: \n\nThere are `O(n^2)` states: one for every subarray of `A`, `A[i:j], 0 <= i < j <= n`.\nEach state takes `O(n)` work.\n\nOverall complexity: `O(n^3)`.\n\n**Top-down Python3**:\n```python\nfrom functools import lru_cache\n\nclass Solution:\n def minScoreTriangulation(self, A):\n @lru_cache(None)\n def dp(i, j):\n if j - i + 1 < 3:\n return 0\n return min(A[i]*A[j]*A[k] + dp(i, k) + dp(k, j) for k in range(i + 1, j))\n return dp(0, len(A) - 1)\n```\n\n**Bottom-up C++**:\n```c++\nclass Solution {\npublic:\n int minScoreTriangulation(vector<int>& A) {\n int n = A.size();\n int dp[50][50] = {};\n for (int sz = 2; sz < n; sz++) {\n for (int i = 0; i + sz < n; i++) {\n int j = i + sz;\n dp[i][j] = 1e9;\n for (int k = i + 1; k < j; k++) {\n dp[i][j] = min(dp[i][j], A[i]*A[j]*A[k] + dp[i][k] + dp[k][j]);\n }\n }\n }\n return dp[0][n - 1];\n }\n};\n```
77
1
[]
9
minimum-score-triangulation-of-polygon
Problem Pattern | Matrix Chain Multiplication
problem-pattern-matrix-chain-multiplicat-jaod
If you have seen Balloon Burst and this problem, not able to find the solution .\nJust read the following pattern carefully .\n\nThese both are the child proble
reverenc
NORMAL
2021-10-11T05:53:54.682698+00:00
2021-10-11T06:40:00.581472+00:00
40,027
false
If you have seen Balloon Burst and this problem, not able to find the solution .\nJust read the following pattern carefully .\n\nThese both are the child problem of MCM .\n\nProblem : If a chain of matrices is given, we have to find the minimum number of the correct sequence of matrices to multiply.\n\n\nThe problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.\nNote:no matter how we parenthesize the product, the result will be the same. For example, if we had four matrices A, B, C, and D, we would have:\n\n(ABC)D = (AB)(CD) = A(BCD) = ....\nHowever, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency. For example, suppose A is a 10 \xD7 30 matrix, B is a 30 \xD7 5 matrix, and C is a 5 \xD7 60 matrix. Then,\n\n(AB)C = (10\xD730\xD75) + (10\xD75\xD760) = 1500 + 3000 = 4500 operations\nA(BC) = (30\xD75\xD760) + (10\xD730\xD760) = 9000 + 18000 = 27000 operations.\nClearly the first parenthesization requires less number of operations.\nNote ; We\'ll be given an array arr[ ] which represents the chain of matrices such that the ith matrix arr[i] is of dimension arr[i-1] x arr[i].\nThat\'s why we start out \'k\' i.e partition from \'i\' =1 so that arr[ 1] is of dimentions arr[1-1] * arr[1] else we\'ll get index out of bound error Eg arr[0-1] * arr[0] is not possible\nSo first half of the array is from i to k & other half is from k+1 to j\nAlso we need to find the cost of multiplication of these 2 resultant matrixes (first half & second half) which is nothing but arr[i-1] * arr[k] * arr[j]\n\nRecursion\nHere is the recursive algo :\n\n\nCode\n ```\n int solve(int i, int j,int arr[])\n {\n if(i>=j)return 0;\n\n int ans=INT_MAX;\n for(int k=i;k<=j-1;k++)\n {\n int tempAns = solve(i,k,arr) + solve(k+1,j,arr)\n + arr[i-1]*arr[k]*arr[j];\n \n ans=min(ans,tempAns); \n }\n return ans;\n }\n int matrixMultiplication(int N, int arr[])\n {\n return solve(1,N-1,arr);\n }\n```\nThe time complexity of the above naive recursive approach is exponential. Observe that the above function computes the same subproblems again and again.\n\nLet us saywe are given an array of 5 elements that means we are given N-1 i.e 4 matrixes .See the following recursion tree for a matrix chain of size 4.\nimage\n\nThere are so many overlapping subproblems . Let\'s optimize it using DP !!\n\nMemoization\nJust adding a few lines to the above code, we can reduce time complexity from exponential to cubic :\n\n\n```\nint dp[501][501];\n \n int solve(int i, int j,int arr[])\n {\n if(i>=j)return 0;\n \n if(dp[i][j]!=-1)\n return dp[i][j];\n\n int ans=INT_MAX;\n for(int k=i;k<=j-1;k++)\n {\n int tempAns = solve(i,k,arr) + solve(k+1,j,arr)\n + arr[i-1]*arr[k]*arr[j];\n \n ans=min(ans,tempAns);\n \n }\n return dp[i][j] = ans;\n }\n int matrixMultiplication(int N, int arr[])\n {\n memset(dp,-1,sizeof(dp));\n return solve(1,N-1,arr);\n }\n\t```\n\t\nBottom Up DP\nIt\'s a bit tricky but if you got the above logic then you woudn\'t face any issues. I stil, prefer the Momoization\n\n```\nint MatrixChainOrder(int arr[], int n)\n{\n \n /* For simplicity of the program, one\n extra row and one extra column are\n allocated in arr[][]. 0th row and 0th\n column of arr[][] are not used */\n int dp[n][n];\n \n int i, j, k, L, q;\n \n /* dp[i, j] = Minimum number of scalar\n multiplications needed to compute the\n matrix A[i]A[i+1]...A[j] = A[i..j] where\n dimension of A[i] is arr[i-1] x arr[i] */\n \n // cost is zero when multiplying\n // one matrix.\n for (i = 1; i < n; i++)\n dp[i][i] = 0;\n \n // L is chain length.\n for (L = 2; L < n; L++)\n {\n for (i = 1; i < n - L + 1; i++)\n {\n j = i + L - 1;\n dp[i][j] = INT_MAX;\n for (k = i; k <= j - 1; k++)\n {\n // q = cost/scalar multiplications\n q = dp[i][k] + dp[k + 1][j]\n + arr[i - 1] * arr[k] * arr[j];\n if (q < dp[i][j])\n dp[i][j] = q;\n }\n }\n }\n \n return dp[1][n - 1];\n}\n```\n
68
0
[]
4
minimum-score-triangulation-of-polygon
Intuitive Java Solution With Explanation
intuitive-java-solution-with-explanation-obzk
Few observations needed before discussing the approach.\n First observe that we only stop drawing inner edges, when we cannot form any more triangels. Obviously
naveen_kothamasu
NORMAL
2019-08-21T04:07:45.032609+00:00
2019-08-21T04:08:44.364189+00:00
1,981
false
Few observations needed before discussing the approach.\n* First observe that we only stop drawing inner edges, when we cannot form any more triangels. Obviously every such triangle has 1 edge from the given polygon or 2 edges. That means, the stop condition is all edges from the polygon are covered.\n* Also observe that it doesn\'t matter which triangle you are trying first. Ultimately, if it is part of optimal configuration, it will end up in the final solution (i.e. doesn\'t matter which subproblem formed that triangle, this will be more clear with the below pic).\n\n\n**Idea**\nUsing the above facts, for convenience we can fix the edge connecting first and last point and see how many triangles can this edge possible be part of (to begin with). And each of the possibilties divide the problem in two parts (left part and right part) and they can be solved recusrively. To repeat, it doesn\'t matter which edge you fix and try possibilities, the fixed edge will always settle with the optimal triangle irrespective of which edge you fix first but fixing other edges will not play well with array indicies.\n\nIn this pic, we fixed 0-5 edge and shown all 4 possilities.\n![image](https://assets.leetcode.com/users/naveenkothamasu/image_1566360233.png)\n\n\n\n\n**Solution1 (TLE)**\n```\npublic int minScoreTriangulation(int[] a) {\n return helper(a, 0, a.length-1);\n }\n private int helper(int[] a, int i, int j){\n if( (j-i+1) < 3) return 0;\n int min = Integer.MAX_VALUE;\n for(int k=i+1; k < j; k++)\n min = Math.min(min, helper(a, i, k)+a[i]*a[k]*a[j]+helper(a, k, j));\n return min;\n }\n```\n**Solution2 (DP)**\n```\nclass Solution {\n Integer[][] dp = null;\n public int minScoreTriangulation(int[] a) {\n dp = new Integer[a.length][a.length];\n return helper(a, 0, a.length-1);\n }\n private int helper(int[] a, int i, int j){\n if( (j-i+1) < 3) return 0;\n if(dp[i][j] != null) return dp[i][j];\n dp[i][j] = Integer.MAX_VALUE;\n for(int k=i+1; k < j; k++)\n dp[i][j] = Math.min(dp[i][j], helper(a, i, k)+a[i]*a[k]*a[j]+helper(a, k, j));\n return dp[i][j];\n }\n}\n```
39
0
[]
6
minimum-score-triangulation-of-polygon
Dynamic programming - clear solution
dynamic-programming-clear-solution-by-ha-1uan
Intuition and Algorithm\nThis problem is similar to: https://www.geeksforgeeks.org/minimum-cost-polygon-triangulation/\nWe can solved it with Dynamic programmin
hamlet_fiis
NORMAL
2019-05-05T04:00:36.732804+00:00
2019-05-08T02:32:34.702766+00:00
2,970
false
**Intuition and Algorithm**\nThis problem is similar to: https://www.geeksforgeeks.org/minimum-cost-polygon-triangulation/\nWe can solved it with Dynamic programming.\n<code>DP(pos1,pos2)</code> = min cost of triangulation of vertices from pos1 to pos2\n<code>if (pos2-pos1<2) return 0;</code> //its not possible to get any triangle\n<code>else DP(pos1,pos2)= min(DP(pos1,k)+ DP(k,pos2) + Cost(pos1,pos2,k)) ) </code>\nWhere <code> Cost(pos1,pos2,k)</code> is the cost of choose triangle with vertices <code>(pos1,pos2,k)</code> and <code>k</code> go from <code>pos1+1</code> to <code>pos2-1</code>\n**Approach 1 (Dynamic programming)**\n\n<code>\n\n\tclass Solution {\n\tpublic:\n\t\tint memo[51][51];\n\t\t\n\t\tint dp(int pos1,int pos2, vector<int>&A){\n\t\t\tif(pos2-pos1<=1)return 0;//no triangle\n\t\t\t\n\t\t\tif(memo[pos1][pos2]!=-1)return memo[pos1][pos2];\n\t\t\tint ans=1<<30;//initialize in large number\n\t\t\tfor(int i=pos1+1;i<pos2;i++)\n\t\t\t\tans=min(ans, dp(pos1,i,A) + dp(i,pos2,A) + A[pos1]*A[pos2]*A[i] );\n\t\t\t\n\t\t\t//I will check the triangle with vertices (pos1,pos2,i)\n\t\t\t\n\t\t\tmemo[pos1][pos2]=ans;\n\t\t\treturn ans;\n\t\t}\n\t\t\n\t\tint minScoreTriangulation(vector<int>& A) {\n\t\t\tmemset(memo,-1,sizeof(memo));\n\t\t\treturn dp(0,A.size()-1,A);\n\t\t}\n\t};\n\n</code>\n\n<b>Complexity Analysis </b>\n* Time Complexity: O(n ^3) where n is the length of A \n* Space Complexity: O(n^ 2) where n is the length of A
25
3
[]
3
minimum-score-triangulation-of-polygon
One More Graphical Explanation
one-more-graphical-explanation-by-coolgk-8eku
Firstly, we know the answer is\n\nanswer = min(combination 1, combination 2, ..., combination n)\n\nthe first step is calculate the first combination (triangle
coolgk
NORMAL
2020-10-29T23:54:41.723982+00:00
2020-10-30T00:09:38.812170+00:00
805
false
Firstly, we know the answer is\n\n**answer = min(combination 1, combination 2, ..., combination n)**\n\nthe first step is calculate the first combination (triangle combinations/triangulation)\n\n**If we pick an edge, ANY edge, this edge MUST be used by all the possible combinations/triangulations, because all combinations must use this edge to form a triangle.**\n\n**pick edge (0, 1)**\n\n![image](https://assets.leetcode.com/users/images/35f349e1-d7d2-468b-bd00-4d027ba6d922_1604013225.007506.png)\n\nAs shown above, we list all possible triangles formed with `edge (0, 1)` and these triangles must belong to different combinations/triangulations (because they overlap each other), and because all combinations must use `edge (0, 1)`, the number of triangles formed with `edge (0, 1)` must be the number of possible combinations/triangulations.\n\nso we can say:\n\ncombination 1 = a triangulation that must use triangle (0, 1, 2) where `(0, 1)` is the picked edge, `2` is one of the other vertices\ncombination 2 = a triangulation that must use triangle (0, 1, 3)\ncombination 3 = a triangulation that must use triangle (0, 1, 4)\n...\ncombination n = a triangulation that must use triangle (0, 1, n)\n\nso the formula becomes\n\n**answer = min( must_use_picked_edge_with_vertex_2, use_picked_edge_with_vertex_3, ... use_picked_edge_with_vertex_n )**\n\n**find the sub problem, calculate combination 1**\n\n**Combination 1 = Use the picked edge with a picked vertex**\n\nwe picked `edge (0, 1)` and we picked `vertex 2` to calculate the score, we need\n\n**triangle (0, 1, 2) score + (min (combination 1, combination 2, ..., combination n) of shape(0, 2, 3, 4, 5))**\n\n![image](https://assets.leetcode.com/users/images/8a54a08b-e851-450b-8add-6e91bfd6dc64_1604014673.7222793.png)\n\n**Min score of (0, 2, 3, 4, 5) is now a sub problem**\n\n**same trick, we pick an edge, ANY edge, then pick a vertex to make a triangle, we calcualte: triangle + min(rest of the shape)** in this case: triangle (0,2,5) + shape(2,3,4,5)\n\n![image](https://assets.leetcode.com/users/images/bf903638-320a-4d21-8f96-b0b1cd44ccba_1604015162.7413847.png)\n\n**calculate combination 2**\n\nWe have done combination/triangulation 1, we still need to calculate 2, 3 ... n and use the **min**\n\n**use the same edge (0,1), pick the next vertex, this time we have more shapes, we need**\n\n**min(shape left) + triangle + min(shape right)**\n\n![image](https://assets.leetcode.com/users/images/48bc6739-2331-43d3-8f16-03740f268541_1604015347.0816524.png)\n\n**min (shape left) and min (shape right) are both sub problems, we have done one sub problem in combination 1, we can use the same trick to calculate both left and right**\n\nBased on this logic, coding the answer should be relatively easy now\n\n```javascript\nfunction rc (vertices, edge = [0, 1], lastVertex = vertices.length - 1, memo = {}) {\n const memoKey = `${edge.join(\',\')},${lastVertex}`;\n if (memo[memoKey] !== undefined) return memo[memoKey];\n\n const [edgeStartVertex, edgeEndVertex] = edge;\n\n let min = Infinity;\n\n for (let i = edgeEndVertex + 1; i <= lastVertex; i++) {\n const mustUseTriangleScore = vertices[edgeStartVertex] * vertices[edgeEndVertex] * vertices[i];\n const leftSideMinScore = i > edgeEndVertex + 1 ? rc(vertices, [edgeEndVertex, edgeEndVertex + 1], i, memo) : 0;\n const rightSideMinScore = i < lastVertex ? rc(vertices, [edgeStartVertex, i], lastVertex, memo) : 0;\n min = Math.min(min, leftSideMinScore + mustUseTriangleScore + rightSideMinScore);\n }\n\n return memo[memoKey] = min;\n}\n\nfunction rc2 (vertices, startVertex = 0, endVertex = vertices.length - 1, memo = {}) {\n if (endVertex - startVertex < 2) return 0;\n \n const memoKey = `${startVertex},${endVertex}`;\n if (memo[memoKey] !== undefined) return memo[memoKey];\n \n let min = Infinity;\n \n for (let i = startVertex + 1; i < endVertex; i++) {\n const mustUseTriangleScore = vertices[startVertex] * vertices[endVertex] * vertices[i];\n const leftSideMinScore = rc2(vertices, startVertex, i, memo);\n const rightSideMinScore = rc2(vertices, i, endVertex, memo);\n min = Math.min(min, leftSideMinScore + mustUseTriangleScore + rightSideMinScore);\n }\n \n return memo[memoKey] = min;\n}\n\nfunction dp (vertices) {\n const dp = Array(vertices.length).fill(0).map(() => Array(vertices.length).fill(0));\n \n for (let start = vertices.length - 1; start >= 0; start--) {\n for (let end = start + 2 ; end < vertices.length; end++) {\n \n let min = Infinity;\n for (let vertex = start + 1; vertex < end; vertex++) {\n const mustUseTriangleScore = vertices[start] * vertices[end] * vertices[vertex];\n const leftSideMinScore = dp[start][vertex];\n const rightSideMinScore = dp[vertex][end];\n min = Math.min(min, leftSideMinScore + mustUseTriangleScore + rightSideMinScore);\n }\n dp[start][end] = min;\n }\n }\n \n return dp[0][vertices.length - 1];\n}\n```\n
19
0
[]
3
minimum-score-triangulation-of-polygon
Java memoization DP solution
java-memoization-dp-solution-by-tankztc-6wpp
\nclass Solution {\n public int minScoreTriangulation(int[] A) {\n return dfs(A, 0, A.length - 1, new Integer[A.length][A.length]);\n }\n \n
tankztc
NORMAL
2019-05-05T05:14:10.966383+00:00
2019-05-11T18:55:27.505879+00:00
1,255
false
```\nclass Solution {\n public int minScoreTriangulation(int[] A) {\n return dfs(A, 0, A.length - 1, new Integer[A.length][A.length]);\n }\n \n int dfs(int[] A, int i, int j, Integer[][] memo) {\n if (j < i + 2) return 0; // base case: you can\'t form a triangle with less than 3 points\n \n if (memo[i][j] != null) return memo[i][j];\n \n int res = Integer.MAX_VALUE;\n for (int k = i + 1; k < j; ++k) {\n res = Math.min(res, dfs(A, i, k, memo) + dfs(A, k, j, memo) + A[i] * A[k] * A[j]);\n }\n \n memo[i][j] = res;\n return memo[i][j];\n }\n}\n```\n\nBottom up DP: \n```\nclass Solution {\n public int minScoreTriangulation(int[] A) {\n int[][] dp = new int[A.length][A.length];\n \n for (int i = A.length - 1; i >= 0; --i) {\n for (int j = i+2; j < A.length; ++j) {\n dp[i][j] = Integer.MAX_VALUE;\n for (int k = i + 1; k < j; ++k) {\n dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[k] * A[j]);\n }\n }\n }\n \n return dp[0][A.length - 1];\n }\n}\n```
16
2
[]
2
minimum-score-triangulation-of-polygon
C++ simple memoization
c-simple-memoization-by-deleted_user-6s3a
\nclass Solution {\npublic:\n int minimum_area(vector<int> &A,int si,int ei,vector<vector<int>>&dp){\n if(si+1==ei) return 0;\n \n if(dp
deleted_user
NORMAL
2020-08-10T14:18:20.647729+00:00
2020-08-10T14:18:20.647776+00:00
1,692
false
```\nclass Solution {\npublic:\n int minimum_area(vector<int> &A,int si,int ei,vector<vector<int>>&dp){\n if(si+1==ei) return 0;\n \n if(dp[si][ei]!=0) return dp[si][ei];\n \n int ans=INT_MAX;\n for(int cut=si+1;cut<ei;cut++){\n \n int leftAns=minimum_area(A,si,cut,dp);\n int rightAns=minimum_area(A,cut,ei,dp);\n \n int myAns=leftAns+(A[si]*A[cut]*A[ei])+rightAns;\n \n ans=min(ans,myAns);\n }\n \n return dp[si][ei]=ans;\n }\n int minScoreTriangulation(vector<int>& A) {\n int n=A.size();\n vector<vector<int>>dp(n,vector<int>(n,0));\n return minimum_area(A,0,n-1,dp);\n }\n \n};\n```
14
0
['Dynamic Programming', 'Memoization', 'C', 'C++']
1
minimum-score-triangulation-of-polygon
EASY | C++ | Matrix Chain Multiplication | Memoization | Aditya Verma Solution
easy-c-matrix-chain-multiplication-memoi-1ei3
Kindly Upvote if you find this useful\n\nThis question is smiliar to Matrix Chain Multiplication\n\nclass Solution {\npublic:\n int dp[1002][1002];\n int
stepheneliazer18
NORMAL
2022-01-16T16:02:22.621171+00:00
2022-01-16T16:02:22.621215+00:00
482
false
**Kindly Upvote if you find this useful**\n\nThis question is smiliar to Matrix Chain Multiplication\n```\nclass Solution {\npublic:\n int dp[1002][1002];\n int solve(vector<int> arr, int i,int j){\n if(i>=j) return 0;\n \n if(dp[i][j]!=-1) return dp[i][j];\n \n int ans = INT_MAX;\n for(int k=i;k<j;k++){\n \n int temp = solve(arr,i,k) + solve(arr,k+1,j) + (arr[i-1] * arr[k] * arr[j]);\n ans = min(ans,temp);\n }\n return dp[i][j] = ans;\n }\n int minScoreTriangulation(vector<int>& values) {\n memset(dp,-1,sizeof(dp));\n return solve(values,1,values.size()-1);\n }\n};\n```\n**Kindly Upvote if you find this useful**
8
0
[]
0
minimum-score-triangulation-of-polygon
Java - Recursive -> Memoization -> 2D Bottom Up
java-recursive-memoization-2d-bottom-up-rky3i
\n- If we currently have a range of numbers from indices \'i -> k\'\n\t- Then the two numbers at \'i\' and \'k\' can be the corners of two vertices\n\t\t- Then
david2999999
NORMAL
2020-09-30T16:19:30.389908+00:00
2020-09-30T16:19:30.389993+00:00
575
false
```\n- If we currently have a range of numbers from indices \'i -> k\'\n\t- Then the two numbers at \'i\' and \'k\' can be the corners of two vertices\n\t\t- Then the last corner \'j\' can be a number from indices \'i + 1 -> k - 1\'\n\t- We can then continue to build triangles using the indices from \'i -> j\' and \'j -> k\'\n- We will pick the index \'j\' that will give us the least total score\n```\n```\npublic class MinimumScoreTriangulationOfPolygonRecursiveApproach {\n public int minScoreTriangulation(int[] A) {\n return minScoreTriangulation(0, A.length - 1, A);\n }\n\n private int minScoreTriangulation(int i, int k, int[] A) {\n if (k - i <= 1) return 0;\n\n int minScore = Integer.MAX_VALUE;\n\n for (int j = i + 1; j < k; j++) {\n minScore = Math.min(minScore,\n minScoreTriangulation(i, j, A) + minScoreTriangulation(j, k, A) + (A[i] * A[j] * A[k]));\n }\n\n return minScore;\n }\n}\n```\n```\npublic class MinimumScoreTriangulationOfPolygonMemoizationApproach {\n public int minScoreTriangulation(int[] A) {\n return minScoreTriangulation(0, A.length - 1, A, new int[A.length][A.length]);\n }\n\n private int minScoreTriangulation(int i, int k, int[] A, int[][] memo) {\n if (k - i <= 1) return 0;\n if (memo[i][k] != 0) return memo[i][k];\n\n int minScore = Integer.MAX_VALUE;\n\n for (int j = i + 1; j < k; j++) {\n minScore = Math.min(minScore,\n minScoreTriangulation(i, j, A, memo) + minScoreTriangulation(j, k, A, memo) + (A[i] * A[j] * A[k]));\n }\n\n return memo[i][k] = minScore;\n }\n}\n```\n```\npublic class MinimumScoreTriangulationOfPolygonBottomUp2DApproach {\n public int minScoreTriangulation(int[] A) {\n int[][] minScores = new int[A.length][A.length];\n\n for (int i = A.length - 1; i >= 0; i--) {\n for (int k = 0; k < A.length; k++) {\n if (k - i <= 1) continue;\n\n minScores[i][k] = Integer.MAX_VALUE;\n\n for (int j = i + 1; j < k; j++) {\n minScores[i][k] = Math.min(minScores[i][k],\n minScores[i][j] + minScores[j][k] + A[i] * A[j] * A[k]);\n }\n }\n }\n\n return minScores[0][A.length - 1];\n }\n}\n```
8
0
[]
1
minimum-score-triangulation-of-polygon
2 Approaches || Recursion+Memoization(Top-Down) & Tabulation(Bottom-Up) || Beats 100%
2-approaches-recursionmemoizationtop-dow-ahb4
Intuition: \nThe problem is a classic example of dynamic programming on sequences. The key observation is that any triangulation of the polygon can be divided i
prayashbhuria931
NORMAL
2024-08-05T17:06:25.220782+00:00
2024-08-17T06:09:49.976985+00:00
311
false
# Intuition: \nThe problem is a classic example of dynamic programming on sequences. The key observation is that any triangulation of the polygon can be divided into smaller triangulations. By solving smaller subproblems and using their results to build up the solution for larger problems, we can efficiently find the minimum score triangulation.\n\n\n# Approach 1: Recursive Approach (Top-Down with Memoization):\n\n- This method involves breaking down the problem into smaller subproblems.\n- For a given range [i,j], the goal is to find the minimum score triangulation of the subpolygon.\n- The base case is when i+1=j, meaning no triangle can be formed.\n- For each potential vertex \uD835\uDC58 between i and j, compute the cost of the triangulation that includes triangle (i,k,j) and recursively solve the subproblems [i,k] and [k,j].\n- Use memoization to store results of subproblems to avoid redundant calculations.\n\n\n# Complexity\n- Time complexity: O(n^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nprivate: \n int solveMem(vector<int> &values,int i,int j, vector<vector<int>> &dp)\n {\n //Base case\n if(i+1==j) return 0;\n\n if(dp[i][j]!=-1) return dp[i][j];\n\n int ans=INT_MAX;\n\n for(int k=i+1;k<j;k++)\n {\n ans=min(ans,values[i]*values[j]*values[k]+solveMem(values,i,k,dp)+solveMem(values,k,j,dp));\n }\n dp[i][j]=ans;\n return dp[i][j];\n }\n\npublic:\n int minScoreTriangulation(vector<int>& values) {\n int n=values.size();\n\n vector<vector<int>> dp(n,vector<int> (n,-1));\n return solveMem(values,0,n-1,dp);\n }\n};\n```\n\n# Approach 2: Tabulation(Bottom-Up Approach)::\n\n- Use a 2D DP array dp where dp[i][j] represents the minimum score to triangulate the subpolygon from vertex i to vertex j.\n- Initialize dp such that dp[i][i + 1] = 0 because no triangle can be formed with less than 3 vertices.\n- Iterate over all possible subpolygon lengths starting from 2 up to the total number of vertices.\n- For each subpolygon [i,j], compute the minimum score by trying all possible vertices k between i and j and updating dp[i][j] with the minimum value.\n\n# Complexity\n- Time complexity: O(n^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution {\nprivate: \n int solveTab(vector<int> &values)\n {\n int n=values.size();\n\n vector<vector<int>> dp(n,vector<int> (n,0));\n\n\n for(int i=n-1;i>=0;i--)\n {\n for(int j=i+2;j<n;j++)\n {\n int ans=INT_MAX;\n for(int k=i+1;k<j;k++)\n {\n ans=min(ans,values[i]*values[j]*values[k]+dp[i][k]+dp[k][j]);\n }\n dp[i][j]=ans;\n }\n\n }\n return dp[0][n-1];\n }\n\npublic:\n int minScoreTriangulation(vector<int>& values) {\n return solveTab(values);\n }\n};\n```\n![upvote.jpg](https://assets.leetcode.com/users/images/9326e095-db55-47e0-84c8-63273e105c5b_1722878627.159309.jpeg)\n
5
0
['Recursion', 'Memoization', 'C++']
2
minimum-score-triangulation-of-polygon
Easy C++ Solution using Memoization
easy-c-solution-using-memoization-by-200-3e5w
\n# Approach\nThe problem involves finding the minimum score for triangulating a polygon formed by the given values. Each value represents the vertices of the p
2005115
NORMAL
2023-07-11T14:19:19.021860+00:00
2023-07-11T14:19:19.021877+00:00
357
false
\n# Approach\nThe problem involves finding the minimum score for triangulating a polygon formed by the given values. Each value represents the vertices of the polygon.\n\nDefine a helper function solve that takes the vector of values, the indices i and j representing the range of values to consider, and the memoization array dp as parameters.\n\nIn the solve function, check the base case where i+1==j. If this condition is true, it means there are only two vertices, and no triangle can be formed. Return 0 in this case.\n\nCheck if the result for the current range i to j is already computed and stored in the memoization array dp. If it is, return the precomputed result dp[i][j].\n\nInitialize a variable ans with a large value (INT_MAX), which will be used to store the minimum score for triangulation.\n\nIterate from k=i+1 to k<j to find the optimal split point for triangulation. Calculate the score for the current split point by multiplying values[i], values[j], and values[k] and adding it to the scores of triangulating the two resulting sub-polygons (solve(values, i, k, dp) and solve(values, k, j, dp)).\n\nUpdate ans with the minimum score found among all the split points.\n\nStore the computed minimum score ans in the memoization array dp[i][j] for future reference.\n\nReturn the minimum score for triangulating the given range i to j.\n\nIn the minScoreTriangulation function, initialize the memoization array dp with -1 values.\n\nCall the solve function with the initial range from 0 to n-1, where n is the size of the values vector.\n\nReturn the result obtained from the solve function.\n\nThis approach utilizes memoization to avoid redundant calculations and optimize the solution. It breaks down the problem into smaller subproblems and calculates the minimum score for each subproblem. The minimum score for the overall problem is obtained from the results of these subproblems.\n<!-- Describe your approach to solving the problem. -->\n\nr space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nint solve(vector<int>& values,int i ,int j ,vector<vector<int>>&dp)\n{\n // BASE CASE CHECK IF THE FIRST ELEMENT AND LAST ELEMENT ARE TOGETHER OR NOT \n if(i+1==j)\n {\n return 0;\n }\n if(dp[i][j]!=-1)\n return dp[i][j];\n int ans = INT_MAX;\n for(int k=i+1;k<j;k++)\n {\n ans = min(ans , values[i]*values[j]*values[k]+solve(values,i,k,dp)+solve(values, k, j , dp));\n }\n dp[i][j]=ans;\n return dp[i][j];\n\n}\n int minScoreTriangulation(vector<int>& values)\n {\n int n = values.size();\n vector<vector<int>>dp(n,vector<int>(n,-1));\n return solve(values,0,n-1,dp); \n }\n};\n```
5
0
['Dynamic Programming', 'C++']
0
minimum-score-triangulation-of-polygon
[C++] Clean and concise DP solution | O(n^3)
c-clean-and-concise-dp-solution-on3-by-s-bfll
Please upvote if it helps!\n\nclass Solution {\npublic:\n int func(vector<int>& a, int i, int j, vector<vector<int>>& dp)\n {\n if(j<=(i+1))\n
somurogers
NORMAL
2021-06-23T03:11:22.812243+00:00
2021-06-23T03:11:22.812291+00:00
603
false
Please upvote if it helps!\n```\nclass Solution {\npublic:\n int func(vector<int>& a, int i, int j, vector<vector<int>>& dp)\n {\n if(j<=(i+1))\n return 0;\n if(dp[i][j]!=-1)\n return dp[i][j];\n \n int ans=INT_MAX;\n for(int k=i+1;k<j;k++)\n {\n int temp = (a[i]*a[j]*a[k]) + func(a,i,k,dp) + func(a,k,j,dp);\n ans = min(ans,temp);\n }\n return dp[i][j] = ans;\n }\n \n int minScoreTriangulation(vector<int>& a) {\n int n=a.size();\n vector<vector<int>> dp(n+1, vector<int>(n+1,-1));\n int ans = func(a,0,n-1,dp);\n return ans;\n }\n};\n```
5
0
['Dynamic Programming', 'C', 'C++']
1
minimum-score-triangulation-of-polygon
Java | Recursive | Memoization | Divde and conquer | (2 ms) with clear explanation.
java-recursive-memoization-divde-and-con-wlw7
class Solution {\n \n Integer[][] dp ;\n \n public int minScoreTriangulation(int[] A) {\n dp= new Integer[A.length][A.length];\n retur
saikumar112
NORMAL
2021-02-06T23:22:44.043178+00:00
2021-02-06T23:22:44.043211+00:00
306
false
class Solution {\n \n Integer[][] dp ;\n \n public int minScoreTriangulation(int[] A) {\n dp= new Integer[A.length][A.length];\n return helper(A, 0, A.length-1);\n }\n \n private int helper(int[] nums, int left, int right){\n \n // base condition when we have sides less than three. \n if(left+2>right) return 0;\n \n if(dp[left][right]!=null) return dp[left][right];\n \n int val=Integer.MAX_VALUE;\n \n // The main intuition is to take first and last values as the base \n //and try all other indices to form a triangle.\n // Once the traingle is formed with the first, index, left ,\n //calculate the cost and split the remaining into left and right sub parts \n //calculate those left and right recursively.\n \n for(int i=left+1; i<right; i++){\n int leftSum = helper(nums, left, i);\n int rightSum = helper(nums, i, right);\n int current = nums[i]*nums[left]*nums[right];\n val=Math.min(val, current+leftSum + rightSum);\n }\n \n return dp[left][right]=val;\n } \n}
5
0
[]
0
minimum-score-triangulation-of-polygon
Java Top Down solution, Beats 99.56%
java-top-down-solution-beats-9956-by-iro-t2t7
This is an example of dynamic programming problem of finding the answer for left part and right part and then combining the solutions.\n\nhttps://leetcode.com/d
ironman04
NORMAL
2020-04-26T00:33:01.472051+00:00
2020-04-26T00:36:03.840703+00:00
353
false
This is an example of dynamic programming problem of finding the answer for left part and right part and then combining the solutions.\n\nhttps://leetcode.com/discuss/general-discussion/458695/dynamic-programming-patterns#Merging-Intervals\n\n```\nclass Solution {\n public int minScoreTriangulation(int[] A) {\n int[][] cache = new int[A.length][A.length];\n return helper(A,0,A.length-1,cache);\n }\n private int helper(int[] A,int i,int j,int[][] cache){\n // if number of vertices is less than 2, you can\'t do anything\n if(j-i<2)\n return 0;\n // if number of vertices is equal to 3, then you can easily find the answer by\n //multiplying the vertices value\n if(j-i == 2)\n return A[i]*A[i+1]*A[j];\n \n if(cache[i][j]!=0)\n return cache[i][j];\n int min = Integer.MAX_VALUE;\n //sol(i,j) = sol(i,k)+sol(k,j)+A[i]*A[k]*A[j];\n for(int k = i+1 ; k<j;k++){\n min = Math.min(min,helper(A,i,k,cache)+helper(A,k,j,cache)+A[i]*A[k]*A[j]);\n }\n cache[i][j] = min;\n return min;\n \n }\n}\n```
5
0
[]
0
minimum-score-triangulation-of-polygon
3 Methods || easy to understand || 2D DP
3-methods-easy-to-understand-2d-dp-by-sa-ca1y
PLEASE READ FULL EXPLANATION AND UPVOTE IF YOU UNDERSTAND THE SOLUTIONS\n# Intuition\nIn the question it is given that the array values is in clockwise directio
sanjay_soni
NORMAL
2023-03-08T06:29:51.310754+00:00
2023-03-08T06:29:51.310795+00:00
607
false
PLEASE READ FULL EXPLANATION AND UPVOTE IF YOU UNDERSTAND THE SOLUTIONS\n# Intuition\nIn the question it is given that the array values is in clockwise direction it means first element and last element are adjacent\n\n# Approach\n1. take first = i and last = j index as base\n2. now we have last - first indexes left for making a triangle let it be k\n3. now we have a triangle of i, j, k and other part left from i to k and k to j\n4. so call recursively for i and k as base and k and j as base and add it to i*j*k\n5. return the minimum \n\n# Code\n```\nclass Solution {\npublic:\n int solve(vector<int> &vec, int i, int j){\n if(i+1 == j) return 0;\n\n int ans = INT_MAX;\n for(int k = i+1; k < j; k++){\n ans = min(ans, vec[i]*vec[j]*vec[k] + solve(vec,i,k) + solve(vec,k,j));\n }\n return ans;\n }\n int minScoreTriangulation(vector<int>& values) {\n return solve(values,0,values.size()-1);\n }\n};\n```\n# Intuition\nin above solution there is overlapping subproblems to it can be solved by dynamic programming \nin above solution 2 parameters are changing so we need a 2d dp\n\n# Approach top down dp\n1. create a 2d dp array of size n+1*n+1 and initialize with -1\n2. store ans in dp[i][j] and return\n3. after base case check if ans is already stored or not\n4. if stored return ans\n5. else call recursion\n\n# Code\n```\nclass Solution {\npublic:\n int solve(vector<int> &vec, int i, int j,vector<vector<int>> &dp){\n if(i+1 == j) return 0;\n\n if(dp[i][j] != -1) return dp[i][j];\n int ans = INT_MAX;\n for(int k = i+1; k < j; k++){\n ans = min(ans, vec[i]*vec[j]*vec[k] + solve(vec,i,k,dp) + solve(vec,k,j,dp));\n }\n dp[i][j] = ans;\n return dp[i][j];\n }\n int minScoreTriangulation(vector<int>& values) {\n int n = values.size();\n vector<vector<int>> dp(n+1,vector<int>(n+1,-1));\n return solve(values,0,n-1,dp);\n }\n};\n```\n# Approach BOTTOM UP DP\n1. create a 2d dp array of size n*n and initialize with 0\n2. analyse base case \n3. since it is a bottom up approach so we traverse from n-1 to 0 for first point (i) of base\n4. and second point of base we traverse form i+2 to n because i+1 can\'t equal to j for making a base\n5. now from i to j make calculate ans like previous approaches by assuming a third point k\n6. return dp[0][n-1]\n\n# Code\n```\nclass Solution {\npublic:\n int minScoreTriangulation(vector<int>& values) {\n int n = values.size();\n vector<vector<int>> dp(n,vector<int>(n,0));\n\n for(int i = n-1; i >= 0; i--){\n for(int j = i+2; j < n; j++){\n int ans = INT_MAX;\n for(int k = i+1; k < j; k++){\n ans = min(ans, values[i]*values[j]*values[k] + dp[i][k] + dp[k][j]);\n }\n dp[i][j] = ans;\n }\n }\n return dp[0][n-1];\n }\n};\n```
4
0
['C++']
1
minimum-score-triangulation-of-polygon
Java - Easiest Solution [both approaches ]
java-easiest-solution-both-approaches-by-rykc
Hi Family,\n\nI put the proper commen in the code Please have a look and if you liked the code Please upvote.\n\n\n// Top To Bottom\n\n\nclass Solution {\n i
singhmohit9718
NORMAL
2022-09-16T14:18:06.723807+00:00
2022-09-16T14:34:28.429172+00:00
588
false
Hi Family,\n\nI put the proper commen in the code Please have a look and if you liked the code Please upvote.\n\n\n// Top To Bottom\n```\n\nclass Solution {\n int dp[][];\n public int minScoreTriangulation(int[] values) {\n int n = values.length;\n dp = new int[n][n];\n for (int i=0;i<n;i++) Arrays.fill(dp[i],-1);\n // call the function with i = 1, j = n-1\n // because every time we have to take the ar[i-1] that\'s why we are starting from i = 1\n return helper_min_score(1,n-1,values);\n }\n \n private int helper_min_score(int i,int j,int values[]){\n if (i == j) return 0;\n \n if (dp[i][j] != -1) return dp[i][j];\n \n int mini = Integer.MAX_VALUE;\n // do partition\n \n for (int k=i;k<=j-1;k++){\n int steps = values[i-1] * values[k] * values[j]\n + helper_min_score(i,k,values)// partition 1\n + helper_min_score(k+1,j,values); // partition 2\n mini = Math.min(steps,mini);\n }\n \n return dp[i][j] = mini;\n }\n}\n\n```\n\n**Bottom To Top**\n```\n\npublic int minScoreTriangulation(int[] values) {\n \n int n = values.length;\n int dp[][] = new int[n][n];\n \n // no need to initialize the dp for base case. because all the values are already 0 in dp initially\n \n for (int i=n-1;i>=1;i--){\n for (int j=i+1;j<n;j++){\n int mini = Integer.MAX_VALUE;\n // for partition\n for (int k=i;k<=j-1;k++){\n int steps = values[i-1] * values[k] * values[j] + dp[i][k] + dp[k+1][j];\n mini = Math.min(mini,steps);\n }\n dp[i][j] = mini;\n }\n }\n return dp[1][n-1];\n \n }\n\n```\n\nThanks!!!
4
0
['Dynamic Programming', 'Memoization', 'Java']
0
minimum-score-triangulation-of-polygon
C++||DP||MCM-Pattern||Easy&Understandale
cdpmcm-patterneasyunderstandale-by-princ-2y45
\nclass Solution {\npublic:\n int solve(vector<int>&values,int i,int j,vector<vector<int>>&dp){\n if(i>=j)\n return 0;\n if(dp[i][j]
prince_725
NORMAL
2022-06-26T11:22:09.872085+00:00
2022-06-26T11:22:09.872126+00:00
644
false
```\nclass Solution {\npublic:\n int solve(vector<int>&values,int i,int j,vector<vector<int>>&dp){\n if(i>=j)\n return 0;\n if(dp[i][j]!=-1){\n return dp[i][j];\n } \n int minm = INT_MAX;\n \n for(int k=i;k<j;k++){\n int left = (dp[i][k]!=-1)? dp[i][k] : solve(values,i,k,dp);\n int right = (dp[k+1][j]!=-1)? dp[k+1][j] : solve(values,k+1,j,dp);\n int temp = left + right + values[i-1]*values[k]*values[j];\n minm = min(minm,temp);\n }\n return dp[i][j] = minm; \n }\n int minScoreTriangulation(vector<int>& values) {\n int n = values.size();\n vector<vector<int>> dp(n+1,vector<int>(n+1,-1));\n return solve(values,1,n-1,dp); \n }\n};\n```
4
0
['Dynamic Programming', 'C']
0
minimum-score-triangulation-of-polygon
C++ Solution || Gap Strategy with explanation
c-solution-gap-strategy-with-explanation-0n9l
In order to solve this problem we will use the Gap Strategy of dynamic programming.\n1. In this strategy we use a 2D array of n x n and then we assign some mean
thanoschild
NORMAL
2022-02-25T09:11:25.161952+00:00
2022-02-25T09:11:25.161979+00:00
356
false
In order to solve this problem we will use the Gap Strategy of dynamic programming.\n1. In this strategy we use a 2D array of n x n and then we assign some meaning to the cells of the 2D array.\n2. Then we fill the matrix diagonally, moving from smaller problems to the bigger problem.\n\n**Approach**\n\n>**->** In the dp, rows will correspond to the first vertex which is fixed (i) and columns correspond to the second vertex which is fixed (j) of the polygon (or sub-polygon).\n**->** So at any cell we store the minimum score of triangulation of the sub-polygon that starts with ith vertex and ends with jth vertex in clockwise direction.\n**->** Now talking of the first relevant diagonal; this diagonal represents the scenario, if there were only one vertex in a sub polygon, it will be zero as no triangulation is possible and therefore no score.\n**->** Second diagonal is also dealt in the same way. As there will be no triangulations possible so the cost will also be zero.\n**->** Moving to the next diagonal; we see that this diagonal represents a sub polygon with three vertices. So it means that the polygon is already triangulated. Therefore this diagonal will store the product of values corresponding to each vertex.\n**->** In the next diagonal, to calculate the minimum score of triangulation of a quadrilateral, we have to consider 2 possibilities.\n**->** And the minimum of both these values will be stored at dp which is the final result for this problem.\n```\nclass Solution {\npublic:\n int minScoreTriangulation(vector<int>& values) {\n int n = values.size();\n vector<vector<int>> dp(n, vector<int>(n));\n for(int g = 0; g<n; g++){\n for(int i=0, j = g; j<n; i++, j++){\n if(g == 0){\n dp[i][j] = 0;\n }\n else if(g == 1){\n dp[i][j] = 0;\n }\n else if(g == 2){\n dp[i][j] = values[i]*values[j]*values[i+1];\n }\n else{\n int minval = 1e8;\n for(int k = i+1; k<=j-1; k++){\n int tri = values[i]*values[k]*values[j];\n int left = dp[i][k];\n int right = dp[k][j];\n int total = tri + left + right;\n minval = min(minval, total);\n }\n dp[i][j] = minval;\n }\n }\n }\n return dp[0][n-1]; \n }\n};\n```
4
0
['Dynamic Programming', 'C']
0
minimum-score-triangulation-of-polygon
Java+DP(MCM Variation)+ with Time-Space Analysis
javadpmcm-variation-with-time-space-anal-1rvd
Time Complexity: O(n^3) since we use 2 nested for loops enclosed with a k(i -> j) loop for every dp[i][j]. \nSpace Complexity: O(n^2) Since, we are using an n
ikanishk__
NORMAL
2022-02-19T14:20:11.280718+00:00
2022-04-05T08:33:55.168215+00:00
568
false
**Time Complexity:** O(n^3) since we use 2 nested for loops enclosed with a k(i -> j) loop for every dp[i][j]. \n**Space Complexity:** O(n^2) Since, we are using an n * n matrix.\n```\nclass Solution {\n public int minScoreTriangulation(int[] arr) {\n int[][] dp = new int[arr.length][arr.length];\n for (int g = 2; g < dp.length; g++) {\n for (int i = 0, j = g; j < dp[0].length; i++, j++) {\n if (g == 2) {\n dp[i][j] = arr[i] * arr[i + 1] * arr[i + 2];\n }\n\n else {\n int min = Integer.MAX_VALUE;\n for (int k = i + 1; k <= j - 1; k++) {\n int leftpart = dp[i][k];\n int rightpart = dp[k][j];\n int triangle = arr[i] * arr[j] * arr[k];\n\n int total = leftpart + rightpart + triangle;\n min=Math.min(min,total);\n }\n dp[i][j] = min;\n }\n }\n \n }\n return dp[0][dp[0].length - 1]; \n }\n}\n```
4
0
['Dynamic Programming', 'Java']
1
minimum-score-triangulation-of-polygon
MCM Pattern | Little Variation | C++ Concise Solution
mcm-pattern-little-variation-c-concise-s-d870
class Solution {\npublic:\n \n int helper(vector& values, int i,int j,vector>&dp)\n {\n // initialization \n if(i>=j) return 0;\n
thechildwholovesyou
NORMAL
2021-09-25T04:56:46.350570+00:00
2021-09-25T04:56:46.350603+00:00
162
false
class Solution {\npublic:\n \n int helper(vector<int>& values, int i,int j,vector<vector<int>>&dp)\n {\n // initialization \n if(i>=j) return 0;\n if(i+1==j) return 0; // when we cannot make a triange \n // imagine the case when index paased are 0,1 or 2,3 and so on \n \n if(dp[i][j]!=-1) return dp[i][j];\n \n int mini=INT_MAX;\n \n for(int k=i+1;k<j;k++)\n {\n int tempAns = helper(values,i,k,dp) + helper(values,k,j,dp)+ (values[i]*values[k]*values[j]);\n \n mini=min(mini, tempAns);\n }\n dp[i][j]=mini;\n return mini;\n }\n \n int minScoreTriangulation(vector<int>& values) {\n vector<vector<int>>dp(values.size()+1, vector<int>(values.size()+1, -1));\n return helper(values,0,values.size()-1,dp);\n }\n};
4
0
[]
1
minimum-score-triangulation-of-polygon
The tricky point: find a way to divide the problem
the-tricky-point-find-a-way-to-divide-th-1966
Foremost, I want to say this problem is not good for interview because it depends a tricky insights about how to divide the problem. For the record, I\'ve never
luanjunyi
NORMAL
2021-01-19T20:31:23.161530+00:00
2021-01-19T20:33:11.548281+00:00
182
false
Foremost, I want to say this problem is not good for interview because it depends a tricky insights about how to divide the problem. For the record, I\'ve never encountered this hard problems in any top tier company(FB, Google) from L3 to L6 interviews(coding is hardest at L3 and L4).\n\nThere are multiple ways to divide and conqur, however, it\'s tough to find a scheme where the number of subproblems is small enough so as to memorized(or DP if you wish).\n\nI spent over one hour to find one such scheme: for one edge in the original polygon, it must be connected with one \'other\' vertex to form a triangle(other means not the two vertex making the edge). Iterate all such vertexes, each vertex correspond to one way of dividing the orignial problem. Recursively divide and conqure. I always use memorized search since it\'s much easier to reason with and impelment.\n\n```python\nclass Solution:\n def minScoreTriangulation(self, arr: List[int]) -> int:\n n = len(arr)\n \n @lru_cache(None)\n def solve(begin, end):\n if (begin + 1) % n == end:\n return 0\n \n ret = -1\n \n split = (begin + 1) % n\n while split != end:\n cur = arr[begin] * arr[end] * arr[split] + solve(begin, split) + solve(split, end)\n if ret == -1 or ret > cur:\n ret = cur\n split = (split + 1) % n\n return ret\n \n return solve(0, n - 1)\n```
4
0
[]
1
minimum-score-triangulation-of-polygon
C++ Top Down Faster than 100%
c-top-down-faster-than-100-by-guptaprati-44v2
\nclass Solution {\npublic:\n int dp[105][105];\n int minScore(vector<int>& A, int i, int k) {\n if( k < i + 2)\n return 0;\n \n
guptapratik104
NORMAL
2020-12-03T17:45:16.837582+00:00
2020-12-03T17:45:16.837628+00:00
224
false
```\nclass Solution {\npublic:\n int dp[105][105];\n int minScore(vector<int>& A, int i, int k) {\n if( k < i + 2)\n return 0;\n \n if(dp[i][k] != -1)\n return dp[i][k];\n \n int minm = INT_MAX;\n \n for(int j = i+1; j < k; j++) {\n minm = min(minm, minScore(A,i,j) + minScore(A,j,k) + A[i]*A[j]*A[k]);\n }\n return dp[i][k] = minm;\n }\n int minScoreTriangulation(vector<int>& A) {\n int i = 0, k = A.size()-1;\n int n = A.size();\n //dp.resize(n+1, vector<int>(n+1, -1));\n memset(dp, -1, sizeof(dp));\n return minScore(A, i, k);\n }\n};\n```
4
0
[]
0
minimum-score-triangulation-of-polygon
Top-down and bottom-up DP
top-down-and-bottom-up-dp-by-xing_yi-5h8k
\nclass Solution:\n def minScoreTriangulation(self, A: List[int]) -> int:\n L = len(A)\n memo = []\n for i in range(L):\n mem
xing_yi
NORMAL
2020-09-07T04:54:26.172873+00:00
2020-09-07T04:54:26.172917+00:00
236
false
```\nclass Solution:\n def minScoreTriangulation(self, A: List[int]) -> int:\n L = len(A)\n memo = []\n for i in range(L):\n memo.append([-1 for _ in range(L)])\n \n def dp(start, end):\n if end - start < 2:\n return 0\n if end - start == 2:\n return A[start] * A[start+1] * A[start+2]\n if memo[start][end] != -1:\n return memo[start][end]\n \n ret = float("inf")\n for i in range(start+1, end):\n ret = min(ret, A[start] * A[end] * A[i] + dp(start, i) + dp(i, end))\n memo[start][end] = ret\n return ret\n return dp(0, L-1)\n```\n\n```\nclass Solution:\n def minScoreTriangulation(self, A: List[int]) -> int:\n L = len(A)\n memo = []\n for start in range(L):\n memo.append([float("inf") for i in range(L)])\n memo[start][(start+1) % L] = 0\n memo[start][(start+2) % L] = A[start] * A[(start+1) % L] * A[(start+2) % L]\n for delta in range(3, L):\n for start in range(L):\n end = start + delta\n if end >= L: break\n for i in range(start+1, end):\n memo[start][end] = min(memo[start][end], A[start] * A[end] * A[i] + memo[start][i] + memo[i][end])\n \n return memo[0][-1]\n```
4
0
[]
0