{
    "data": {
        "question": {
            "questionId": "1186",
            "questionFrontendId": "1117",
            "boundTopicId": null,
            "title": "Building H2O",
            "titleSlug": "building-h2o",
            "content": "<p>There are two kinds of threads: <code>oxygen</code> and <code>hydrogen</code>. Your goal is to group these threads to form water molecules.</p>\n\n<p>There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given <code>releaseHydrogen</code> and <code>releaseOxygen</code> methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.</p>\n\n<p>In other words:</p>\n\n<ul>\n\t<li>If an oxygen thread arrives at the barrier when no hydrogen threads are present, it must wait for two hydrogen threads.</li>\n\t<li>If a hydrogen thread arrives at the barrier when no other threads are present, it must wait for an oxygen thread and another hydrogen thread.</li>\n</ul>\n\n<p>We do not have to worry about matching the threads up explicitly; the threads do not necessarily know which other threads they are paired up with. The key is that threads pass the barriers in complete sets; thus, if we examine the sequence of threads that bind and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.</p>\n\n<p>Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.</p>\n\n<p>&nbsp;</p>\n<p><strong>Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> water = &quot;HOH&quot;\n<strong>Output:</strong> &quot;HHO&quot;\n<strong>Explanation:</strong> &quot;HOH&quot; and &quot;OHH&quot; are also valid answers.\n</pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> water = &quot;OOHHHH&quot;\n<strong>Output:</strong> &quot;HHOHHO&quot;\n<strong>Explanation:</strong> &quot;HOHHHO&quot;, &quot;OHHHHO&quot;, &quot;HHOHOH&quot;, &quot;HOHHOH&quot;, &quot;OHHHOH&quot;, &quot;HHOOHH&quot;, &quot;HOHOHH&quot; and &quot;OHHOHH&quot; are also valid answers.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>3 * n == water.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n\t<li><code>water[i]</code> is either <code>&#39;H&#39;</code> or <code>&#39;O&#39;</code>.</li>\n\t<li>There will be exactly <code>2 * n</code> <code>&#39;H&#39;</code> in <code>water</code>.</li>\n\t<li>There will be exactly <code>n</code> <code>&#39;O&#39;</code> in <code>water</code>.</li>\n</ul>\n",
            "translatedTitle": null,
            "translatedContent": null,
            "isPaidOnly": false,
            "difficulty": "Medium",
            "likes": 330,
            "dislikes": 89,
            "isLiked": null,
            "similarQuestions": "[]",
            "exampleTestcases": "\"HOH\"\n\"OOHHHH\"",
            "categoryTitle": "Concurrency",
            "contributors": [],
            "topicTags": [
                {
                    "name": "Concurrency",
                    "slug": "concurrency",
                    "translatedName": null,
                    "__typename": "TopicTagNode"
                }
            ],
            "companyTagStats": null,
            "codeSnippets": [
                {
                    "lang": "C++",
                    "langSlug": "cpp",
                    "code": "class H2O {\npublic:\n    H2O() {\n        \n    }\n\n    void hydrogen(function<void()> releaseHydrogen) {\n        \n        // releaseHydrogen() outputs \"H\". Do not change or remove this line.\n        releaseHydrogen();\n    }\n\n    void oxygen(function<void()> releaseOxygen) {\n        \n        // releaseOxygen() outputs \"O\". Do not change or remove this line.\n        releaseOxygen();\n    }\n};",
                    "__typename": "CodeSnippetNode"
                },
                {
                    "lang": "Java",
                    "langSlug": "java",
                    "code": "class H2O {\n\n    public H2O() {\n        \n    }\n\n    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {\n\t\t\n        // releaseHydrogen.run() outputs \"H\". Do not change or remove this line.\n        releaseHydrogen.run();\n    }\n\n    public void oxygen(Runnable releaseOxygen) throws InterruptedException {\n        \n        // releaseOxygen.run() outputs \"O\". Do not change or remove this line.\n\t\treleaseOxygen.run();\n    }\n}",
                    "__typename": "CodeSnippetNode"
                },
                {
                    "lang": "Python",
                    "langSlug": "python",
                    "code": "class H2O(object):\n    def __init__(self):\n        pass\n\n\n    def hydrogen(self, releaseHydrogen):\n        \"\"\"\n        :type releaseHydrogen: method\n        :rtype: void\n        \"\"\"\n        \n        # releaseHydrogen() outputs \"H\". Do not change or remove this line.\n        releaseHydrogen()\n\n\n    def oxygen(self, releaseOxygen):\n        \"\"\"\n        :type releaseOxygen: method\n        :rtype: void\n        \"\"\"\n        \n        # releaseOxygen() outputs \"O\". Do not change or remove this line.\n        releaseOxygen()",
                    "__typename": "CodeSnippetNode"
                },
                {
                    "lang": "Python3",
                    "langSlug": "python3",
                    "code": "class H2O:\n    def __init__(self):\n        pass\n\n\n    def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None:\n        \n        # releaseHydrogen() outputs \"H\". Do not change or remove this line.\n        releaseHydrogen()\n\n\n    def oxygen(self, releaseOxygen: 'Callable[[], None]') -> None:\n        \n        # releaseOxygen() outputs \"O\". Do not change or remove this line.\n        releaseOxygen()",
                    "__typename": "CodeSnippetNode"
                },
                {
                    "lang": "C",
                    "langSlug": "c",
                    "code": "typedef struct {\n    // User defined data may be declared here.\n    \n} H2O;\n\nH2O* h2oCreate() {\n    H2O* obj = (H2O*) malloc(sizeof(H2O));\n    \n    // Initialize user defined data here.\n    \n    return obj;\n}\n\nvoid hydrogen(H2O* obj) {\n    \n    // releaseHydrogen() outputs \"H\". Do not change or remove this line.\n    releaseHydrogen();\n}\n\nvoid oxygen(H2O* obj) {\n    \n    // releaseOxygen() outputs \"O\". Do not change or remove this line.\n    releaseOxygen();\n}\n\nvoid h2oFree(H2O* obj) {\n    // User defined data may be cleaned up here.\n    \n}",
                    "__typename": "CodeSnippetNode"
                },
                {
                    "lang": "C#",
                    "langSlug": "csharp",
                    "code": "public class H2O {\n\n    public H2O() {\n        \n    }\n\n    public void Hydrogen(Action releaseHydrogen) {\n\t\t\n        // releaseHydrogen() outputs \"H\". Do not change or remove this line.\n        releaseHydrogen();\n    }\n\n    public void Oxygen(Action releaseOxygen) {\n        \n        // releaseOxygen() outputs \"O\". Do not change or remove this line.\n\t\treleaseOxygen();\n    }\n}",
                    "__typename": "CodeSnippetNode"
                }
            ],
            "stats": "{\"totalAccepted\": \"28.9K\", \"totalSubmission\": \"53.2K\", \"totalAcceptedRaw\": 28918, \"totalSubmissionRaw\": 53155, \"acRate\": \"54.4%\"}",
            "hints": [],
            "solution": null,
            "status": null,
            "sampleTestCase": "\"HOH\"",
            "metaData": "{\n  \"name\": \"H2O\",\n  \"params\": [\n    {\n      \"name\": \"water\",\n      \"type\": \"string\"\n    }\n  ],\n  \"return\": {\n    \"type\": \"string\"\n  },\n  \"languages\": [\n    \"java\",\n    \"cpp\",\n    \"python\",\n    \"python3\",\n    \"csharp\",\n    \"c\"\n  ],\n  \"manual\": true\n}",
            "judgerAvailable": true,
            "judgeType": "large",
            "mysqlSchemas": [],
            "enableRunCode": true,
            "enableTestMode": false,
            "enableDebugger": false,
            "envInfo": "{\"cpp\": [\"C++\", \"<p>Compiled with <code> clang 11 </code> using the latest C++ 17 standard.</p>\\r\\n\\r\\n<p>Your code is compiled with level two optimization (<code>-O2</code>). <a href=\\\"https://github.com/google/sanitizers/wiki/AddressSanitizer\\\" target=\\\"_blank\\\">AddressSanitizer</a> is also enabled to help detect out-of-bounds and use-after-free bugs.</p>\\r\\n\\r\\n<p>Most standard library headers are already included automatically for your convenience.</p>\"], \"java\": [\"Java\", \"<p><code> OpenJDK 17 </code>. Java 8 features such as lambda expressions and stream API can be used. </p>\\r\\n\\r\\n<p>Most standard library headers are already included automatically for your convenience.</p>\\r\\n<p>Includes <code>Pair</code> class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.</p>\"], \"python\": [\"Python\", \"<p><code>Python 2.7.12</code>.</p>\\r\\n\\r\\n<p>Most libraries are already imported automatically for your convenience, such as <a href=\\\"https://docs.python.org/2/library/array.html\\\" target=\\\"_blank\\\">array</a>, <a href=\\\"https://docs.python.org/2/library/bisect.html\\\" target=\\\"_blank\\\">bisect</a>, <a href=\\\"https://docs.python.org/2/library/collections.html\\\" target=\\\"_blank\\\">collections</a>. If you need more libraries, you can import it yourself.</p>\\r\\n\\r\\n<p>For Map/TreeMap data structure, you may use <a href=\\\"http://www.grantjenks.com/docs/sortedcontainers/\\\" target=\\\"_blank\\\">sortedcontainers</a> library.</p>\\r\\n\\r\\n<p>Note that Python 2.7 <a href=\\\"https://www.python.org/dev/peps/pep-0373/\\\" target=\\\"_blank\\\">will not be maintained past 2020</a>. For the latest Python, please choose Python3 instead.</p>\"], \"c\": [\"C\", \"<p>Compiled with <code>gcc 8.2</code> using the gnu99 standard.</p>\\r\\n\\r\\n<p>Your code is compiled with level one optimization (<code>-O1</code>). <a href=\\\"https://github.com/google/sanitizers/wiki/AddressSanitizer\\\" target=\\\"_blank\\\">AddressSanitizer</a> is also enabled to help detect out-of-bounds and use-after-free bugs.</p>\\r\\n\\r\\n<p>Most standard library headers are already included automatically for your convenience.</p>\\r\\n\\r\\n<p>For hash table operations, you may use <a href=\\\"https://troydhanson.github.io/uthash/\\\" target=\\\"_blank\\\">uthash</a>. \\\"uthash.h\\\" is included by default. Below are some examples:</p>\\r\\n\\r\\n<p><b>1. Adding an item to a hash.</b>\\r\\n<pre>\\r\\nstruct hash_entry {\\r\\n    int id;            /* we'll use this field as the key */\\r\\n    char name[10];\\r\\n    UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n    HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n</pre>\\r\\n</p>\\r\\n\\r\\n<p><b>2. Looking up an item in a hash:</b>\\r\\n<pre>\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n    struct hash_entry *s;\\r\\n    HASH_FIND_INT(users, &user_id, s);\\r\\n    return s;\\r\\n}\\r\\n</pre>\\r\\n</p>\\r\\n\\r\\n<p><b>3. Deleting an item in a hash:</b>\\r\\n<pre>\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n</pre>\\r\\n</p>\"], \"csharp\": [\"C#\", \"<p><a href=\\\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9\\\" target=\\\"_blank\\\">C# 10 with .NET 6 runtime</a></p>\\r\\n\\r\\n<p>Your code is compiled with debug flag enabled (<code>/debug</code>).</p>\"], \"python3\": [\"Python3\", \"<p><code>Python 3.10</code>.</p>\\r\\n\\r\\n<p>Most libraries are already imported automatically for your convenience, such as <a href=\\\"https://docs.python.org/3/library/array.html\\\" target=\\\"_blank\\\">array</a>, <a href=\\\"https://docs.python.org/3/library/bisect.html\\\" target=\\\"_blank\\\">bisect</a>, <a href=\\\"https://docs.python.org/3/library/collections.html\\\" target=\\\"_blank\\\">collections</a>. If you need more libraries, you can import it yourself.</p>\\r\\n\\r\\n<p>For Map/TreeMap data structure, you may use <a href=\\\"http://www.grantjenks.com/docs/sortedcontainers/\\\" target=\\\"_blank\\\">sortedcontainers</a> library.</p>\"]}",
            "libraryUrl": null,
            "adminUrl": null,
            "challengeQuestion": null,
            "__typename": "QuestionNode"
        }
    }
}