{ "data": { "question": { "questionId": "2104", "questionFrontendId": "1993", "boundTopicId": null, "title": "Operations on Tree", "titleSlug": "operations-on-tree", "content": "

You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.

\n\n

The data structure should support the following functions:

\n\n\n\n

Implement the LockingTree class:

\n\n\n\n

 

\n

Example 1:

\n\"\"\n
\nInput\n["LockingTree", "lock", "unlock", "unlock", "lock", "upgrade", "lock"]\n[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]\nOutput\n[null, true, false, true, true, true, false]\n\nExplanation\nLockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\nlockingTree.lock(2, 2);    // return true because node 2 is unlocked.\n                           // Node 2 will now be locked by user 2.\nlockingTree.unlock(2, 3);  // return false because user 3 cannot unlock a node locked by user 2.\nlockingTree.unlock(2, 2);  // return true because node 2 was previously locked by user 2.\n                           // Node 2 will now be unlocked.\nlockingTree.lock(4, 5);    // return true because node 4 is unlocked.\n                           // Node 4 will now be locked by user 5.\nlockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n                           // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\nlockingTree.lock(0, 1);    // return false because node 0 is already locked.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Medium", "likes": 210, "dislikes": 37, "isLiked": null, "similarQuestions": "[{\"title\": \"Throne Inheritance\", \"titleSlug\": \"throne-inheritance\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "exampleTestcases": "[\"LockingTree\",\"lock\",\"unlock\",\"unlock\",\"lock\",\"upgrade\",\"lock\"]\n[[[-1,0,0,1,1,2,2]],[2,2],[2,3],[2,2],[4,5],[0,1],[0,1]]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Hash Table", "slug": "hash-table", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Tree", "slug": "tree", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Breadth-First Search", "slug": "breadth-first-search", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Design", "slug": "design", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "class LockingTree {\npublic:\n LockingTree(vector& parent) {\n \n }\n \n bool lock(int num, int user) {\n \n }\n \n bool unlock(int num, int user) {\n \n }\n \n bool upgrade(int num, int user) {\n \n }\n};\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * LockingTree* obj = new LockingTree(parent);\n * bool param_1 = obj->lock(num,user);\n * bool param_2 = obj->unlock(num,user);\n * bool param_3 = obj->upgrade(num,user);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "class LockingTree {\n\n public LockingTree(int[] parent) {\n \n }\n \n public boolean lock(int num, int user) {\n \n }\n \n public boolean unlock(int num, int user) {\n \n }\n \n public boolean upgrade(int num, int user) {\n \n }\n}\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * LockingTree obj = new LockingTree(parent);\n * boolean param_1 = obj.lock(num,user);\n * boolean param_2 = obj.unlock(num,user);\n * boolean param_3 = obj.upgrade(num,user);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "class LockingTree(object):\n\n def __init__(self, parent):\n \"\"\"\n :type parent: List[int]\n \"\"\"\n \n\n def lock(self, num, user):\n \"\"\"\n :type num: int\n :type user: int\n :rtype: bool\n \"\"\"\n \n\n def unlock(self, num, user):\n \"\"\"\n :type num: int\n :type user: int\n :rtype: bool\n \"\"\"\n \n\n def upgrade(self, num, user):\n \"\"\"\n :type num: int\n :type user: int\n :rtype: bool\n \"\"\"\n \n\n\n# Your LockingTree object will be instantiated and called as such:\n# obj = LockingTree(parent)\n# param_1 = obj.lock(num,user)\n# param_2 = obj.unlock(num,user)\n# param_3 = obj.upgrade(num,user)", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "class LockingTree:\n\n def __init__(self, parent: List[int]):\n \n\n def lock(self, num: int, user: int) -> bool:\n \n\n def unlock(self, num: int, user: int) -> bool:\n \n\n def upgrade(self, num: int, user: int) -> bool:\n \n\n\n# Your LockingTree object will be instantiated and called as such:\n# obj = LockingTree(parent)\n# param_1 = obj.lock(num,user)\n# param_2 = obj.unlock(num,user)\n# param_3 = obj.upgrade(num,user)", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "\n\n\ntypedef struct {\n \n} LockingTree;\n\n\nLockingTree* lockingTreeCreate(int* parent, int parentSize) {\n \n}\n\nbool lockingTreeLock(LockingTree* obj, int num, int user) {\n \n}\n\nbool lockingTreeUnlock(LockingTree* obj, int num, int user) {\n \n}\n\nbool lockingTreeUpgrade(LockingTree* obj, int num, int user) {\n \n}\n\nvoid lockingTreeFree(LockingTree* obj) {\n \n}\n\n/**\n * Your LockingTree struct will be instantiated and called as such:\n * LockingTree* obj = lockingTreeCreate(parent, parentSize);\n * bool param_1 = lockingTreeLock(obj, num, user);\n \n * bool param_2 = lockingTreeUnlock(obj, num, user);\n \n * bool param_3 = lockingTreeUpgrade(obj, num, user);\n \n * lockingTreeFree(obj);\n*/", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "public class LockingTree {\n\n public LockingTree(int[] parent) {\n \n }\n \n public bool Lock(int num, int user) {\n \n }\n \n public bool Unlock(int num, int user) {\n \n }\n \n public bool Upgrade(int num, int user) {\n \n }\n}\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * LockingTree obj = new LockingTree(parent);\n * bool param_1 = obj.Lock(num,user);\n * bool param_2 = obj.Unlock(num,user);\n * bool param_3 = obj.Upgrade(num,user);\n */", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {number[]} parent\n */\nvar LockingTree = function(parent) {\n \n};\n\n/** \n * @param {number} num \n * @param {number} user\n * @return {boolean}\n */\nLockingTree.prototype.lock = function(num, user) {\n \n};\n\n/** \n * @param {number} num \n * @param {number} user\n * @return {boolean}\n */\nLockingTree.prototype.unlock = function(num, user) {\n \n};\n\n/** \n * @param {number} num \n * @param {number} user\n * @return {boolean}\n */\nLockingTree.prototype.upgrade = function(num, user) {\n \n};\n\n/** \n * Your LockingTree object will be instantiated and called as such:\n * var obj = new LockingTree(parent)\n * var param_1 = obj.lock(num,user)\n * var param_2 = obj.unlock(num,user)\n * var param_3 = obj.upgrade(num,user)\n */", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "class LockingTree\n\n=begin\n :type parent: Integer[]\n=end\n def initialize(parent)\n \n end\n\n\n=begin\n :type num: Integer\n :type user: Integer\n :rtype: Boolean\n=end\n def lock(num, user)\n \n end\n\n\n=begin\n :type num: Integer\n :type user: Integer\n :rtype: Boolean\n=end\n def unlock(num, user)\n \n end\n\n\n=begin\n :type num: Integer\n :type user: Integer\n :rtype: Boolean\n=end\n def upgrade(num, user)\n \n end\n\n\nend\n\n# Your LockingTree object will be instantiated and called as such:\n# obj = LockingTree.new(parent)\n# param_1 = obj.lock(num, user)\n# param_2 = obj.unlock(num, user)\n# param_3 = obj.upgrade(num, user)", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "\nclass LockingTree {\n\n init(_ parent: [Int]) {\n \n }\n \n func lock(_ num: Int, _ user: Int) -> Bool {\n \n }\n \n func unlock(_ num: Int, _ user: Int) -> Bool {\n \n }\n \n func upgrade(_ num: Int, _ user: Int) -> Bool {\n \n }\n}\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * let obj = LockingTree(parent)\n * let ret_1: Bool = obj.lock(num, user)\n * let ret_2: Bool = obj.unlock(num, user)\n * let ret_3: Bool = obj.upgrade(num, user)\n */", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "type LockingTree struct {\n \n}\n\n\nfunc Constructor(parent []int) LockingTree {\n \n}\n\n\nfunc (this *LockingTree) Lock(num int, user int) bool {\n \n}\n\n\nfunc (this *LockingTree) Unlock(num int, user int) bool {\n \n}\n\n\nfunc (this *LockingTree) Upgrade(num int, user int) bool {\n \n}\n\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * obj := Constructor(parent);\n * param_1 := obj.Lock(num,user);\n * param_2 := obj.Unlock(num,user);\n * param_3 := obj.Upgrade(num,user);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "class LockingTree(_parent: Array[Int]) {\n\n def lock(num: Int, user: Int): Boolean = {\n \n }\n\n def unlock(num: Int, user: Int): Boolean = {\n \n }\n\n def upgrade(num: Int, user: Int): Boolean = {\n \n }\n\n}\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * var obj = new LockingTree(parent)\n * var param_1 = obj.lock(num,user)\n * var param_2 = obj.unlock(num,user)\n * var param_3 = obj.upgrade(num,user)\n */", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "class LockingTree(parent: IntArray) {\n\n fun lock(num: Int, user: Int): Boolean {\n \n }\n\n fun unlock(num: Int, user: Int): Boolean {\n \n }\n\n fun upgrade(num: Int, user: Int): Boolean {\n \n }\n\n}\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * var obj = LockingTree(parent)\n * var param_1 = obj.lock(num,user)\n * var param_2 = obj.unlock(num,user)\n * var param_3 = obj.upgrade(num,user)\n */", "__typename": "CodeSnippetNode" }, { "lang": "Rust", "langSlug": "rust", "code": "struct LockingTree {\n\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl LockingTree {\n\n fn new(parent: Vec) -> Self {\n \n }\n \n fn lock(&self, num: i32, user: i32) -> bool {\n \n }\n \n fn unlock(&self, num: i32, user: i32) -> bool {\n \n }\n \n fn upgrade(&self, num: i32, user: i32) -> bool {\n \n }\n}\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * let obj = LockingTree::new(parent);\n * let ret_1: bool = obj.lock(num, user);\n * let ret_2: bool = obj.unlock(num, user);\n * let ret_3: bool = obj.upgrade(num, user);\n */", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "class LockingTree {\n /**\n * @param Integer[] $parent\n */\n function __construct($parent) {\n \n }\n \n /**\n * @param Integer $num\n * @param Integer $user\n * @return Boolean\n */\n function lock($num, $user) {\n \n }\n \n /**\n * @param Integer $num\n * @param Integer $user\n * @return Boolean\n */\n function unlock($num, $user) {\n \n }\n \n /**\n * @param Integer $num\n * @param Integer $user\n * @return Boolean\n */\n function upgrade($num, $user) {\n \n }\n}\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * $obj = LockingTree($parent);\n * $ret_1 = $obj->lock($num, $user);\n * $ret_2 = $obj->unlock($num, $user);\n * $ret_3 = $obj->upgrade($num, $user);\n */", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "class LockingTree {\n constructor(parent: number[]) {\n\n }\n\n lock(num: number, user: number): boolean {\n\n }\n\n unlock(num: number, user: number): boolean {\n\n }\n\n upgrade(num: number, user: number): boolean {\n\n }\n}\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * var obj = new LockingTree(parent)\n * var param_1 = obj.lock(num,user)\n * var param_2 = obj.unlock(num,user)\n * var param_3 = obj.upgrade(num,user)\n */", "__typename": "CodeSnippetNode" }, { "lang": "Racket", "langSlug": "racket", "code": "(define locking-tree%\n (class object%\n (super-new)\n\n ; parent : (listof exact-integer?)\n (init-field\n parent)\n \n ; lock : exact-integer? exact-integer? -> boolean?\n (define/public (lock num user)\n\n )\n ; unlock : exact-integer? exact-integer? -> boolean?\n (define/public (unlock num user)\n\n )\n ; upgrade : exact-integer? exact-integer? -> boolean?\n (define/public (upgrade num user)\n\n )))\n\n;; Your locking-tree% object will be instantiated and called as such:\n;; (define obj (new locking-tree% [parent parent]))\n;; (define param_1 (send obj lock num user))\n;; (define param_2 (send obj unlock num user))\n;; (define param_3 (send obj upgrade num user))", "__typename": "CodeSnippetNode" }, { "lang": "Erlang", "langSlug": "erlang", "code": "-spec locking_tree_init_(Parent :: [integer()]) -> any().\nlocking_tree_init_(Parent) ->\n .\n\n-spec locking_tree_lock(Num :: integer(), User :: integer()) -> boolean().\nlocking_tree_lock(Num, User) ->\n .\n\n-spec locking_tree_unlock(Num :: integer(), User :: integer()) -> boolean().\nlocking_tree_unlock(Num, User) ->\n .\n\n-spec locking_tree_upgrade(Num :: integer(), User :: integer()) -> boolean().\nlocking_tree_upgrade(Num, User) ->\n .\n\n\n%% Your functions will be called as such:\n%% locking_tree_init_(Parent),\n%% Param_1 = locking_tree_lock(Num, User),\n%% Param_2 = locking_tree_unlock(Num, User),\n%% Param_3 = locking_tree_upgrade(Num, User),\n\n%% locking_tree_init_ will be called before every test case, in which you can do some necessary initializations.", "__typename": "CodeSnippetNode" }, { "lang": "Elixir", "langSlug": "elixir", "code": "defmodule LockingTree do\n @spec init_(parent :: [integer]) :: any\n def init_(parent) do\n\n end\n\n @spec lock(num :: integer, user :: integer) :: boolean\n def lock(num, user) do\n\n end\n\n @spec unlock(num :: integer, user :: integer) :: boolean\n def unlock(num, user) do\n\n end\n\n @spec upgrade(num :: integer, user :: integer) :: boolean\n def upgrade(num, user) do\n\n end\nend\n\n# Your functions will be called as such:\n# LockingTree.init_(parent)\n# param_1 = LockingTree.lock(num, user)\n# param_2 = LockingTree.unlock(num, user)\n# param_3 = LockingTree.upgrade(num, user)\n\n# LockingTree.init_ will be called before every test case, in which you can do some necessary initializations.", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"6.7K\", \"totalSubmission\": \"15.9K\", \"totalAcceptedRaw\": 6713, \"totalSubmissionRaw\": 15949, \"acRate\": \"42.1%\"}", "hints": [ "How can we use the small constraints to help us solve the problem?", "How can we traverse the ancestors and descendants of a node?" ], "solution": null, "status": null, "sampleTestCase": "[\"LockingTree\",\"lock\",\"unlock\",\"unlock\",\"lock\",\"upgrade\",\"lock\"]\n[[[-1,0,0,1,1,2,2]],[2,2],[2,3],[2,2],[4,5],[0,1],[0,1]]", "metaData": "{\n \"classname\": \"LockingTree\",\n \"constructor\": {\n \"params\": [\n {\n \"type\": \"integer[]\",\n \"name\": \"parent\"\n }\n ]\n },\n \"methods\": [\n {\n \"params\": [\n {\n \"type\": \"integer\",\n \"name\": \"num\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"user\"\n }\n ],\n \"name\": \"lock\",\n \"return\": {\n \"type\": \"boolean\"\n }\n },\n {\n \"params\": [\n {\n \"type\": \"integer\",\n \"name\": \"num\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"user\"\n }\n ],\n \"name\": \"unlock\",\n \"return\": {\n \"type\": \"boolean\"\n }\n },\n {\n \"params\": [\n {\n \"type\": \"integer\",\n \"name\": \"num\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"user\"\n }\n ],\n \"name\": \"upgrade\",\n \"return\": {\n \"type\": \"boolean\"\n }\n }\n ],\n \"return\": {\n \"type\": \"boolean\"\n },\n \"systemdesign\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 17 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 gnu99 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

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

Your code is compiled with debug flag enabled (/debug).

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

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

Your code is run with --harmony flag, enabling new ES6 features.

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

lodash.js library is included by default.

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

For Priority Queue / Queue data structures, you may use datastructures-js/priority-queue and datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.1

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

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.5.2.

\"], \"golang\": [\"Go\", \"

Go 1.17.6.

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

Support https://godoc.org/github.com/emirpasic/gods library.

\"], \"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.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.3.10.

\"], \"rust\": [\"Rust\", \"

Rust 1.58.1

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

Supports rand v0.6\\u00a0from crates.io

\"], \"php\": [\"PHP\", \"

PHP 8.1.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 4.5.4, Node.js 16.13.2.

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

Your code is run with --harmony flag, enabling new ES2020 features.

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

lodash.js library is included by default.

\"], \"racket\": [\"Racket\", \"

Run with Racket 8.3.

\"], \"erlang\": [\"Erlang\", \"Erlang/OTP 24.2\"], \"elixir\": [\"Elixir\", \"Elixir 1.13.0 with Erlang/OTP 24.2\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }