{ "data": { "question": { "questionId": "1186", "questionFrontendId": "1117", "boundTopicId": null, "title": "Building H2O", "titleSlug": "building-h2o", "content": "

There are two kinds of threads: oxygen and hydrogen. Your goal is to group these threads to form water molecules.

\n\n

There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen 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.

\n\n

In other words:

\n\n\n\n

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.

\n\n

Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.

\n\n

 

\n

Example 1:

\n\n
\nInput: water = "HOH"\nOutput: "HHO"\nExplanation: "HOH" and "OHH" are also valid answers.\n
\n\n

Example 2:

\n\n
\nInput: water = "OOHHHH"\nOutput: "HHOHHO"\nExplanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Medium", "likes": 491, "dislikes": 128, "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 releaseHydrogen) {\n \n // releaseHydrogen() outputs \"H\". Do not change or remove this line.\n releaseHydrogen();\n }\n\n void oxygen(function 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\": \"44.8K\", \"totalSubmission\": \"80.1K\", \"totalAcceptedRaw\": 44807, \"totalSubmissionRaw\": 80077, \"acRate\": \"56.0%\"}", "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++\", \"

Compiled with clang 11 using the latest C++ 20 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 17. Java 8 features such as lambda expressions and stream API can be used.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"c\": [\"C\", \"

Compiled with gcc 8.2 using the gnu11 standard.

\\r\\n\\r\\n

Your code is compiled with level one optimization (-O1). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n\\r\\n

For hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:

\\r\\n\\r\\n

1. Adding an item to a hash.\\r\\n

\\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
\\r\\n

\\r\\n\\r\\n

2. Looking up an item in a hash:\\r\\n

\\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
\\r\\n

\\r\\n\\r\\n

3. Deleting an item in a hash:\\r\\n

\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n
\\r\\n

\"], \"csharp\": [\"C#\", \"

C# 10 with .NET 6 runtime

\"], \"python3\": [\"Python3\", \"

Python 3.10.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }