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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
validate-binary-search-tree | Simple JS DFS | simple-js-dfs-by-pranaykmr-xnln | \nvar isValidBST = function(root, min = -Infinity, max = Infinity) {\n if(root === null)\n return true;\n if(root.val <= min || root.val >= max)\n | pranaykmr | NORMAL | 2021-02-02T22:15:51.795195+00:00 | 2021-02-02T22:15:51.795241+00:00 | 3,490 | false | ```\nvar isValidBST = function(root, min = -Infinity, max = Infinity) {\n if(root === null)\n return true;\n if(root.val <= min || root.val >= max)\n return false;\n return isValidBST(root.right, root.val, max) && isValidBST(root.left, min, root.val)\n};\n``` | 24 | 0 | ['JavaScript'] | 2 |
validate-binary-search-tree | ✅ 🔥 0 ms Runtime Beats 100% User🔥|| Code Idea ✅ || Algorithm & Solving Step ✅ || | 0-ms-runtime-beats-100-user-code-idea-al-xhjk | \n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n BST property:\n\n1. The left subtree contains only nodes with keys less than the no | Letssoumen | NORMAL | 2024-12-02T00:34:01.100405+00:00 | 2024-12-02T00:34:01.100432+00:00 | 3,780 | false | \n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n **BST property**:\n\n1. The left subtree contains only nodes with keys **less than** the node\'s key.\n2. The right subtree contains only nodes with keys **greater than** the node\'s key.\n3. Both subtrees must also be valid BSTs.\n\n---\n\n### **Approach: Use Valid Range for Node Values** :\nWe validate the tree recursively by maintaining a range [min, max]for each node:\n- For the root, the range is (-\u221E, \u221E).\n- For the left child of a node with value `v`, the range becomes (-\u221E, v).\n- For the right child of a node with value `v`, the range becomes (v, \u221E).\n\nAt each node:\n- If the node\'s value is outside the valid range, the tree is not a BST.\n- Otherwise, recursively validate its left and right subtrees with updated ranges.\n\n---\n\n### **Algorithm Complexity** :\n- **Time Complexity**: O(n), where n is the number of nodes (each node is visited once).\n- **Space Complexity**: O(h), where his the height of the tree (due to recursion stack).\n\n---\n\n### **C++ Implementation** :\n```cpp\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n return validate(root, nullptr, nullptr);\n }\n\nprivate:\n bool validate(TreeNode* node, TreeNode* minNode, TreeNode* maxNode) {\n if (!node) return true;\n\n // Check current node\'s value against the valid range\n if ((minNode && node->val <= minNode->val) || \n (maxNode && node->val >= maxNode->val)) {\n return false;\n }\n\n // Recursively validate left and right subtrees\n return validate(node->left, minNode, node) && \n validate(node->right, node, maxNode);\n }\n};\n```\n\n---\n\n### **Python Implementation** :\n```python\nclass Solution:\n def isValidBST(self, root: TreeNode) -> bool:\n def validate(node, min_val, max_val):\n if not node:\n return True\n\n # Check current node\'s value against the valid range\n if (min_val is not None and node.val <= min_val) or \\\n (max_val is not None and node.val >= max_val):\n return False\n\n # Recursively validate left and right subtrees\n return validate(node.left, min_val, node.val) and \\\n validate(node.right, node.val, max_val)\n\n return validate(root, None, None)\n```\n\n---\n\n### **Java Implementation** :\n```java\npublic class Solution {\n public boolean isValidBST(TreeNode root) {\n return validate(root, null, null);\n }\n\n private boolean validate(TreeNode node, Integer minVal, Integer maxVal) {\n if (node == null) return true;\n\n // Check current node\'s value against the valid range\n if ((minVal != null && node.val <= minVal) || \n (maxVal != null && node.val >= maxVal)) {\n return false;\n }\n\n // Recursively validate left and right subtrees\n return validate(node.left, minVal, node.val) && \n validate(node.right, node.val, maxVal);\n }\n}\n```\n\n---\n\n### **Why This Approach Works** know this ?\n- By passing the valid range [min, max] to each subtree, we ensure that all nodes adhere to the BST property globally, not just locally.\n- The use of recursion ensures concise and readable code.\n\n---\n\n### **Alternative Approach: In-order Traversal** :\nThe in-order traversal of a valid BST results in a strictly increasing sequence. We can:\n1. Perform an in-order traversal.\n2. Check if the sequence is strictly increasing.\n\n\n | 23 | 1 | ['Tree', 'Depth-First Search', 'C++', 'Java', 'Python3'] | 0 |
validate-binary-search-tree | C++ Solution Using LONG_MAX and LONG_MIN | c-solution-using-long_max-and-long_min-b-2nca | \tclass Solution {\n\tpublic:\n\t\tbool isValidBSTHelper(TreeNode root, long min, long max) {\n\t\t\tif(root == NULL){\n\t\t\t\treturn true;\n\t\t\t} \n\t\t\t | pankajgupta20 | NORMAL | 2021-05-13T09:47:37.388499+00:00 | 2021-06-03T16:40:52.248230+00:00 | 2,693 | false | \tclass Solution {\n\tpublic:\n\t\tbool isValidBSTHelper(TreeNode* root, long min, long max) {\n\t\t\tif(root == NULL){\n\t\t\t\treturn true;\n\t\t\t} \n\t\t\tif(root->val > min && root->val < max) {\n\t\t\t\treturn isValidBSTHelper(root->left, min, root->val) && isValidBSTHelper(root->right, root->val, max);\n\t\t\t} \n\t\t\treturn false;\n\t\t}\n\t\tbool isValidBST(TreeNode* root) {\n\t\t\treturn isValidBSTHelper(root, LONG_MIN, LONG_MAX);\n\t\t} \n\t}; | 23 | 0 | ['Recursion', 'C', 'C++'] | 6 |
validate-binary-search-tree | Recursive approach✅ | O( n)✅ | (Step by step explanation)✅ | recursive-approach-o-n-step-by-step-expl-bo12 | Intuition\nThe problem requires checking whether a binary tree is a valid binary search tree (BST). A BST is a binary tree where for each node, the values of al | monster0Freason | NORMAL | 2023-11-14T04:47:30.733304+00:00 | 2023-11-14T04:47:30.733326+00:00 | 3,500 | false | # Intuition\nThe problem requires checking whether a binary tree is a valid binary search tree (BST). A BST is a binary tree where for each node, the values of all nodes in its left subtree are less than the node\'s value, and the values of all nodes in its right subtree are greater than the node\'s value.\n\n# Approach\nThe approach is based on a recursive algorithm. At each node, we check if its value lies within a certain range, which is determined by its position in the tree. The initial range for the root is (-\u221E, +\u221E). As we traverse the tree, the range narrows down for each node based on its value and position.\n\n1. **Initialization**: Start with the root of the binary tree and an initial range of (-\u221E, +\u221E).\n\n **Reason**: We begin the recursive check from the root with an unbounded range.\n\n2. **Range Check**: For each node, check if its value lies within the current range. If the value is not within the range, return false.\n\n **Reason**: A binary tree is a valid BST only if the values of its nodes satisfy the BST property.\n\n3. **Recursive Check**: Recursively check the left and right subtrees of the current node, updating the range accordingly.\n\n **Reason**: We need to check the left and right subtrees to ensure the entire tree satisfies the BST property.\n\n4. **Termination Condition**: If we reach a null node, return true, as a null node is a valid BST.\n\n **Reason**: The recursion should terminate when we reach the end of a branch.\n\n5. **Result**: The final result is the boolean value returned by the recursive function.\n\n **Reason**: The result indicates whether the entire binary tree is a valid BST.\n\n# Complexity\n- **Time complexity**: O(n)\n - We visit each node once during the recursive check.\n- **Space complexity**: O(h)\n - The maximum depth of the recursion stack is the height of the binary tree. In the worst case, the space complexity is proportional to the height of the tree.\n\n# Code\n\n\n<details open>\n <summary>Python Solution</summary>\n\n```python\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def bst(root, min_val=float(\'-inf\'), max_val=float(\'inf\')):\n if root == None:\n return True\n\n if not (min_val < root.val < max_val):\n return False\n\n return (bst(root.left, min_val, root.val) and\n bst(root.right, root.val, max_val))\n\n return bst(root)\n```\n</details>\n\n<details open>\n <summary>C++ Solution</summary>\n\n```cpp\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n return bst(root, LLONG_MIN, LLONG_MAX);\n }\n\n bool bst(TreeNode* root, long long min_val, long long max_val) {\n if (root == NULL) {\n return true;\n }\n\n if (!(min_val < root->val && root->val < max_val)) {\n return false;\n }\n\n return bst(root->left, min_val, root->val) && bst(root->right, root->val, max_val);\n }\n};\n```\n</details>\n\n# Please upvote the solution if you understood it.\n\n | 22 | 0 | ['Tree', 'Depth-First Search', 'Recursion', 'C++', 'Python3'] | 2 |
validate-binary-search-tree | Beats 100% | Only 3 LINES Code ->Diagram & Image Best Explaination🥇 | C++/Python/Java 🔥 | beats-100-only-3-lines-code-diagram-imag-gda5 | Diagram Data Flow\n Describe your first thoughts on how to solve this problem. \n\n\n# Approach\nBefore we start properties to verify BST are:\n- Top root node | 7mm | NORMAL | 2023-05-29T10:15:41.402002+00:00 | 2023-05-29T10:15:41.402033+00:00 | 6,483 | false | # Diagram Data Flow\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n**Before we start properties to verify BST are:**\n- Top root node should have range -infinity to +infinity\n- When we move to left of BST its value must be in -infinity and\nthe value of its parent root !\n- When move to right its value lies in more the parent root value and + infinity .\n- We just checked this condition recursively and DONE ! \n- Let -infinity and + infinity to given constaints in questions.\n- Done\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(H)\n# Code\n```\n\nclass Solution {\npublic:\n bool solve(TreeNode*root,long long int lb,long long int ub)\n {\n if(root==nullptr)return true;\n if((root->val<ub&&root->val>lb)&&(solve(root->left,lb,root->val))&&(solve(root->right,root->val,ub))) return true;\n else return false;\n }\n bool isValidBST(TreeNode* root) {\n long long int lb=-2147483649;\n long long int ub=2147483648;\n bool ans =solve(root,lb,ub);\n return ans;\n \n }\n};\n```\n\n\n | 22 | 0 | ['Tree', 'Binary Search Tree', 'Recursion', 'Binary Tree', 'C++'] | 3 |
validate-binary-search-tree | 🔥 Python || Easily Understood ✅ || Faster than 96% || Recursion | python-easily-understood-faster-than-96-nm9z9 | Method: recursion\n\ndef isValidBST(self, root: Optional[TreeNode]) -> bool:\n\tdef check_validate(root, lower, upper):\n\t\tif not root:\n\t\t\treturn True\n\t | wingskh | NORMAL | 2022-08-11T05:05:13.193881+00:00 | 2022-08-12T09:41:16.592513+00:00 | 2,786 | false | Method: `recursion`\n```\ndef isValidBST(self, root: Optional[TreeNode]) -> bool:\n\tdef check_validate(root, lower, upper):\n\t\tif not root:\n\t\t\treturn True\n\t\tif lower >= root.val or upper <= root.val:\n\t\t\treturn False\n\t\telse:\n\t\t\treturn check_validate(root.left, lower, root.val) and check_validate(\n\t\t\t\troot.right, root.val, upper\n\t\t\t)\n\n\treturn check_validate(root, -math.inf, math.inf)\n```\n\n**Time Complexity**: `O(n)`\n**Space Complexity**: `O(n)`\n<br/>\nUsing `in-order`, much more easy-understanding\n```\nlast = -math.inf\nended = False\ndef isValidBST(self, root: Optional[TreeNode]) -> bool:\n\tdef check_validate(cur):\n\t\tif self.ended:\n\t\t\treturn \n\t\tif cur.left:\n\t\t\tcheck_validate(cur.left)\n\n\t\tif not(cur.val > self.last):\n\t\t\tself.ended = True\n\t\t\treturn\n\n\t\tself.last = cur.val\n\t\tif cur.right:\n\t\t\tcheck_validate(cur.right)\n\tcheck_validate(root)\n\treturn not self.ended\n```\n\n**Time Complexity**: `O(n)`\n**Space Complexity**: `O(n)`\n<br/>\n | 22 | 0 | ['Recursion', 'Python'] | 2 |
validate-binary-search-tree | C++ | DFS Recursion | Time: O (n), Space: O (n) | c-dfs-recursion-time-o-n-space-o-n-by-hi-zc1z | DFS Recusive Approach\nThe reason why we update min and max at every step is because:\n1. For every left node, the max value it can have it less than its parent | hiitsme | NORMAL | 2020-12-13T05:16:15.456740+00:00 | 2022-02-22T02:45:34.537603+00:00 | 3,802 | false | **DFS Recusive Approach**\nThe reason why we update min and max at every step is because:\n1. For every left node, the max value it can have it less than its parent\'s and the min value it can have is the left most node for that particular subtree.\n2. For every right node, the max value it can have it less than the right most node of that particular subtree and the min value it can have is the root value.\n\nTime Complexity: O (n)\nSpace Complexity: O (n) (For the recursion Stack)\n```\nclass Solution {\npublic:\n bool isValidBSTHelper (TreeNode* currentNode, TreeNode* min, TreeNode* max) {\n if (currentNode==NULL) return true; \n if (min && currentNode->val <= min->val) return false;\n if (max && currentNode->val >= max->val) return false;\n\n return isValidBSTHelper (currentNode->left, min, currentNode) && isValidBSTHelper (currentNode->right, currentNode, max);\n }\n \n bool isValidBST(TreeNode* root) {\n return isValidBSTHelper (root, NULL, NULL);\n }\n};\n```\nThis is a [nice intuitive solution](https://leetcode.com/problems/validate-binary-search-tree/discuss/990894/C%2B%2B-faster-than-90.55-of-C%2B%2B-and-less-than-87.48-of-C%2B%2B)\n\n**Iterative Inorder Stack Solution**\nTime Complexity: O(N)\nSpace Complexity: O(N)\n```\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n stack <TreeNode*> s; \n TreeNode* pre=NULL;\n \n while (root || !s.empty()) {\n while (root) {\n s.push(root);\n root=root->left;\n }\n root=s.top(), s.pop();\n \n if (pre!=NULL && root->val<=pre->val) return false;\n pre=root;\n root=root->right;\n }\n return true;\n }\n};\n```\nVery nice article https://leetcode.com/problems/validate-binary-search-tree/discuss/32112/Learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-(Java-Solution)\n | 22 | 0 | ['Stack', 'Recursion', 'C', 'Iterator'] | 3 |
validate-binary-search-tree | Easy to understand 2 lines solution! O(n) with Examples and Explanation - JavaScript | easy-to-understand-2-lines-solution-on-w-4m7e | Short and sweet:\n\nts\nfunction isValidBST(root: TreeNode|null, min = -Infinity, max = Infinity): boolean {\n if(!root) return true;\n return !(root.val <= m | adriansky | NORMAL | 2020-08-10T13:23:11.952883+00:00 | 2020-08-10T13:23:33.839826+00:00 | 2,351 | false | Short and sweet:\n\n```ts\nfunction isValidBST(root: TreeNode|null, min = -Infinity, max = Infinity): boolean {\n if(!root) return true;\n return !(root.val <= min || root.val >= max) && isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);\n};\n```\n\nHow it works?\n- If the root is `null`, then is a valid BST.\n- If the root is NOT null, then we check for the following:\n - check if the current node\'s value is within boundaries (min/max). The intial boundaries are -/+ Infinity so any value would be valid.\n - However, for the children we start restricting the boundaries. If we go to the left subtree, then we set the current node as the `max` boundary. Similarly, if we go the right subtree, then we set the current node\'s value as the `min`.\n\nLet\'s do some examples:\n\n**Example 1**:\n\n`[20,10,30,null,18,null,null,9,19]`\n\n\n\nThe recursion call will be the following:\n\n- isValidBST(root: 20, min = -Infinity, max = Infinity)\n\t- isValidBST(root: 10, min = -Infinity, max = 20)\n\t\t- isValidBST(root: 18, min = 10, max = 20)\n\t\t\t- isValidBST(root: 9, min = 10, max = 18): `false`, though `9 < 18 < 19`, 9 is lower than the `min=10`, so it will return false.\n\n\n**Example 2**:\n\n`[20,10,30,null,18,null,null,17,19]`\n\n\n\nThe recursion call will be the following:\n- isValidBST(root: 20, min: -Infinity, max: Infinity): `true`\n\t- isValidBST(root: 10, min = -Infinity, max = 20): `true`\n\t\t- isValidBST(root: 18, min = 10, max = 20): `true`\n\t\t\t- isValidBST(root: 17, min = 10, max = 18): `true`\n\t\t\t- isValidBST(root: 19, min = 18, max = 20): `true`\n\t- isValidBST(root: 30, min = 20, max = Infinity): `true`\n\nEach one returns true so it\'s a valid BST.\n\n | 22 | 0 | ['TypeScript', 'JavaScript'] | 4 |
validate-binary-search-tree | Accepted Java solution | accepted-java-solution-by-vy7sun-hjy8 | import java.util.Stack;\n\npublic class Solution {\n\nStack stack = new Stack();\n\npublic void inOrder(TreeNode root){\n\n if(root != null){\n inOrde | vy7sun | NORMAL | 2015-03-12T06:07:41+00:00 | 2015-03-12T06:07:41+00:00 | 6,762 | false | import java.util.Stack;\n\npublic class Solution {\n\nStack<Integer> stack = new Stack<Integer>();\n\npublic void inOrder(TreeNode root){\n\n if(root != null){\n inOrder(root.left);\n stack.push(root.val);\n inOrder(root.right);\n }\n}\npublic boolean isValidBST(TreeNode root){\n\n if(root == null){\n return true;\n }\n\n inOrder(root);\n int i = stack.pop();\n\n while(!stack.isEmpty()){\n int j = stack.pop();\n if(i <= j){\n return false;\n }\n i = j;\n }\n\n return true;\n}\n} | 22 | 2 | [] | 7 |
validate-binary-search-tree | 1ms Java solution, O(n) time and O(1) space, using Integer object and null pointer | 1ms-java-solution-on-time-and-o1-space-u-m34c | public class Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBSTHelper(root, null, null);\n }\n \n pr | yanggao | NORMAL | 2015-11-11T18:11:43+00:00 | 2015-11-11T18:11:43+00:00 | 5,306 | false | public class Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBSTHelper(root, null, null);\n }\n \n private boolean isValidBSTHelper(TreeNode root, Integer leftBound, Integer rightBound) {\n // recursively pass left and right bounds from higher level to lower level\n if (root == null) {\n return true;\n }\n if (leftBound != null && root.val <= leftBound || rightBound != null && root.val >= rightBound) {\n return false;\n }\n return isValidBSTHelper(root.left, leftBound, root.val) && isValidBSTHelper(root.right, root.val, rightBound);\n }\n } | 21 | 3 | [] | 5 |
validate-binary-search-tree | Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 || DFS | easy-0-ms-100-fully-explained-java-c-pyt-2mcy | Java Solution:\n\n// Runtime: 0 ms, faster than 100.00% of Java online submissions for Validate Binary Search Tree.\nclass Solution {\n public boolean isVali | PratikSen07 | NORMAL | 2022-08-30T10:35:48.562898+00:00 | 2022-08-30T10:43:45.999392+00:00 | 4,926 | false | # **Java Solution:**\n```\n// Runtime: 0 ms, faster than 100.00% of Java online submissions for Validate Binary Search Tree.\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBST(root, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); \n } \n public boolean isValidBST(TreeNode root, double minimum, double maximum){\n // Base case: root is null...\n if(root == null) return true;\n // If the value of root is less or equal to minimum...\n // Or If the value of root is greater or equal to maximum...\n if(root.val <= minimum || root.val >= maximum) return false;\n // Recursively call the function for the left and right subtree...\n return isValidBST(root.left, minimum, root.val) && isValidBST(root.right, root.val, maximum);\n }\n}\n```\n\n# **C++ Solution:**\n```\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n // Base case...\n if(root == NULL) return true;\n return check(root, LONG_MIN, LONG_MAX);\n }\n bool check(TreeNode* root, long minimum, long maximum){\n // If root is NULl...\n if(root == NULL) return true;\n // If the value of root is less or equal to minimum \n // Or If the value of root is greater or equal to maximum\n if(root->val <= minimum || root->val >= maximum) return false;\n // Recursively call the function for the left and right subtree...\n return check(root->left, minimum, root->val) && check(root->right, root->val, maximum);\n }\n};\n```\n\n# **Python/Python3 Solution:**\n```\nclass Solution(object):\n def isValidBST(self, root, maximum = float(\'-inf\'), minimum = float(\'inf\')):\n # Base case: root is null...\n if not root: return True\n # If the value of root is less thsn minimum Or greater than maximum...\n if not maximum < root.val < minimum: return False\n # Recursively call the function for the left and right subtree...\n return self.isValidBST(root.left, maximum, root.val) and self.isValidBST(root.right, root.val, minimum)\n```\n \n# **JavaScript Solution:**\n```\nvar isValidBST = function(root, minimum, maximum) {\n // Base case: root is null...\n if(root == null) return true;\n // If the value of root is less or equal to minimum...\n // Or If the value of root is greater or equal to maximum...\n if(root.val <= minimum || root.val >= maximum) return false;\n // Recursively call the function for the left and right subtree...\n return isValidBST(root.left, minimum, root.val) && isValidBST(root.right, root.val, maximum);\n};\n```\n\n# **C Language:**\n```\nbool check(struct TreeNode* root, long minimum, long maximum){\n // If root is NULl...\n if(root == NULL) return true;\n // If the value of root is less or equal to minimum \n // Or If the value of root is greater or equal to maximum\n if(root->val <= minimum || root->val >= maximum) return false;\n // Recursively call the function for the left and right subtree...\n return check(root->left, minimum, root->val) && check(root->right, root->val, maximum);\n}\nbool isValidBST(struct TreeNode* root){\n // Base case...\n if(root == NULL) return true;\n return check(root, LONG_MIN, LONG_MAX);\n}\n```\n\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 20 | 0 | ['Tree', 'Depth-First Search', 'C', 'Python', 'Java', 'Python3', 'JavaScript'] | 5 |
validate-binary-search-tree | ✅Java|| 0ms 100% Faster||Beginner Friendly | java-0ms-100-fasterbeginner-friendly-by-oa5xu | If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries | ganajayant | NORMAL | 2022-08-11T01:50:19.558914+00:00 | 2022-08-12T10:44:52.800799+00:00 | 1,456 | false | **If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.**\n\n```\npublic boolean isValidBST(TreeNode root) {\n return isValid(root, Long.MIN_VALUE, Long.MAX_VALUE);\n }\n\n private boolean isValid(TreeNode node, long l, long h) {\n if (node == null) { // Base Case\n return true;\n }\n\t\t// intially head can be anything between -inf to +inf\n\t\t//after head left node should be l to previous head node value and right node should be head node value to h\n return node.val > l && node.val < h && isValid(node.left, l, node.val) && isValid(node.right, node.val, h);\n }\n``` | 20 | 4 | ['Binary Search Tree', 'Recursion', 'Java'] | 1 |
validate-binary-search-tree | JAVA || Easy Solution || 100% faster Code | java-easy-solution-100-faster-code-by-sh-bbt6 | \tPLEASE UPVOTE IF YOU LIKE\n\nclass Solution {\n private boolean flag=true;\n TreeNode prev=null;\n public boolean isValidBST(TreeNode root) {\n | shivrastogi | NORMAL | 2022-08-11T02:59:05.277441+00:00 | 2022-08-11T02:59:05.277491+00:00 | 3,007 | false | \tPLEASE UPVOTE IF YOU LIKE\n```\nclass Solution {\n private boolean flag=true;\n TreeNode prev=null;\n public boolean isValidBST(TreeNode root) {\n inorder(root);\n return flag;\n }\n public void inorder(TreeNode root){\n if(root==null) return;\n \n inorder(root.left);\n \n if(prev!=null && root.val<=prev.val){\n flag=false;\n return;\n }\n prev=root;\n \n inorder(root.right);\n }\n}\n``` | 19 | 2 | ['Java'] | 4 |
validate-binary-search-tree | Python easy to understand iterative and recursive solutions | python-easy-to-understand-iterative-and-y8jkc | \nclass Solution(object):\n def isValidBST(self, root):\n return self.valid(root, -sys.maxsize, sys.maxsize)\n \n def valid(self, root, l, r):\n | oldcodingfarmer | NORMAL | 2015-08-14T15:51:08+00:00 | 2020-09-24T13:33:05.414583+00:00 | 7,203 | false | ```\nclass Solution(object):\n def isValidBST(self, root):\n return self.valid(root, -sys.maxsize, sys.maxsize)\n \n def valid(self, root, l, r):\n if not root:\n return True\n if not (l < root.val < r):\n return False\n return self.valid(root.left, l, root.val) and self.valid(root.right, root.val, r)\n \n def isValidBST3(self, root):\n pre, stack = None, []\n while True:\n while root:\n stack.append(root)\n root = root.left\n if not stack:\n return True\n node = stack.pop()\n if pre and pre.val >= node.val:\n return False\n pre = node\n root = node.right\n \n def isValidBST2(self, root):\n ret, stack = [], []\n while True:\n while root:\n stack.append(root)\n root = root.left\n if not stack:\n break\n node = stack.pop()\n ret.append(node.val)\n root = node.right\n for i in range(len(ret)-1):\n if ret[i] >= ret[i+1]:\n return False\n return True\n \n def isValidBST1(self, root):\n ret = []\n self.dfs(root, ret)\n for i in range(len(ret)-1):\n if ret[i] >= ret[i+1]:\n return False\n return True\n \n def dfs(self, root, ret):\n if root:\n self.dfs(root.left, ret)\n ret.append(root.val)\n self.dfs(root.right, ret)\n``` | 19 | 1 | ['Recursion', 'Iterator', 'Python'] | 6 |
validate-binary-search-tree | Python || InOrder Traversal || Easy To Understand 🔥 | python-inorder-traversal-easy-to-underst-21fu | Code\n\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n arr = []\n def inorder(root):\n if root is None: | karanjadaun22 | NORMAL | 2023-02-21T08:38:19.945290+00:00 | 2023-02-21T08:38:19.945322+00:00 | 6,508 | false | # Code\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n arr = []\n def inorder(root):\n if root is None: return None\n inorder(root.left)\n arr.append(root.val)\n inorder(root.right)\n inorder(root)\n return True if arr == list(sorted(set(arr))) else False\n``` | 18 | 0 | ['Python3'] | 5 |
validate-binary-search-tree | ✔️ Simple Python Solution to Validate Binary Search Tree using Recursion 🔥 | simple-python-solution-to-validate-binar-mhdl | IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D\n\n\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n \n de | pniraj657 | NORMAL | 2022-10-15T04:51:05.006743+00:00 | 2022-11-02T03:29:28.353316+00:00 | 6,058 | false | **IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n \n def valid(node, left, right):\n if not node:\n return True\n if not (node.val<right and node.val>left):\n return False\n \n return (valid(node.left, left, node.val) and \n valid(node.right, node.val, right))\n \n return valid(root, float(-inf), float(inf))\n```\n**Visit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: https://www.python-techs.com/** | 17 | 1 | ['Binary Search Tree', 'Recursion', 'Python', 'Python3'] | 3 |
validate-binary-search-tree | Go: 4ms | go-4ms-by-ayenter-fv98 | \nfunc isValidBST(root *TreeNode) bool {\n return RecValidate(root, nil, nil)\n}\n\nfunc RecValidate(n, min, max *TreeNode) bool {\n if n == nil {\n | ayenter | NORMAL | 2020-02-15T19:06:46.914338+00:00 | 2020-02-15T19:06:46.914372+00:00 | 1,641 | false | ```\nfunc isValidBST(root *TreeNode) bool {\n return RecValidate(root, nil, nil)\n}\n\nfunc RecValidate(n, min, max *TreeNode) bool {\n if n == nil {\n return true\n }\n if min != nil && n.Val <= min.Val {\n return false\n }\n if max != nil && n.Val >= max.Val {\n return false\n }\n return RecValidate(n.Left, min, n) && RecValidate(n.Right, n, max)\n}\n``` | 16 | 0 | ['Go'] | 2 |
validate-binary-search-tree | Simple DFS solution | C# | simple-dfs-solution-c-by-baymax-7yxy | Intuition & Approach\n Describe your first thoughts on how to solve this problem. \nSince all the nodes in the left-sub-tree should be less than the current nod | Baymax_ | NORMAL | 2023-05-05T04:37:19.526216+00:00 | 2023-05-05T04:37:31.169719+00:00 | 1,604 | false | # Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince all the nodes in the left-sub-tree should be less than the current node, and all the nodes in the right-sub-tree should be greater than the current node, we can iterate down to check if each node satisfies the condition, that is it should be in a range (min, max) where max for nodes in left-sub-tree and min for right-sub-tree is the parent node vlaue.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) - as we need to visit all nodes once\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) - as we do not use any extra space\n**But**, if we consider the space occupied in the memory by the stacking-recursive function call (function-call stack), we can it is O(n)\n\n## Please upvote if you like the approach\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public int val;\n * public TreeNode left;\n * public TreeNode right;\n * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\npublic class Solution {\n public bool IsValidBST(TreeNode root) {\n return Evaluate(root, long.MinValue, long.MaxValue);\n }\n\n private bool Evaluate(TreeNode node, long min, long max)\n {\n if (node == null)\n {\n return true;\n }\n\n return (\n node.val > min &&\n node.val < max &&\n Evaluate(node.left, min, node.val) &&\n Evaluate(node.right, node.val, max)\n );\n }\n}\n```\n\n## Please upvote if you like the approach | 15 | 0 | ['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'C#'] | 2 |
validate-binary-search-tree | 4 line C++ simple solution, easy understanding | 4-line-c-simple-solution-easy-understand-dlif | bool isValidBST(TreeNode* root) {\n return dfs_valid(root, LONG_MIN, LONG_MAX);\n }\n bool dfs_valid(TreeNode *root, long low, long high) {\n | lchen77 | NORMAL | 2015-12-14T00:54:02+00:00 | 2015-12-14T00:54:02+00:00 | 4,167 | false | bool isValidBST(TreeNode* root) {\n return dfs_valid(root, LONG_MIN, LONG_MAX);\n }\n bool dfs_valid(TreeNode *root, long low, long high) {\n if (!root) return true;\n return low < root->val && root->val < high && dfs_valid(root->left, low, root->val)\n && dfs_valid(root->right, root->val, high);\n } | 15 | 1 | ['C++'] | 3 |
validate-binary-search-tree | Superb Lgic BST | superb-lgic-bst-by-ganjinaveen-phrz | \nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def BST(root,mx,mi):\n if not root:\n return T | GANJINAVEEN | NORMAL | 2023-07-15T23:57:25.425820+00:00 | 2023-07-15T23:57:25.425844+00:00 | 2,258 | false | ```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def BST(root,mx,mi):\n if not root:\n return True\n elif root.val>=mx or root.val<=mi:\n return False\n else:\n return BST(root.left,root.val,mi) and BST(root.right,mx,root.val)\n return BST(root,float(\'inf\'),float(\'-inf\'))\n```\n# please upvote me it would encourage me alot\n | 14 | 0 | ['Binary Search Tree', 'Python', 'Python3'] | 1 |
validate-binary-search-tree | Java recursive solution 0ms, without using Long.MAX_VALUE and Long.MIN_VALUE | java-recursive-solution-0ms-without-usin-tjqt | Approach\nFor this problem, we need to choose one biggest value > Integer.MAX_VALUE\nand one smallest value < Integer.MIN_VALUE as the maximum and minimum, resp | xian-wen | NORMAL | 2023-03-02T09:44:08.443696+00:00 | 2023-04-05T12:38:38.033051+00:00 | 3,186 | false | # Approach\nFor this problem, we need to choose one biggest value > `Integer.MAX_VALUE`\nand one smallest value < `Integer.MIN_VALUE` as the maximum and minimum, respectively. They could not be equal, otherwise cases like\n```\nroot = [2147483647]\nroot = [2147483647, 2147483647]\n```\nwill be failed.\n\n`Long.MAX_VALUE` and `Long.MIN_VALUE` are luckily the two that meet our needs. However, if unluckily in the future the LeetCode admin adds them into the test cases, cases like\n```\nroot = [9223372036854775807]\nroot = [9223372036854775807, 9223372036854775807]\n```\nwill be failed again.\n\nTherefore, it is better to avoid using them. We can simply replace the `int` or `long` with `TreeNode`, and set them to `null` when calling the helper function, as shown in the code below.\n\n# Reference\nhttps://algs4.cs.princeton.edu/32bst/BST.java.html\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBST(root, null, null);\n }\n\n private boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {\n if (root == null) {\n return true;\n }\n\n if (min != null && root.val <= min.val) {\n return false;\n }\n\n if (max != null && root.val >= max.val) {\n return false;\n }\n return isValidBST(root.left, min, root) \n && isValidBST(root.right, root, max);\n }\n}\n``` | 13 | 0 | ['Java'] | 3 |
validate-binary-search-tree | C++ / Python simple O(n) solution | c-python-simple-on-solution-by-tovam-jk2p | C++ :\n\n\nclass Solution {\npublic:\n void inorder(TreeNode* root)\n {\n if(!root)\n return;\n \n inorder(root -> left);\ | TovAm | NORMAL | 2021-10-07T12:28:59.063568+00:00 | 2021-10-07T12:28:59.063600+00:00 | 1,907 | false | **C++ :**\n\n```\nclass Solution {\npublic:\n void inorder(TreeNode* root)\n {\n if(!root)\n return;\n \n inorder(root -> left);\n bTree.push_back(root -> val);\n inorder(root -> right);\n }\n\n bool isValidBST(TreeNode* root) {\n // An empty tree\n if(!root)\n return true;\n \n // A leaf\n if(!root -> right && !root -> left)\n return true;\n \n // Inorder traversal to get the tree\'s values sorted\n inorder(root);\n \n for(int i = 0; i < bTree.size() - 1; ++i)\n if(bTree[i] >= bTree[i + 1])\n return false;\n return true;\n \n }\n \n private:\n vector<int> bTree;\n};\n```\n\n**Python :**\n\n```\nclass Solution:\n def __init__(self):\n self.tree = []\n \n def inorder(self, root: Optional[TreeNode]) -> None:\n if not root:\n return\n \n self.inorder(root.left);\n self.tree.append(root.val);\n self.inorder(root.right);\n \n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return True\n \n if not root.right and not root.left:\n return True\n \n self.inorder(root)\n \n for i in range(len(self.tree) - 1):\n if self.tree[i] >= self.tree[i + 1]:\n return False\n return True;\n```\n\n**Like it ? please upvote !** | 13 | 0 | ['C', 'Python', 'Python3'] | 2 |
validate-binary-search-tree | Test cases missing | test-cases-missing-by-loick-9zt1 | There should be a test case where some nodes have values equal to Integer.MIN_VALUE and Integer.MAX_VALUE;\n\nThis solution is accepted and shouldn't be:\n\n | loick | NORMAL | 2013-12-05T09:36:57+00:00 | 2013-12-05T09:36:57+00:00 | 3,607 | false | There should be a test case where some nodes have values equal to Integer.MIN_VALUE and Integer.MAX_VALUE;\n\nThis solution is accepted and shouldn't be:\n\n public boolean isValidBST(TreeNode root) {\n if (root == null) return true;\n return isValidBST(root.left,Integer.MIN_VALUE, root.val) \n && isValidBST(root.right,root.val,Integer.MAX_VALUE);\n }\n\n public boolean isValidBST(TreeNode root, int smallest, int largest) {\n if (root == null) return true;\n if (root.val > smallest && root.val < largest)\n return isValidBST(root.left,smallest, root.val) \n && isValidBST(root.right,root.val,largest);\n else\n return false;\n } | 13 | 1 | [] | 6 |
validate-binary-search-tree | 1 ms Java Solution | 1-ms-java-solution-by-harish20-nudr | public class Solution {\n private TreeNode prev = null;\n \n public boolean isValidBST(TreeNode root) {\n if(root == null){\n | harish20 | NORMAL | 2016-04-26T06:49:13+00:00 | 2016-04-26T06:49:13+00:00 | 1,333 | false | public class Solution {\n private TreeNode prev = null;\n \n public boolean isValidBST(TreeNode root) {\n if(root == null){\n return true;\n }\n if(!isValidBST(root.left)) return false;\n if(prev != null && root.val <= prev.val) return false;\n prev = root;\n return isValidBST(root.right);\n }\n } | 13 | 1 | [] | 1 |
validate-binary-search-tree | Three solutions in C++ | three-solutions-in-c-by-zefengsong-6wiq | Solution 1. \n\nBF, O(n^2).\n\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n if(!root) return true;\n if(!isValid(root->left, | zefengsong | NORMAL | 2017-08-19T11:22:29.554000+00:00 | 2017-08-19T11:22:29.554000+00:00 | 3,098 | false | **Solution 1.** \n\nBF, O(n^2).\n```\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n if(!root) return true;\n if(!isValid(root->left, root->val, true) || !isValid(root->right, root->val, false)) return false;\n return isValidBST(root->left) && isValidBST(root->right);\n }\n \n bool isValid(TreeNode* root, int bound, bool isLeft){\n return !root || (isLeft ? root->val < bound : root->val > bound ) && isValid(root->left, bound, isLeft) && isValid(root->right, bound, isLeft);\n }\n};\n```\n***\n**Solution 2.** \n\nIn-order, recursive, O(n), refered from [here](https://discuss.leetcode.com/topic/4659/c-in-order-traversal-and-please-do-not-rely-on-buggy-int_max-int_min-solutions-any-more).\n```\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n TreeNode* pre = NULL;\n return isValid(root, pre);\n }\n \n bool isValid(TreeNode* root, TreeNode* &pre){\n if(!root) return true;\n if(!isValid(root->left, pre)) return false;\n if(pre && root->val <= pre->val) return false;\n pre = root;\n return isValid(root->right, pre);\n }\n};\n```\n***\n**Solution 3.** \n\nIn-order, iterative, O(n), refered from [here](https://discuss.leetcode.com/topic/46016/learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-java-solution).\n```\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n stack<TreeNode*>s;\n TreeNode* pre = NULL;\n while(root || !s.empty()){\n while(root){\n s.push(root);\n root = root->left;\n }\n root = s.top();\n s.pop();\n if(pre && root->val <= pre->val) return false;\n pre = root;\n root = root->right;\n }\n return true;\n }\n};\n``` | 13 | 0 | ['C++'] | 3 |
validate-binary-search-tree | 4 BEST C++ solutions || Recursive, iterative and inorder approach || Beats 100% !! | 4-best-c-solutions-recursive-iterative-a-0997 | Code\n\n// Recursive solution - Using LONG_MIN anmd LONG_MAX\nclass Solution {\npublic: \n bool solve(TreeNode* root, long min, long max){\n if(root = | prathams29 | NORMAL | 2023-08-28T16:53:49.672894+00:00 | 2023-08-28T16:53:49.672930+00:00 | 1,371 | false | # Code\n```\n// Recursive solution - Using LONG_MIN anmd LONG_MAX\nclass Solution {\npublic: \n bool solve(TreeNode* root, long min, long max){\n if(root == NULL) \n return true;\n \n if(root->val <= min || root->val >= max) \n return false;\n \n return solve(root->left, min, root->val) && solve(root->right, root->val, max);\n }\n\n bool isValidBST(TreeNode* root) {\n return solve(root, LONG_MIN, LONG_MAX);\n }\n};\n\n// Recursion solution - Using nodes\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n return solve(root, NULL, NULL);\n }\n \n bool solve(TreeNode* root, TreeNode* max, TreeNode* min){\n if(root==NULL){\n return true;\n }\n\t\t\n if((min==NULL || root->val > min->val) && (max==NULL || root->val < max->val)){\n return solve(root->left, root, min) && solve(root->right, max, root);\n }\n return false;\n }\n};\n\n\n// Iterative solution\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n if(root == NULL)\n return true;\n \n stack<TreeNode*> s;\n TreeNode *pre = NULL;\n\n while(root != NULL || !s.empty()){\n while(root != NULL){\n s.push(root);\n root = root->left;\n }\n root = s.top();\n s.pop();\n if(pre != NULL && root->val <= pre->val){\n return false;\n }\n pre = root;\n root = root->right;\n }\n return true;\n }\n};\n\n// Check if inorder is sorted\nclass Solution {\npublic:\n void inorder(TreeNode *root, vector<int> &ans){\n if(root == NULL)\n return;\n \n inorder(root->left, ans);\n ans.push_back(root->val);\n inorder(root->right, ans);\n }\n\n bool isValidBST(TreeNode* root) {\n vector<int> ans;\n inorder(root, ans);\n\n for(int i=1; i<ans.size(); i++){\n if(ans[i] <= ans[i-1])\n return false;\n }\n return true;\n }\n};\n``` | 12 | 0 | ['Tree', 'Depth-First Search', 'Binary Search Tree', 'Binary Tree', 'C++'] | 1 |
validate-binary-search-tree | ✅Intuitive C++ Solution | Inorder Traversal | intuitive-c-solution-inorder-traversal-b-csv7 | Let\'s connect on Linkedin https://www.linkedin.com/in/arthur-asanaliev/\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- | Arthis_ | NORMAL | 2023-04-07T13:08:38.853462+00:00 | 2023-04-10T16:45:22.674218+00:00 | 4,788 | false | ##### Let\'s connect on Linkedin https://www.linkedin.com/in/arthur-asanaliev/\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> nodes;\n void inorder(TreeNode* root) {\n if (root->left) inorder(root->left);\n nodes.push_back(root->val);\n if (root->right) inorder(root->right);\n }\n bool isValidBST(TreeNode* root) {\n inorder(root);\n for (int i = 0; i < nodes.size() - 1; i++) {\n if (nodes[i] >= nodes[i+1]) return false;\n }\n return true;\n }\n};\n``` | 12 | 0 | ['Binary Search Tree', 'C++'] | 1 |
validate-binary-search-tree | Easy C++ solution | DFS | Recursion | easy-c-solution-dfs-recursion-by-coding_-fgla | Solution via in-order traversal [we need to check whether that returned elements are in ascending order]\n\n\nclass Solution {\npublic:\n long int num = LONG | coding_menance | NORMAL | 2022-10-23T15:48:12.373311+00:00 | 2022-11-01T05:31:26.731665+00:00 | 3,111 | false | # Solution via in-order traversal [we need to check whether that returned elements are in ascending order]\n\n```\nclass Solution {\npublic:\n long int num = LONG_MIN;\n\n bool isValidBST(TreeNode* root) {\n if (!root) return true;\n \n bool ans = isValidBST(root->left);\n \n if (root->val > num) {\n num = root->val;\n } else return false;\n\n return ans && isValidBST(root->right);\n }\n};\n```\n\n# Solution via recursion\n```\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root, long int min = LONG_MIN, long int max = LONG_MAX) {\n if (!root) return true;\n\n if (root->val > min && root->val < max) {\n return true && isValidBST(root->left, min, root->val) && isValidBST(root->right, root->val, max);\n }\n\n return false;\n }\n};\n```\n\n\n*If the above approaches helped you, then please upvote the solution!*\n\n## My GitHub: https://github.com/crimsonKn1ght | 12 | 0 | ['Tree', 'Depth-First Search', 'C++'] | 2 |
validate-binary-search-tree | ✔️ 100% Fastest Swift Solution, time: O(n), space: O(n). | 100-fastest-swift-solution-time-on-space-28pu | \n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right | sergeyleschev | NORMAL | 2022-04-08T13:37:06.811342+00:00 | 2022-04-08T13:37:06.811383+00:00 | 981 | false | ```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * public var val: Int\n * public var left: TreeNode?\n * public var right: TreeNode?\n * public init() { self.val = 0; self.left = nil; self.right = nil; }\n * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }\n * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {\n * self.val = val\n * self.left = left\n * self.right = right\n * }\n * }\n */\n \nclass Solution {\n // - Complexity:\n // - time: O(n), where n is the number of nodes in the tree.\n // - space: O(n), where n is the number of nodes in the tree.\n\n private var prev: Int?\n \n func isValidBST(_ root: TreeNode?) -> Bool {\n inorder(root)\n }\n \n private func inorder(_ root: TreeNode?) -> Bool {\n guard let root = root else { return true }\n \n guard inorder(root.left) else { return false }\n \n if let prev = prev, root.val <= prev { return false }\n \n prev = root.val\n return inorder(root.right)\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 12 | 0 | ['Swift'] | 2 |
validate-binary-search-tree | Validate Binary Search Tree 4 line compressed code | validate-binary-search-tree-4-line-compr-7opd | \npublic boolean isValidBST(TreeNode root) {\n return isValid(root,Long.MIN_VALUE,Long.MAX_VALUE); \n }\n public boolean isValid(TreeNode roo | ritik26 | NORMAL | 2020-12-16T12:09:38.731827+00:00 | 2020-12-16T12:09:38.731853+00:00 | 705 | false | ```\npublic boolean isValidBST(TreeNode root) {\n return isValid(root,Long.MIN_VALUE,Long.MAX_VALUE); \n }\n public boolean isValid(TreeNode root,long least,long max){\n if(root==null) return true;\n if(root.left!=null&&(root.left.val>=root.val||root.left.val<=least)) return false;\n if(root.right!=null&&(root.right.val<=root.val||root.right.val>=max)) return false;\n return isValid(root.left,least,root.val)&&isValid(root.right,root.val,max);\n }\n```\nfor video explanation leet code soln\nhttps://leetcode.com/problems/validate-binary-search-tree/solution/\n\n**If you like it please upvote ,it inspires me ** | 12 | 4 | ['Depth-First Search', 'Java'] | 3 |
validate-binary-search-tree | DFS solution easy to understand💪🏻 | dfs-solution-easy-to-understand-by-just_-mgfp | \n def isValidBST(self, root: TreeNode) -> bool:\n self.answer = True\n \n def dfs(root, left, right):\n if root:\n | just_4ina | NORMAL | 2020-09-15T11:43:53.516684+00:00 | 2020-09-15T11:43:53.516747+00:00 | 1,853 | false | ```\n def isValidBST(self, root: TreeNode) -> bool:\n self.answer = True\n \n def dfs(root, left, right):\n if root:\n if left >= root.val or root.val >= right:\n self.answer = False\n return\n dfs(root.left, left, root.val)\n dfs(root.right, root.val, right)\n dfs(root, float("-inf"), float(\'inf\'))\n return self.answer\n``` | 12 | 0 | ['Depth-First Search', 'Recursion', 'Python', 'Python3'] | 4 |
validate-binary-search-tree | Python - Simple Solution | python-simple-solution-by-nuclearoreo-e22u | \nclass Solution:\n def isValidBST(self, root: TreeNode) -> bool:\n return self.helper(root, float(\'-inf\'), float(\'inf\'))\n \n def helper(se | nuclearoreo | NORMAL | 2019-08-03T21:57:45.099029+00:00 | 2019-08-03T21:57:45.099068+00:00 | 1,940 | false | ```\nclass Solution:\n def isValidBST(self, root: TreeNode) -> bool:\n return self.helper(root, float(\'-inf\'), float(\'inf\'))\n \n def helper(self, node, minVal, maxVal):\n if node == None:\n return True\n \n if node.val <= minVal or node.val >= maxVal:\n return False\n \n left = self.helper(node.left, minVal, node.val)\n right = self.helper(node.right, node.val, maxVal)\n \n return left and right \n``` | 12 | 1 | ['Python', 'Python3'] | 0 |
validate-binary-search-tree | C# DFS | c-dfs-by-bacon-zcih | \npublic class Solution {\n public bool IsValidBST(TreeNode root) {\n return DFS(root, long.MinValue, long.MaxValue);\n }\n\n private bool DFS(T | bacon | NORMAL | 2019-05-04T03:35:27.768279+00:00 | 2019-05-04T03:35:27.768324+00:00 | 2,267 | false | ```\npublic class Solution {\n public bool IsValidBST(TreeNode root) {\n return DFS(root, long.MinValue, long.MaxValue);\n }\n\n private bool DFS(TreeNode root, long min, long max) {\n if (root == null) return true;\n if (min < root.val && root.val < max) {\n var leftResult = DFS(root.left, min, root.val);\n var rightResult = DFS(root.right, root.val, max);\n\n if (leftResult && rightResult) {\n return true;\n }\n }\n\n return false;\n }\n}\n``` | 12 | 0 | [] | 3 |
validate-binary-search-tree | Swift | swift-by-fuzzybuckbeak-z7op | swift\nfunc isValidBST(_ root: TreeNode?) -> Bool {\n return isBst(root, min: Int.min, max: Int.max)\n}\n \nprivate func isBst(_ node: TreeNode?, min: Int, | fuzzybuckbeak | NORMAL | 2019-02-06T09:16:55.110548+00:00 | 2019-02-06T09:16:55.110593+00:00 | 1,326 | false | ```swift\nfunc isValidBST(_ root: TreeNode?) -> Bool {\n return isBst(root, min: Int.min, max: Int.max)\n}\n \nprivate func isBst(_ node: TreeNode?, min: Int, max: Int) -> Bool {\n\tif node == nil { return true }\n\tif node!.val <= min || node!.val >= max { return false }\n\treturn isBst(node?.left, min: min, max: node!.val) &&\n\t\t isBst(node?.right, min: node!.val, max: max)\n\n}\n``` | 12 | 0 | [] | 1 |
validate-binary-search-tree | javascript | javascript-by-yinchuhui88-185e | \nvar isValidBST = function(root) {\n if(!root) \n return true\n return dfs(root, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)\n \n func | yinchuhui88 | NORMAL | 2018-12-20T12:39:48.978941+00:00 | 2018-12-20T12:39:48.978980+00:00 | 3,989 | false | ```\nvar isValidBST = function(root) {\n if(!root) \n return true\n return dfs(root, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)\n \n function dfs(root, min, max){\n if(!root) \n return true\n if(root.val <= min || root.val >= max)\n return false\n return dfs(root.left, min, root.val) && dfs(root.right, root.val, max)\n }\n};\n``` | 12 | 0 | [] | 3 |
validate-binary-search-tree | Python inorder non-recursive solution, using stack | python-inorder-non-recursive-solution-us-ygsb | class Solution(object):\n def isValidBST(self, root):\n """\n :type root: TreeNode\n :rtype: bool\n """\n | shengwen | NORMAL | 2015-10-24T20:19:01+00:00 | 2015-10-24T20:19:01+00:00 | 2,640 | false | class Solution(object):\n def isValidBST(self, root):\n """\n :type root: TreeNode\n :rtype: bool\n """\n # using inorder - binary search tree will be ascending order\n stack = []\n cur = root\n pre = None\n while len(stack) or cur:\n if cur:\n stack.append(cur)\n cur = cur.left\n else:\n p = stack.pop()\n if pre and p.val <= pre.val:\n return False\n pre = p\n cur = p.right\n return True | 12 | 0 | ['Stack', 'Python'] | 1 |
validate-binary-search-tree | Easy 100% beats. Stack. Python. | easy-100-beats-stack-python-by-einsou-57aj | IntuitionA Binary Search Tree (BST) follows a strict ordering rule:
• All nodes in the left subtree must be less than the current node.
• All nodes in the right | einsou | NORMAL | 2025-03-03T13:53:13.731115+00:00 | 2025-03-03T13:53:13.731115+00:00 | 1,121 | false | # Intuition
A Binary Search Tree (BST) follows a strict ordering rule:
• All nodes in the left subtree must be less than the current node.
• All nodes in the right subtree must be greater than the current node.
Instead of using recursion, we can leverage an iterative DFS approach with a stack.
Each node should satisfy a valid value range (min_val, max_val), which gets updated as we traverse deeper.
• Initially, the root node has no constraints, so we start with (-∞, +∞).
• As we go deeper:
• The left child must be within (-∞, node.val).
• The right child must be within (node.val, +∞).
• If any node violates its valid range, the tree is not a BST.
# Approach
1. Use a stack to perform a depth-first traversal of the tree.
2. Each stack entry contains (node, min_val, max_val), where:
• min_val: Lower bound (left subtree constraint).
• max_val: Upper bound (right subtree constraint).
3. Processing each node:
• If node.val is not within (min_val, max_val), return False (BST property violated).
• Push the right child with updated min_val = node.val into the stack.
• Push the left child with updated max_val = node.val into the stack.
# Complexity
- Time complexity:
O(N)
- Space complexity:
O(N)
# Code
```python3 []
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
stack = [(root, float('-inf'), float('inf'))]
while stack:
node, min_val, max_val = stack.pop()
if not node:
continue
if not (min_val < node.val < max_val):
return False
stack.append((node.right, node.val, max_val))
stack.append((node.left, min_val, node.val))
return True
```

| 11 | 0 | ['Python3'] | 0 |
validate-binary-search-tree | Python - Simple Solution | python-simple-solution-by-vvivekyadav-q4f7 | If you got help from this,... Plz Upvote .. it encourage me\n\n# Code\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0 | vvivekyadav | NORMAL | 2023-09-23T13:41:38.169834+00:00 | 2023-09-23T13:42:15.917342+00:00 | 1,927 | false | **If you got help from this,... Plz Upvote .. it encourage me**\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n \n def solve(root, min_val, max_val):\n if root is None:\n return True\n \n if root.val <= min_val or root.val >= max_val:\n return False\n\n left = solve(root.left, min_val, root.val)\n right = solve(root.right, root.val, max_val)\n return left and right \n\n return solve(root, float(\'-inf\'), float(\'inf\'))\n``` | 11 | 0 | ['Tree', 'Depth-First Search', 'Binary Search Tree', 'Recursion', 'Binary Tree', 'Python', 'Python3'] | 2 |
validate-binary-search-tree | Best O(N) Solution | best-on-solution-by-kumar21ayush03-9yqj | Approach\nBest Approach\n\n# Complexity\n- Time complexity:\nO(n) \n\n- Space complexity:\nO(h) --> h is height of the BST\n\n# Code\n\n/**\n * Definition for a | kumar21ayush03 | NORMAL | 2023-03-08T12:02:48.718790+00:00 | 2023-03-14T14:47:51.728225+00:00 | 3,031 | false | # Approach\nBest Approach\n\n# Complexity\n- Time complexity:\n$$O(n)$$ \n\n- Space complexity:\n$$O(h)$$ --> h is height of the BST\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n if (root->left == NULL && root->right == NULL)\n return true; \n return checkBST(root, NULL, NULL); \n }\n\n bool checkBST(TreeNode* root, TreeNode* min, TreeNode* max) {\n if (root == NULL)\n return true;\n if ((min != NULL && root->val <= min->val) || (max != NULL && root->val >= max->val))\n return false;\n return checkBST(root->left, min, root) &&\n checkBST(root->right, root, max); \n }\n};\n``` | 11 | 0 | ['C++'] | 1 |
validate-binary-search-tree | ⭐ Simple brute force solution, O(N) ⌛time O(N) 🌌 space. | simple-brute-force-solution-on-time-on-s-d0d9 | Intuition\n Describe your first thoughts on how to solve this problem. \nIf you clearly understand the question, it states that you just need to check whether t | programmer-buddy | NORMAL | 2023-03-03T11:59:38.969979+00:00 | 2023-03-03T11:59:38.970012+00:00 | 2,603 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you clearly understand the question, it states that you just need to check whether the BST is valid or not, and when we traverse a BST using INORDER, the output stream will be a sorted list.\n\n# Simple Approach\n<!-- Describe your approach to solving the problem. -->\nWe can traverse the BST using Inorder and store each output element in a list, and check whether the list is sorted or not.\n\n**FOR EXAMPLE:**\nIf the BST looks something like this:\n\n\nThe **INORDER** traversal will be - [1, 3, 4, 6, 7, 8, 10, 13, 14]\nAnd if a tree is a BST the inorder will be sorted;\n\nThe above tree is a valid BST, and we can check that using the above inorder list.\n\n\n# Complexity\n- Time complexity: O(N) for traversing tree and O(N) for checking if resultant list is sorted or not, N = Number of Nodes in a tree.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) in worst case if tree is skewed, and O(N) space for storing each element in a list.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n\n // Travserse entire tree using inorder, and store each element inside the res.\n void inorder(TreeNode* root, vector<int>&res) {\n if(!root) return;\n inorder(root->left, res);\n res.push_back(root->val);\n inorder(root->right, res);\n }\n\n bool isValidBST(TreeNode* root) {\n vector<int> res;\n inorder(root, res);\n for(int i=1; i<res.size(); ++i) {\n // Checking if res[i-1] >= res[i] then return false;\n // That means the input tree is not a valid BST;\n if(res[i-1]>=res[i]) return false;\n }\n return true;\n // Follow up: solve this without using any extra space.\n // Hint: You can use ranges, for each element.\n }\n};\n\n``` | 11 | 0 | ['Binary Search Tree', 'Recursion', 'C++'] | 2 |
validate-binary-search-tree | ✅Short || C++ || Java || PYTHON || Explained Solution✔️ || Beginner Friendly ||🔥 🔥 BY MR CODER | short-c-java-python-explained-solution-b-ngt6 | Please UPVOTE if you LIKE!!\nWatch this video for the better explanation of the code.\nAlso you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode c | mrcoderrm | NORMAL | 2022-09-12T19:04:31.629187+00:00 | 2022-09-12T19:04:31.629231+00:00 | 1,325 | false | **Please UPVOTE if you LIKE!!**\n***Watch this video for the better explanation of the code.***\n**Also you can SUBSCRIBE \uD83E\uDC83 this channel for the daily leetcode challange solution.**\nhttps://www.youtube.com/watch?v=geBeUvcMMwo\n\n**C++**\n```\nclass Solution {\npublic:\n void helper(TreeNode* root, vector<int> & ans){\n if(root==NULL ) return;\n helper(root->left, ans);\n ans.push_back(root->val);\n helper(root->right, ans);\n \n }\n bool isValidBST(TreeNode* root) {\n vector<int> ans;\n helper(root, ans);\n for(int i=0; i<ans.size()-1; i++){\n if( ans[i]>= ans[i+1] ) return false;\n }\n return true;\n }\n};\n```\n\n**PYTHON**\n\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def valid_bst(root, min_val, max_val):\n if root is None:\n return True\n if root.val <= min_val or root.val >= max_val:\n return False\n return valid_bst(root.left, min_val, root.val) and valid_bst(root.right, root.val, max_val)\n return valid_bst(root, -2**31-1, 2**31)\n```\n**JAVA**\n\n```\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n \n return isValidBST(root,Long.MIN_VALUE,Long.MAX_VALUE);\n }\n \n public boolean isValidBST(TreeNode root,long minval,long maxval){\n if(root == null) return true;\n if(root.val >= maxval || root.val <= minval) return false;\n \n return isValidBST(root.left,minval,root.val) && isValidBST(root.right,root.val,maxval);\n }\n}\n```\n**Please UPVOTE if you LIKE!!** | 11 | 0 | ['C', 'Python', 'Java'] | 2 |
validate-binary-search-tree | Easy C++ Inorder Traversal O(N) | easy-c-inorder-traversal-on-by-venkatng-cs4z | The inorder traversal of a BST is always sorted.\nAlgortihm\n1) Obtain the Inorder traversal of Binary Tree\n2) Check if Inorder traversal is sorted\n3) If sort | venkatng | NORMAL | 2022-01-11T08:28:54.355792+00:00 | 2022-01-11T08:29:42.313525+00:00 | 760 | false | The inorder traversal of a BST is always sorted.\nAlgortihm\n1) Obtain the Inorder traversal of Binary Tree\n2) Check if Inorder traversal is sorted\n3) If sorted then return TRUE\n4) If NOT sorted then return FALSE\n\nInorder Traversal Explained\n\n\n```\nclass Solution {\npublic:\n void check(TreeNode* root, vector <int>& res){\n if(root == NULL) return;\n \n check(root->left,res);\n res.push_back(root->val);\n check(root->right,res);\n }\n bool isValidBST(TreeNode* root) {\n vector <int> res;\n check(root,res);\n for(int i = 1; i <res.size(); i++){\n if(res[i] <= res[i-1]) return false;\n }\n return true;\n }\n};\n```\nUpvote if you understood.\nThank you! | 11 | 0 | ['Recursion', 'C++'] | 1 |
validate-binary-search-tree | Java solution both recursive and non-recursive - good way to build concept on Tree | java-solution-both-recursive-and-non-rec-ttgj | I found this to be a good problem to improve concepts on tree, especially BST.\nApproach 1: Employ BST property and iterative inorder traversal.\nWe remember th | th1nkgeek | NORMAL | 2021-04-10T01:16:33.367924+00:00 | 2021-04-10T01:17:35.750414+00:00 | 915 | false | I found this to be a good problem to improve concepts on tree, especially BST.\nApproach 1: Employ BST property and iterative inorder traversal.\nWe remember that in BST, an iterative inorder traversal is basically an ascending sorted list. Now, we also know that no two elements in the tree are equal.\n\nHence the simple logic that at any given point of time, the previous element should not be greater than or equal to the current element. For the first element, previous element is just "null".\n\nFor boundary conditions, we need to understand that Integer.MAX_VALUE and Integer.MIN_VALUE are all valid values, so cannot be used as sentinel markers. \n\nCode below:\n```\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n Stack<TreeNode> stack = new Stack<>();\n TreeNode prev = null;\n TreeNode curr = root;\n \n while (curr != null || !stack.isEmpty()) {\n while (curr != null) {\n stack.push(curr);\n curr = curr.left;\n }\n \n // Inorder visit of node\n curr = stack.pop();\n\t\t\t// Checking BST property\n if (prev != null && prev.val >= curr.val) {\n return false;\n }\n prev = curr;\n curr = curr.right;\n }\n // At this stage, all nodes have been visited, and we know the tree is BST\n return true;\n \n }\n}\n```\n\nNow the interviewer can ask for any alternative approach to solve this problem, like a recursive approach without any global/member variable. In this case, we need to think about invariant here are the bounds of each node.\nIf a node is a left child in a BST, it\'s max value is bound by its parent. Similarly, if it right child, then its min value is bound by its parent.\n\nOne trick here is how do we intuitively pass unbounded limits since MIN and MAX values are already taken? In Java, Integer object comes to the rescue, and the value "null" indicates unbounded value.\n\nRest of the code is pretty intuitive:\n```\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return helper(root, null, null);\n }\n \n private boolean helper(TreeNode node, Integer minVal, Integer maxVal) {\n if (node == null) {\n return true;\n }\n \n // Preorder traversal: check if the current node respects the bounds\n if (minVal != null && node.val <= minVal) {\n return false;\n }\n \n if (maxVal != null && node.val >= maxVal) {\n return false;\n }\n \n // Traverse left and right children, note that current node applies to min and max bounds based on which\n // child we select\n boolean left = helper(node.left, minVal, node.val);\n boolean right = helper(node.right, node.val, maxVal);\n return left == true && right == true;\n }\n}\n```\n\nBoth the algorithms take O(n) time complexity since they intend to visit all nodes to ensure the tree is BST, and O(h) space which signifies the stack size (explicit stack or recursion stack). Skewed tree with only left/right child will take worst case space of (n) following basic tree property.\n | 11 | 0 | ['Tree', 'Java'] | 1 |
validate-binary-search-tree | Simple Readable Java Recursion Solution | simple-readable-java-recursion-solution-mvbu9 | \nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBST(root, null, null);\n }\n \n public boolean isValidBST(Tre | anicol-l | NORMAL | 2020-04-23T23:50:16.064281+00:00 | 2020-04-23T23:51:25.597135+00:00 | 1,523 | false | ```\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBST(root, null, null);\n }\n \n public boolean isValidBST(TreeNode root, Integer min, Integer max) {\n if (root == null) \n return true; \n if ((max != null && root.val >= max) || (min != null && root.val <= min)) \n return false; \n return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);\n }\n}\n``` | 11 | 0 | ['Depth-First Search', 'Recursion', 'Java'] | 2 |
validate-binary-search-tree | Output in submit and run code are different | output-in-submit-and-run-code-are-differ-oy5f | I submit my code and got return as wrong answer since it does not pass case [0,-1]. It shows my output is false but it should be true. Then I run code by check | lizyxr | NORMAL | 2015-09-23T23:18:28+00:00 | 2015-09-23T23:18:28+00:00 | 8,009 | false | I submit my code and got return as wrong answer since it does not pass case [0,-1]. It shows my output is false but it should be true. Then I run code by check customized case [0,-1]. It shows my output is true. Is there anything wrong?\n\n # Definition for a binary tree node.\n # class TreeNode(object):\n # def __init__(self, x):\n # self.val = x\n # self.left = None\n # self.right = None\n \n class Solution(object):\n global pre\n pre = None\n def isValidBST(self, root):\n """\n :type root: TreeNode\n :rtype: bool\n """\n global pre\n if (root == None):\n return True\n if ((not self.isValidBST(root.left)) or (pre != None and pre.val >= root.val)):\n return False\n pre = root\n if (not self.isValidBST(root.right)):\n return False\n return True | 11 | 0 | [] | 5 |
validate-binary-search-tree | Morris Traversal, O(1) space, No recursion, O(n) time with explanation, Java | morris-traversal-o1-space-no-recursion-o-1hbz | // inorder traversal to see if the value is monotonically increased\n // use morris traversal to gain O(1) space, No recursion and O(n) time\n // main ide | mayijie88 | NORMAL | 2015-06-28T19:34:29+00:00 | 2015-06-28T19:34:29+00:00 | 3,278 | false | // inorder traversal to see if the value is monotonically increased\n // use morris traversal to gain O(1) space, No recursion and O(n) time\n // main idea: the key part of tree traversal is how to go back to parent,\n // one way is to use recursion and store parent in function stack,\n // another way is to use explicit stack to store parent,\n // morris traversal modify the original tree and \n // let the right child of the predecessor of the root to point back to itself\n // in order to go back to the root and then restore the pointer(set it to null again)\n // the overall time complexity is still O(n), since the tree is traversed\n // no more than twice(there is not overlap between the path of finding predecessor).\n public boolean isValidBST(TreeNode root) {\n TreeNode curr = root;\n TreeNode prev = null;\n TreeNode pred = null; // predecessor\n \n while (curr != null) {\n if (curr.left == null) {\n if (prev != null) {\n if (curr.val <= prev.val) {\n return false;\n }\n }\n prev = curr;\n curr = curr.right;\n } else {\n pred = curr.left;\n while (pred.right != null && pred.right != curr) { // find predecessor\n pred = pred.right;\n }\n if (pred.right == curr) {\n pred.right = null;\n if (prev != null) {\n if (curr.val <= prev.val) {\n return false;\n }\n }\n prev = curr;\n curr = curr.right;\n } else {\n pred.right = curr;\n curr = curr.left;\n }\n }\n }\n \n return true;\n } | 11 | 0 | ['Java'] | 2 |
validate-binary-search-tree | Simplest logic Inorder should be increasing order: Runtime- 0 ms Beats 100.00% | simplest-logic-inorder-should-be-increas-9qax | ApproachSimplest logic Inorder should be increasing orderComplexity
Time complexity:
0 ms Beats 100.00%
Space complexity:
8.08 MB Beats 7.27%
Code | sushilmaxbhile | NORMAL | 2025-04-01T05:43:33.676429+00:00 | 2025-04-01T05:46:03.421125+00:00 | 616 | false | # Approach
Simplest logic Inorder should be increasing order
# Complexity
- Time complexity:
0 ms Beats 100.00%
- Space complexity:
8.08 MB Beats 7.27%
# Code
```golang []
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isValidBST(root *TreeNode) bool {
inorder := []int{}
generateInorder(root, &inorder) // generate inorder
// if inorder[ele] >= inorder[ele+1] => invalid bst
for idx := 0; idx < len(inorder)-1; idx++ {
if inorder[idx] >= inorder[idx+1] { return false }
}
return true
}
func generateInorder(root *TreeNode, inorder *[]int) {
if root == nil { return }
generateInorder(root.Left, inorder)
(*inorder) = append((*inorder), root.Val)
generateInorder(root.Right, inorder)
}
``` | 10 | 2 | ['Go'] | 1 |
validate-binary-search-tree | Pattern easy understanding | pattern-easy-understanding-by-dixon_n-30x3 | Intuition\n\nupdate the min and max values range for everynode follow BST property of left and right values.\n\n# Complexity \n- Time complexity: O(n)\n\n- Spac | Dixon_N | NORMAL | 2024-05-13T04:50:16.410010+00:00 | 2024-05-13T04:50:16.410055+00:00 | 1,276 | false | # Intuition\n\nupdate the min and max values **range for everynode** follow BST property of left and right values.\n\n# Complexity \n- Time complexity: O(n)\n\n- Space complexity: O(n)\n# Pattern\n[1448. Count Good Nodes in Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/solutions/3978785/simple-iteration-recursion-dfs-bfs/)\n[230. Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/solutions/3951388/beats-100-t-97-63-s-simple-explanation-all-solutions/)\n\n# Code\n```java []\npublic class Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);\n }\n \n public boolean isValidBST(TreeNode root, long minVal, long maxVal) {\n if (root == null) return true;\n if (root.val >= maxVal || root.val <= minVal) return false;\n return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);\n }\n}\n```\n```java []\n\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n if (root == null) return true;\n Stack<TreeNode> stack = new Stack<>();\n TreeNode pre = null;\n while (root != null || !stack.isEmpty()) {\n while (root != null) {\n stack.push(root);\n root = root.left;\n }\n root = stack.pop();\n if(pre != null && root.val <= pre.val) return false;\n pre = root;\n root = root.right;\n }\n return true;\n}\n}\n```\n```java []\nimport java.util.LinkedList;\nimport java.util.Queue;\n\nclass Solution {\n class NodeInfo {\n TreeNode node;\n long minVal;\n long maxVal;\n \n NodeInfo(TreeNode node, long minVal, long maxVal) {\n this.node = node;\n this.minVal = minVal;\n this.maxVal = maxVal;\n }\n }\n \n public boolean isValidBST(TreeNode root) {\n if (root == null) {\n return true;\n }\n \n Queue<NodeInfo> queue = new LinkedList<>();\n queue.offer(new NodeInfo(root, Long.MIN_VALUE, Long.MAX_VALUE));\n \n while (!queue.isEmpty()) {\n NodeInfo info = queue.poll();\n TreeNode node = info.node;\n \n if (node.val <= info.minVal || node.val >= info.maxVal) {\n return false;\n }\n \n if (node.left != null) {\n queue.offer(new NodeInfo(node.left, info.minVal, node.val));\n }\n \n if (node.right != null) {\n queue.offer(new NodeInfo(node.right, node.val, info.maxVal));\n }\n }\n \n return true;\n }\n}\n```\n\n<img src="https://assets.leetcode.com/users/images/787ae0f1-23ee-4bd0-b6d5-657ac428b838_1693806287.9120827.gif" alt="Please Upvote\uD83D\uDC4D " title="Please Upvote\uD83D\uDC4D" style="display: block; margin: 0 auto;" width="120" height="200"/>\n<strong style="display: block; text-align: center; font-weight: bold;">This is a tree series solution, please upvote if you find this helpful.</strong>\n | 10 | 0 | ['Tree', 'Binary Search Tree', 'Recursion', 'Binary Tree', 'Java'] | 2 |
validate-binary-search-tree | C++ | 6 different solutions | recursive / iteratively / in-order traversal check previous / ... | c-6-different-solutions-recursive-iterat-deu4 | I came up with a few different approaches. Please let me know if you came up with another idea.Solution 1: recursive with numeric limitsSolution 2: recursive wi | heder | NORMAL | 2022-08-11T07:13:40.352620+00:00 | 2025-03-03T22:28:11.821527+00:00 | 401 | false | I came up with a few different approaches. Please let me know if you came up with another idea.
**Solution 1: recursive with numeric limits**
```
bool isValidBST(TreeNode* root) {
return isValidBST(root, numeric_limits<long>::min(), numeric_limits<long>::max());
}
bool isValidBST(TreeNode* node, long min, long max) {
if (!node) return true;
return
(min < node->val && node->val < max) &&
isValidBST(node->left, min, node->val) &&
isValidBST(node->right, node->val, max);
}
```
**Solution 2: recursive with lower bound and upper bound node**
In this version we don't need to make any assumptions about ```TreeNode::val```, all we care about is that they are compareable. In the following solutions we always only compare values to each other and don't make any futher assumptions about there type.
```
bool isValidBST(TreeNode* root) {
return isValidBST(root, nullptr, nullptr);
}
bool isValidBST(TreeNode* node, TreeNode* lb, TreeNode* ub) {
if (!node) return true;
if (lb && !(lb->val < node->val)) return false;
if (ub && !(node->val < ub->val)) return false;
return
isValidBST(node->left, lb, node) &&
isValidBST(node->right, node, ub);
}
```
**Solution 3: interative with lower bound and upper bound node**
We might as well do this iteratively. We could also use a ```stack``` instead of a ```queue```.
```
bool isValidBST(TreeNode* root) {
if (!root) return true;
queue<array<TreeNode*, 3>> q;
q.push({root, nullptr, nullptr});
while (!empty(q)) {
auto [node, lb, ub] = q.front(); q.pop();
if (lb && lb->val >= node->val) return false;
if (ub && ub->val <= node->val) return false;
if (node->left) q.push({node->left, lb, node});
if (node->right) q.push({node->right, node, ub});
}
return true;
}
```
**Solution 4: inorder traversal w/ previous node recursively**
A different approach is to compare a node with a previous node in an inorder traversal. The values need to be asceding.
```
bool isValidBST(TreeNode* root) {
TreeNode* prev = nullptr;
return isValidBST(root, &prev);
}
bool isValidBST(TreeNode* root, TreeNode** prev) {
if (!root) return true;
if (root->left && !isValidBST(root->left, prev)) return false;
// visit
if (*prev && root->val <= (*prev)->val) return false;
*prev = root;
if (root->right && !isValidBST(root->right, prev)) return false;
return true;
}
```
**Solution 5: inorder traversal w/ previous node iteratively**
Like solution 4, but iteratively.
```
bool isValidBST(TreeNode* root) {
stack<TreeNode*> st;
TreeNode* prev = nullptr;
while (true) {
while (root) {
st.push(root);
root = root->left;
}
if (empty(st)) break;
root = st.top(); st.pop();
// Visit.
if (prev && prev->val >= root->val) return false;
prev = root;
root = root->right;
}
return true;
}
```
**Solution 6: serialise the BST and check if sequence is monotonic increasing**
Note that ```std::is_sorted``` can't be used here. This uses extra memory for the serialised sequence, which feels a bit unnecassary, but oh well, sue me. :)
```
bool isValidBST(TreeNode* root) {
vector<int> values;
stack<TreeNode*> st;
while (true) {
while (root) {
st.push(root);
root = root->left;
}
if (empty(st)) break;
root = st.top(); st.pop();
// Visit.
values.push_back(root->val);
root = root->right;
}
// NB. std::is_sorted can't be used, because while [2,2,2] is sorted it's not
// strictly increasing, which is what we need to test for here.
return adjacent_find(begin(values), end(values), greater_equal<>()) == end(values);
}
```
**Bonus Solution: custom STL iterator**
We can turn this into a one liner:
```
bool isValidBST(TreeNode* root) {
// NB. std::is_sorted can't be used, because while [2,2,2] is sorted it's not
// strictly increasing, which is what we need to test for here.
return adjacent_find(begin(root), end(root), greater_equal<>()) == end(root);
}
```
... if we implement a custom iterator for ```TreeNode```. This avoids the extra memory for the ```vector<int>``` from solution 6, but this iterator is quite a heavy object and expensive to copy. It would take more work to make this efficient, but it works. To make the code above work we need something like this:
```
// TODO(heder): Can we turn this into a "lean" iterator? This one is quite "fat", as it has
// a stack<> member.
struct Iterator
{
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = int;
using pointer = value_type*;
using reference = value_type&;
// TODO(heder): Keep the root pointer around so we know if the iterator is
// from the same tree?
Iterator(TreeNode* root) : curr_(root) {
gotoLeftMost(curr_);
}
reference operator*() const { return curr_->val; }
pointer operator->() { return &(curr_->val); }
// Prefix increment
Iterator& operator++() {
if (curr_) {
gotoLeftMost(curr_->right);
}
return *this;
}
// Postfix increment
Iterator operator++(int) { Iterator tmp = *this; ++(*this); return tmp; }
friend bool operator== (const Iterator& a, const Iterator& b) {
return a.curr_ == b.curr_;
};
friend bool operator!= (const Iterator& a, const Iterator& b) { return !(a == b); }
private:
stack<TreeNode*> st_;
TreeNode* curr_;
void gotoLeftMost(TreeNode* node) {
while (node) {
st_.push(node);
node = node->left;
}
if (empty(st_)) {
curr_ = nullptr;
} else {
curr_ = st_.top();
st_.pop();
}
}
};
struct Iterator begin(TreeNode* root) {
return Iterator(root);
}
struct Iterator end(TreeNode* root) {
return Iterator(nullptr);
}
```
Comments on how to improve any of the solutions are welcome. | 10 | 1 | ['Recursion', 'C', 'Iterator'] | 0 |
validate-binary-search-tree | C++ long long man | c-long-long-man-by-midnightsimon-yo3s | if you go left, set bounds to min to root->val\n2. if you go right, set boudns to root->val to max\n3. use long long to get away from overflow and underflows\n4 | midnightsimon | NORMAL | 2022-08-11T01:27:00.424163+00:00 | 2022-08-11T01:27:00.424211+00:00 | 1,290 | false | 1. if you go left, set bounds to min to root->val\n2. if you go right, set boudns to root->val to max\n3. use long long to get away from overflow and underflows\n**4. check out the twitch channel. Link in profile.**\n```\nclass Solution { \n bool dfs(TreeNode* root, long long mn, long long mx) {\n if(!root) return true;\n \n if(root->val <= mn || root->val >= mx) return false;\n \n bool left = dfs(root->left, mn, root->val);\n bool right = dfs(root->right, root->val, mx);\n \n return left && right;\n }\n \npublic:\n bool isValidBST(TreeNode* root) {\n return dfs(root, LONG_MIN, LONG_MAX);\n }\n};\n``` | 10 | 1 | [] | 3 |
validate-binary-search-tree | C++ clear recursive solution without using longlong/double | c-clear-recursive-solution-without-using-mjmg | \nclass Solution {\npublic:\n bool isValidBST(TreeNode* root, TreeNode* nmin = nullptr, TreeNode* nmax = nullptr) {\n if(!root) \n return t | freeyy | NORMAL | 2019-07-27T12:10:59.441616+00:00 | 2019-07-27T12:11:35.096670+00:00 | 1,806 | false | ```\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root, TreeNode* nmin = nullptr, TreeNode* nmax = nullptr) {\n if(!root) \n return true;\n if(nmin && root->val <= nmin->val)\n return false;\n if(nmax && root->val >= nmax->val)\n return false;\n return isValidBST(root->left, nmin, root) && isValidBST(root->right, root, nmax);\n }\n};\n``` | 10 | 1 | ['Recursion', 'C++'] | 3 |
validate-binary-search-tree | Easy to Understand - Concise - C++ | easy-to-understand-concise-c-by-lc00703-69ko | Code\n\nclass Solution {\npublic:\n vector<int> nodes;\n void inorder(TreeNode* root) {\n if (root->left) inorder(root->left);\n nodes.push_ | lc00703 | NORMAL | 2023-04-21T12:39:45.639915+00:00 | 2023-04-21T12:39:45.639963+00:00 | 8,065 | false | # Code\n```\nclass Solution {\npublic:\n vector<int> nodes;\n void inorder(TreeNode* root) {\n if (root->left) inorder(root->left);\n nodes.push_back(root->val);\n if (root->right) inorder(root->right);\n }\n bool isValidBST(TreeNode* root) {\n inorder(root);\n for (int i = 0; i < nodes.size() - 1; i++) {\n if (nodes[i] >= nodes[i+1]) return false;\n }\n return true;\n }\n};\n``` | 9 | 0 | ['C++'] | 0 |
validate-binary-search-tree | Python solution with linear time complexity. 100% working! | python-solution-with-linear-time-complex-upth | \n def dfs(lower,upper,node):\n if not node:\n return True\n elif node.val<=lower or node.val>=upper:\n | enigmatic__soul | NORMAL | 2023-01-28T18:39:00.395973+00:00 | 2023-01-28T18:39:00.396017+00:00 | 2,242 | false | \n def dfs(lower,upper,node):\n if not node:\n return True\n elif node.val<=lower or node.val>=upper:\n return False\n else:\n return dfs(lower,node.val,node.left) and dfs(node.val,upper,node.right)\n return dfs(float(\'-inf\'),float(\'inf\'),root) \n``` | 9 | 0 | ['Python'] | 0 |
validate-binary-search-tree | Optimized approach | optimized-approach-by-nikhil_mane-yq1s | 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 | nikhil_mane | NORMAL | 2023-01-02T02:11:57.929211+00:00 | 2023-01-02T02:11:57.929255+00:00 | 2,842 | 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```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n bool isValidBST(TreeNode* root) {\n \n return check(root, LONG_MIN, LONG_MAX);\n }\n\n bool check(TreeNode* root, long minval, long maxval ){\n\n if(root==NULL) return true;\n\n if(root->val >= maxval || root->val <= minval) return false;\n\n return check(root->left,minval, root->val) && check(root->right, root->val, maxval);\n\n\n }\n};\n``` | 9 | 0 | ['C++'] | 0 |
validate-binary-search-tree | Python - Recursion and Recursive stack space + O(1) space | python-recursion-and-recursive-stack-spa-v5k2 | Without using a list just use prev variable to store the previous node value and check if the Tree nodes are in ascending order during the inorder traversal. Yo | Thiru_Mv | NORMAL | 2022-08-01T22:23:57.545318+00:00 | 2022-08-01T22:29:14.480588+00:00 | 522 | false | Without using a list just use prev variable to store the previous node value and check if the Tree nodes are in ascending order during the inorder traversal. You dont have to create extra space for list.\n \n def isValidBST(self, root):\n """\n :type root: TreeNode\n :rtype: bool\n """\n self.flag = True\n self.prev = float("-inf")\n self.inorder(root)\n return self.flag\n\n \n def inorder(self,root):\n #base condition\n if root==None:\n return\n \n\n self.inorder(root.left)\n \n if root.val<=self.prev:\n self.flag = False \n self.prev = root.val\n \n self.inorder(root.right) | 9 | 0 | ['Recursion', 'Python'] | 0 |
validate-binary-search-tree | Python recursive and iterative solutions | python-recursive-and-iterative-solutions-8qpe | Recursive solution:\n\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def helper(root, min_val=float("-inf"), max_val=flo | PythonicLava | NORMAL | 2022-06-26T00:18:49.921198+00:00 | 2022-06-26T00:18:49.921225+00:00 | 1,508 | false | Recursive solution:\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n def helper(root, min_val=float("-inf"), max_val=float("inf")):\n if root is None:\n return True\n \n return (min_val < root.val < max_val and helper(root.left, min_val, root.val) and helper(root.right, root.val, max_val))\n return helper(root)\n```\n\nIterative Solution:\n```\nclass Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n queue = deque()\n queue.append((root, float("-inf"), float("inf")))\n \n while queue:\n node, min_val, max_val = queue.popleft()\n if node:\n if min_val >= node.val or node.val >= max_val:\n return False\n if node.left:\n queue.append((node.left, min_val, node.val))\n \n if node.right:\n queue.append((node.right, node.val, max_val))\n return True\n``` | 9 | 1 | ['Recursion', 'Iterator', 'Python', 'Python3'] | 1 |
validate-binary-search-tree | Neat Java Recursive Solution | neat-java-recursive-solution-by-jayomg-5zgf | java\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBST(root, null, null);\n }\n \n public boolean isValidBST | jayomg | NORMAL | 2019-01-31T00:50:49.750231+00:00 | 2019-01-31T00:50:49.750294+00:00 | 759 | false | ``` java\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n return isValidBST(root, null, null);\n }\n \n public boolean isValidBST(TreeNode x, TreeNode min, TreeNode max) {\n if (x == null) return true;\n if (max != null && x.val >= max.val) return false;\n if (min != null && x.val <= min.val) return false;\n return isValidBST(x.left, min, x) && isValidBST(x.right, x ,max);\n }\n}\n\n```\n\n | 9 | 0 | [] | 2 |
validate-binary-search-tree | Java solution after adding test cases | java-solution-after-adding-test-cases-by-qfuc | Actually, not too much needs to be changed if you got AC code when extra test cases are not added. The only difference is add if-else condition for node's value | chase1991 | NORMAL | 2014-11-16T23:42:35+00:00 | 2014-11-16T23:42:35+00:00 | 2,562 | false | Actually, not too much needs to be changed if you got AC code when extra test cases are not added. The only difference is add if-else condition for node's value equals INT_MAX and INT_MIN. \n\n public class Solution {\n public boolean isValidBST(TreeNode root) {\n if (root == null) {\n return true;\n }\n if (root.left == null && root.right == null) {\n return true;\n }\n return check(root, Integer.MAX_VALUE, Integer.MIN_VALUE);\n }\n \n public boolean check(TreeNode node, int max, int min) {\n if (node == null) {\n return true;\n }\n if (node.val > max || node.val < min) {\n return false;\n }\n \n // if node's value is INT_MIN, it should not have left child any more\n if (node.val == Integer.MIN_VALUE && node.left != null) {\n return false;\n }\n \n // if node's value is INT_MAX, it should not have right child any more\n if (node.val == Integer.MAX_VALUE && node.right != null) {\n return false;\n }\n \n return check(node.left, node.val - 1, min) && check(node.right, max, node.val + 1);\n }\n } | 9 | 0 | [] | 4 |
validate-binary-search-tree | ✅💯🔥Simple Code🚀📌|| 🔥✔️Easy to understand🎯 || 🎓🧠Beats 100%🔥|| Beginner friendly💀💯 | simple-code-easy-to-understand-beats-100-7pxb | Solution tuntun mosi ki photo ke baad hai. Scroll Down\n\n\n# Code\njava []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int | atishayj4in | NORMAL | 2024-08-20T21:07:57.351801+00:00 | 2024-08-20T21:07:57.351832+00:00 | 1,792 | false | Solution tuntun mosi ki photo ke baad hai. Scroll Down\n\n\n# Code\n```java []\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n long Prev = Long.MIN_VALUE;\n\n void inorder(TreeNode a, boolean[] Is) {\n if (a == null){\n return;\n }\n inorder(a.left, Is);\n if (a.val <= Prev){\n Is[0] = false;\n }\n Prev = a.val;\n inorder(a.right, Is);\n }\n\n public boolean isValidBST(TreeNode a) {\n boolean[] Is = {true};\n inorder(a, Is);\n return Is[0];\n }\n}\n```\n | 8 | 1 | ['Tree', 'Depth-First Search', 'Binary Search Tree', 'C', 'Binary Tree', 'Python', 'C++', 'Java', 'JavaScript'] | 2 |
validate-binary-search-tree | 0ms||Easy||JAVA✌ | 0mseasyjava-by-tamosakatwa-guba | 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 | tamosakatwa | NORMAL | 2023-01-08T15:04:33.317081+00:00 | 2023-01-08T15:04:33.317119+00:00 | 2,180 | 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```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public TreeNode pre=null;\n public boolean isValidBST(TreeNode root) {\n \n if(root!=null){\n if(!isValidBST(root.left)) return false;\n if(pre!=null && root.val<=pre.val) return false;\n pre=root;\n return isValidBST(root.right);\n } \n return true;\n }\n}\n``` | 8 | 1 | ['Java'] | 1 |
validate-binary-search-tree | ✅Easiest 3 Lines Recursive Solution✅ | easiest-3-lines-recursive-solution-by-yo-beks | Easiest 3 lines recursive solution using C++.\nSelf Explanatory\n\n bool isBST(TreeNode* root,long min, long max){\n if(root==NULL) return true;\n | yogesh3_14 | NORMAL | 2022-08-12T04:53:46.203711+00:00 | 2022-08-15T00:19:20.691984+00:00 | 368 | false | **Easiest 3 lines recursive solution using C++.\nSelf Explanatory**\n```\n bool isBST(TreeNode* root,long min, long max){\n if(root==NULL) return true;\n if(root->val <= min || root->val >= max) return false;\n return isBST(root->left,min,root->val) and isBST(root->right,root->val,max);\n }\n \n bool isValidBST(TreeNode* root) {\n return isBST(root, LONG_MIN, LONG_MAX);\n }\n```\n**Please UPVOTE if you like** | 8 | 0 | ['Binary Search Tree', 'Recursion', 'C'] | 0 |
validate-binary-search-tree | 🗓️ Daily LeetCoding Challenge August, Day 11 | daily-leetcoding-challenge-august-day-11-4w7x | This problem is the Daily LeetCoding Challenge for August, Day 11. Feel free to share anything related to this problem here! You can ask questions, discuss what | leetcode | OFFICIAL | 2022-08-11T00:00:27.674623+00:00 | 2022-08-11T00:00:27.674698+00:00 | 7,767 | false | This problem is the Daily LeetCoding Challenge for August, Day 11.
Feel free to share anything related to this problem here!
You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made!
---
If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide
- **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem.
- **Images** that help explain the algorithm.
- **Language and Code** you used to pass the problem.
- **Time and Space complexity analysis**.
---
**📌 Do you want to learn the problem thoroughly?**
Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/validate-binary-search-tree/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis.
<details>
<summary> Spoiler Alert! We'll explain these 4 approaches in the official solution</summary>
**Approach 1:** Recursive Traversal with Valid Range
**Approach 2:** Iterative Traversal with Valid Range
**Approach 3:** Recursive Inorder Traversal
**Approach 4:** Iterative Inorder Traversal
</details>
If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)!
---
<br>
<p align="center">
<a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank">
<img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" />
</a>
</p>
<br> | 8 | 0 | [] | 71 |
validate-binary-search-tree | Java Recursive Approach (100% Faster) | java-recursive-approach-100-faster-by-ni-8t0z | \n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n | nikitajuneja1 | NORMAL | 2022-03-07T16:58:57.366456+00:00 | 2022-03-07T16:59:46.302363+00:00 | 770 | false | ```\n/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n public boolean isValidBST(TreeNode root) {\n //for every node, maintain upper bound and lowerbound\n //helper func(root, lower bound, upper bound) - for recursion\n return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);\n }\n boolean helper(TreeNode root, long min, long max){\n if(root==null)\n return true;\n if(root.val<=min || root.val>=max)\n return false;\n //update the lower bound for right subtree and upper bound for left subtree\n return helper(root.left, min, root.val) && helper(root.right, root.val, max);\n }\n}\n```\nPlease upvote if it helps! | 8 | 0 | ['Depth-First Search', 'Recursion', 'Java'] | 0 |
validate-binary-search-tree | C++ Easy Solution | Recursion | c-easy-solution-recursion-by-amittiwari0-3jco | \nclass Solution {\npublic:\n \n bool solve(TreeNode* root, long long int min,long long int max){\n if(!root)return true;\n \n if(roo | amittiwari04 | NORMAL | 2021-11-12T05:53:33.029396+00:00 | 2021-11-12T05:53:33.029443+00:00 | 1,259 | false | ```\nclass Solution {\npublic:\n \n bool solve(TreeNode* root, long long int min,long long int max){\n if(!root)return true;\n \n if(root->val>=max || root->val<=min)return false;\n \n return solve(root->left,min,root->val) and solve(root->right,root->val,max);\n }\n \n bool isValidBST(TreeNode* root) {\n if(!root)return true;\n \n return solve(root,-1e18,1e18);\n }\n};\n```\n\nHope you like it.\n\nPlease upvote it :) | 8 | 0 | ['Recursion', 'C', 'C++'] | 1 |
validate-binary-search-tree | Python Morris O(1) space approach | python-morris-o1-space-approach-by-dynam-7wzk | For when the Interviewer asks for a space optimal i.e. O(1) BST traversal as a follow-up question.\nThis is standard in-order morris traversal as a generator. T | dynamicstardust | NORMAL | 2021-03-27T03:03:36.686436+00:00 | 2021-03-28T05:38:16.215480+00:00 | 301 | false | For when the Interviewer asks for a space optimal i.e. O(1) BST traversal as a follow-up question.\nThis is standard in-order morris traversal as a generator. The values yielded by Morris generator with BST should be strictly increasing in this problem.\n\n```\nclass Solution:\n def isValidBST(self, root: TreeNode) -> bool:\n def morris(root):\n if not root: return None\n curr = root\n while curr:\n if not curr.left:\n yield curr.val\n curr = curr.right\n else:\n prev = curr.left\n while prev.right != None and prev.right != curr:\n prev = prev.right\n if prev.right == None:\n prev.right = curr\n curr = curr.left\n elif prev.right == curr:\n prev.right = None\n yield curr.val\n curr = curr.right\n prev = -math.inf\n for val in morris(root):\n if val <= prev: return False\n prev = val\n return True\n```\nNote: Morris traversal has an O(N) time complexity, since we visit every node in the worst case. It has a O(1) space complexity, since we merely modify (change and restore) pointers during traversal and do not make use of any stack memory.\n---\n<img src="https://assets.leetcode.com/users/images/46a0cb74-af6c-48ec-8d80-6b298cbe5e4f_1616909821.403881.png" width=700>\n | 8 | 0 | ['Python'] | 1 |
validate-binary-search-tree | 🔥BEATS 💯 % 🎯 |✨SUPER EASY BEGINNERS 👏 | beats-super-easy-beginners-by-codewithsp-u9rg | IntuitionThe problem requires us to determine whether a given binary tree is a valid binary search tree (BST). A valid BST must satisfy the following conditions | CodeWithSparsh | NORMAL | 2025-01-20T15:56:47.577585+00:00 | 2025-01-20T15:58:01.451327+00:00 | 1,409 | false | 
---

---
## Intuition
The problem requires us to determine whether a given binary tree is a valid binary search tree (BST). A valid BST must satisfy the following conditions:
1. The left subtree of a node contains only nodes with values less than the node’s value.
2. The right subtree of a node contains only nodes with values greater than the node’s value.
3. Both the left and right subtrees must also be binary search trees.
My first thought is to use a recursive approach to traverse the tree while keeping track of the permissible range for each node's value. This can be done by passing down the minimum and maximum allowable values as we traverse.
## Approach
1. **Recursive Helper Function**:
- Implement a helper function that takes a node and the permissible minimum and maximum values for that node.
- If the current node is null, return true (base case).
- Check if the current node's value violates the min-max constraints:
- If it is less than or equal to the minimum or greater than or equal to the maximum, return false.
- Recursively check the left subtree with updated maximum (current node's value) and the right subtree with updated minimum (current node's value).
- Return true if both subtrees are valid.
2. **Initial Call**:
- Start the recursion from the root of the tree, initially allowing any integer values as bounds.
### Code Examples
```cpp []
#include <bits/stdc++.h>
using namespace std;
class TreeNode {
public:
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
bool isValidBST(TreeNode* root) {
return helper(root, LONG_MIN, LONG_MAX);
}
bool helper(TreeNode* node, long min, long max) {
if (node == nullptr) return true; // Base case: empty tree is valid
if (node->val <= min || node->val >= max) return false; // Check constraints
// Recursively check left and right subtrees
return helper(node->left, min, node->val) && helper(node->right, node->val, max);
}
};
```
```java []
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode node, long min, long max) {
if (node == null) return true; // Base case: empty tree is valid
if (node.val <= min || node.val >= max) return false; // Check constraints
// Recursively check left and right subtrees
return helper(node.left, min, node.val) && helper(node.right, node.val, max);
}
}
```
```javascript []
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class Solution {
isValidBST(root) {
return this.helper(root, -Infinity, Infinity);
}
helper(node, min, max) {
if (node === null) return true; // Base case: empty tree is valid
if (node.val <= min || node.val >= max) return false; // Check constraints
// Recursively check left and right subtrees
return this.helper(node.left, min, node.val) && this.helper(node.right, node.val, max);
}
}
```
```python []
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.helper(root, float('-inf'), float('inf'))
def helper(self, node: TreeNode, min_val: float, max_val: float) -> bool:
if not node:
return True # Base case: empty tree is valid
if not (min_val < node.val < max_val):
return False # Check constraints
# Recursively check left and right subtrees
return self.helper(node.left, min_val, node.val) and self.helper(node.right, node.val, max_val)
```
```dart []
class TreeNode {
int val;
TreeNode? left;
TreeNode? right;
TreeNode([this.val = 0, this.left, this.right]);
}
class Solution {
bool isValidBST(TreeNode? root) {
return helper(root, double.negativeInfinity, double.infinity);
}
bool helper(TreeNode? node, double minVal, double maxVal) {
if (node == null) return true; // Base case: empty tree is valid
if (node.val <= minVal || node.val >= maxVal) return false; // Check constraints
// Recursively check left and right subtrees
return helper(node.left, minVal, node.val) && helper(node.right, node.val, maxVal);
}
}
```
## Complexity
- **Time complexity**: $$O(n)$$ where $$n$$ is the number of nodes in the binary tree since each node needs to be visited once.
- **Space complexity**: $$O(h)$$ where $$h$$ is the height of the tree. This accounts for space used by recursion stack. In a balanced BST constructed from sorted data, $$h$$ would be $$O(\log n)$$; in a skewed tree (e.g., linked list-like structure), it could reach up to $$O(n)$$.
## Citations
**Validating Binary Search Trees**: A detailed explanation of how to validate BSTs using various methods [LeetCode](https://leetcode.com/problems/validate-binary-search-tree/).
---
 {:style='width:250px'}
| 7 | 0 | ['Tree', 'Depth-First Search', 'Binary Search Tree', 'C', 'Binary Tree', 'C++', 'Java', 'Python3', 'JavaScript', 'Dart'] | 2 |
watering-plants-ii | Straightforward | straightforward-by-votrubac-z18w | I am scared of Alice and Bob problems. But this one, luckily, is benign (except for a lengthy description).\n\nThe one thing to realize is that, if the array si | votrubac | NORMAL | 2021-12-12T04:02:05.024729+00:00 | 2021-12-12T04:19:08.328164+00:00 | 2,827 | false | I am scared of Alice and Bob problems. But this one, luckily, is benign (except for a lengthy description).\n\nThe one thing to realize is that, if the array size is odd, Alice or Bob can water it if they have water, or one of them needs to refill otherwise.\n\n**C++**\n```cpp\nint minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int i = 0, j = plants.size() - 1, canA = capacityA, canB = capacityB, res = 0;\n while (i < j) {\n res += (canA < plants[i]) + (canB < plants[j]);\n canA = canA < plants[i] ? capacityA : canA;\n canB = canB < plants[j] ? capacityB : canB;\n canA -= plants[i++];\n canB -= plants[j--];\n }\n return res + (i == j && max(canA, canB) < plants[i]);\n}\n``` | 49 | 6 | [] | 7 |
watering-plants-ii | [C++/Java/Python] O(N) Easy Intuition + Image Explanation | cjavapython-on-easy-intuition-image-expl-f0ly | As it\'s given in problem statement\n> Alice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from rig | sachuverma | NORMAL | 2021-12-12T04:03:27.738493+00:00 | 2021-12-12T05:15:22.077948+00:00 | 2,487 | false | As it\'s given in problem statement\n> Alice waters the plants in order from **left to right**, starting from the `0th` plant. Bob waters the plants in order from **right to left**, starting from the `(n - 1)th` plant. They begin watering the plants **simultaneously**.\n\n\n# Intuition:\n\nWe need to keep two pointer in left and right to start watering from both sides simultaneously. \nKeep on counting fills for both of them. \nAnd when they meet in middle find the one with more water. \n\n# Example:\n\nplants = [2, 1, 1, 1]\naliceCapacity = 2, bobCapacity = 4\naliceCan = 2, bobCan = 4\n\nNow currently Alice will water 0th plant and Bob waters 3rd plant.\nThere was no refill.\naliceCan = 0, bobCan = 3\nrefills = 0\n\nThen Alice will not be able to water 1st plant, so she needs to refill\nbut Bob waters 2rd plant.\naliceCan = 1, bobCan = 3\nrefills = 1\n\nHence total refills were 1.\n\nBut consider we had one more plant in middle.\n[2, 1, 2, 1, 1]\nBoth will reach at 2nd plant at same time\nBob had 2 in it\'s can but Alice had 0\nHence bob would have watered it without refill.\n\n\n\n\n# Code:\n\n## C++:\n```c++\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int N = plants.size(), i = 0, j = N - 1;\n \n if (N == 1) return 0;\n \n int totalFills = 0; \n int aliceCan = capacityA, bobCan = capacityB; \n \n // Iterate over all plants left and right one similutaneously.\n while (i <= j) {\n \n // We have reached middle plant.\n if (i == j) { \n // The one with more water in can will water the plant.\n if (aliceCan >= bobCan) {\n if (aliceCan < plants[i]) {\n // Alice need to refill the can.\n ++totalFills;\n }\n ++i;\n }\n else {\n if (bobCan < plants[j]) {\n // Bob need to refill the can.\n ++totalFills;\n }\n --j;\n }\n } \n \n else {\n // If Alice doesn\'t have sufficient water, she refills.\n if (aliceCan < plants[i]) {\n aliceCan = capacityA;\n ++totalFills;\n }\n \n // Alice waters.\n aliceCan -= plants[i];\n ++i;\n \n // If Bob doesn\'t have sufficient water, he refills.\n if (bobCan < plants[j]) {\n bobCan = capacityB; \n ++totalFills;\n }\n \n // Bob waters.\n bobCan -= plants[j];\n --j;\n }\n }\n return totalFills;\n }\n};\n```\n\n## Java:\n```java\nclass Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n int N = plants.length, i = 0, j = N - 1;\n \n if (N == 1) return 0;\n \n int totalFills = 0; \n int aliceCan = capacityA, bobCan = capacityB; \n \n while (i <= j) {\n if (i == j) { \n if (aliceCan >= bobCan) {\n if (aliceCan < plants[i]) {\n ++totalFills;\n }\n ++i;\n }\n else {\n if (bobCan < plants[j]) {\n ++totalFills;\n }\n --j;\n }\n } \n \n else {\n if (aliceCan < plants[i]) {\n aliceCan = capacityA;\n ++totalFills;\n }\n aliceCan -= plants[i];\n ++i;\n \n if (bobCan < plants[j]) {\n bobCan = capacityB; \n ++totalFills;\n }\n bobCan -= plants[j];\n --j;\n }\n }\n \n return totalFills;\n }\n}\n```\n\n## Python:\n```python\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n N = len(plants)\n i, j = 0, N -1\n \n if N == 1: \n return 0\n \n totalFills = 0\n aliceCan, bobCan = capacityA, capacityB\n \n while i <= j:\n \n if i == j:\n if aliceCan >= bobCan:\n if aliceCan < plants[i]:\n totalFills += 1\n i += 1\n \n else:\n if bobCan < plants[j]:\n totalFills += 1\n j -= 1 \n \n else:\n if aliceCan < plants[i]:\n aliceCan = capacityA\n totalFills += 1\n \n aliceCan -= plants[i]\n i += 1\n \n if bobCan < plants[j]:\n bobCan = capacityB;\n totalFills += 1\n \n bobCan -= plants[j]\n j -= 1\n \n return totalFills\n \n```\n\n# Complexity Analysis:\n**Time Complexity: O(N) -** We traverse each plant in the array only once.\n**Space Complexity: O(1) -** We only use constant variables.\n\n\nUpvote if you like. Comment for suggestions. \uD83D\uDE05 | 27 | 2 | [] | 8 |
watering-plants-ii | Java | Simple Detailed Explanation || ⏲ 3ms100% faster || 2 Pointer | java-simple-detailed-explanation-3ms100-qa7c8 | \u2714 Solution: 2 Pointer | Beats 100 %, 3ms \u23F2\n-----\n Alice start from i=0\n Bob start from j=n-1 index , n size of array\n Both Alice and bob move one | abhi9720 | NORMAL | 2021-12-12T16:29:46.313235+00:00 | 2022-02-21T15:19:47.218783+00:00 | 1,203 | false | ### \u2714 ***Solution: 2 Pointer*** | Beats 100 %, 3ms \u23F2\n-----\n* Alice start from i=0\n* Bob start from j=n-1 index , n size of array\n* Both Alice and bob move one step , Now all cases possible in their movement\n\t* **Case 1 :** Alice and Bob both have sufficient water , they will water plant \n\t* **Case 2 :** Either Alice or Bob water finished , then refill water can of their and `increase refill count`\n\t* **Case 3**: If Alice and bob reach a plant at same time , then Check which one have more water , that will watering plant , if both with equal water then Alice water \n\t* Lets Make all these If-else conditions \n\n### Lets Code \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB\uD83D\uDCBB\n---\nDo read comment for more better understanding \n```\nclass Solution {\n public int minimumRefill(int[] p, int ca, int cb) { \n\t\n int refill= 0,oca = ca, ocb = cb;// let save our orginal capacity , needed to refill can again\n int i=0, j = p.length-1; // starting both end \n \n while(i<=j){\n\t\t\n if(i==j){// mean both at same position\n if(ca>=cb){\n if(p[i]>ca){\n refill++;\n } \n }\n else{ \n if(p[j]>cb){\n refill++; \n } \n }\n\t\t\t\t // no more plant left for watering so break loop \n break; \n }\n \n // first check if they have sufficient amount of water \n // if not then refill it with orginal capacity \n\t\t\t\n if(p[i]>ca){\n refill++;\n ca = oca;\n } \n if(p[j]>cb){\n refill++;\n cb= ocb;\n }\n \n\t\t\t// decrease consumed water \n ca-=p[i] ; \n cb-=p[j]; \n\t\t\t\n\t\t\t// move both \n\t\t\ti++; \n j--;\t\t\t \n }\n return refill; \n }\n}\n```\n | 19 | 1 | ['Two Pointers', 'Java'] | 3 |
watering-plants-ii | [Python3] 2 pointers | python3-2-pointers-by-ye15-hikm | Please check out this commit for solutions of weekly 271. \n\n\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) | ye15 | NORMAL | 2021-12-12T04:02:06.535814+00:00 | 2021-12-12T18:43:10.904122+00:00 | 965 | false | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/f57038d6cca9ccb356a137b3af67fba615a067dd) for solutions of weekly 271. \n\n```\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n ans = 0 \n lo, hi = 0, len(plants)-1\n canA, canB = capacityA, capacityB\n while lo < hi: \n if canA < plants[lo]: ans += 1; canA = capacityA\n canA -= plants[lo]\n if canB < plants[hi]: ans += 1; canB = capacityB\n canB -= plants[hi]\n lo, hi = lo+1, hi-1\n if lo == hi and max(canA, canB) < plants[lo]: ans += 1\n return ans \n``` | 10 | 0 | ['Python3'] | 2 |
watering-plants-ii | C++ solutions | c-solutions-by-infox_92-4m9w | \nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int N = plants.size(), i = 0, j = N - 1;\n | Infox_92 | NORMAL | 2022-11-20T06:29:40.500895+00:00 | 2022-11-20T06:29:40.500940+00:00 | 497 | false | ```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int N = plants.size(), i = 0, j = N - 1;\n \n if (N == 1) return 0;\n \n int totalFills = 0; \n int aliceCan = capacityA, bobCan = capacityB; \n \n // Iterate over all plants left and right one similutaneously.\n while (i <= j) {\n \n // We have reached middle plant.\n if (i == j) { \n // The one with more water in can will water the plant.\n if (aliceCan >= bobCan) {\n if (aliceCan < plants[i]) {\n // Alice need to refill the can.\n ++totalFills;\n }\n ++i;\n }\n else {\n if (bobCan < plants[j]) {\n // Bob need to refill the can.\n ++totalFills;\n }\n --j;\n }\n } \n \n else {\n // If Alice doesn\'t have sufficient water, she refills.\n if (aliceCan < plants[i]) {\n aliceCan = capacityA;\n ++totalFills;\n }\n \n // Alice waters.\n aliceCan -= plants[i];\n ++i;\n \n // If Bob doesn\'t have sufficient water, he refills.\n if (bobCan < plants[j]) {\n bobCan = capacityB; \n ++totalFills;\n }\n \n // Bob waters.\n bobCan -= plants[j];\n --j;\n }\n }\n return totalFills;\n }\n};\n``` | 9 | 0 | ['Dynamic Programming', 'C', 'C++'] | 0 |
watering-plants-ii | C++ Two Pointers | c-two-pointers-by-lzl124631x-pmyy | See my latest update in repo LeetCode\n## Solution 1. Two Pointers\n\ncpp\n// OJ: https://leetcode.com/contest/weekly-contest-271/problems/watering-plants-ii/\n | lzl124631x | NORMAL | 2021-12-12T04:01:16.168236+00:00 | 2021-12-12T04:17:57.509404+00:00 | 899 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n## Solution 1. Two Pointers\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-271/problems/watering-plants-ii/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n int minimumRefill(vector<int>& A, int ca, int cb) {\n int N = A.size(), i = 0, j = N - 1, ans = 0, a = ca, b = cb; // i/j is the position of Alice/Bob. a/b is the water of Alice/Bob\n while (i <= j) {\n if (i == j) { // If Alice and Bob are at the same spot\n if (a >= b) ans += a < A[i++];\n else ans += b < A[j--];\n } else {\n if (a < A[i]) a = ca, ++ans;\n a -= A[i++];\n if (b < A[j]) b = cb, ++ans;\n b -= A[j--];\n }\n }\n return ans;\n }\n};\n``` | 8 | 3 | [] | 1 |
watering-plants-ii | [JAVA/C++] Easy solution explained with comments | javac-easy-solution-explained-with-comme-ezft | JAVA:\n\n\'\'\'class Solution {\n\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n\t\n\t\t//number of refills\n int re = 0;\ | hetvigarg | NORMAL | 2021-12-12T04:06:19.408738+00:00 | 2021-12-12T05:14:10.660512+00:00 | 673 | false | **JAVA:**\n\n\'\'\'class Solution {\n\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n\t\n\t\t//number of refills\n int re = 0;\n \n int a = capacityA, b = capacityB;\n int n = plants.length;\n \n\t\tif(n==1) return 0;\n\t\t\n int j=n-1;\n for (int i = 0; i < n; ++i) {\n \n //if they are at the same plant\n if(i==j){\n \n //if both have equal water or alice has more water\n if(a>=b){\n if (a < plants[i]) {\n a = capacityA;\n re++;\n break;\n }\n }\n \n //if bob has more water\n else if(b>a){\n if(b < plants[j]){\n b = capacityB;\n re++;\n break;\n }\n }\n \n //we have watered all plants\n break;\n }\n \n //if less water in alice\'s can than required refill it\n if (a < plants[i]) {\n a = capacityA;\n re++;\n }\n \n //if less water in bob\'s can than required refill it\n if(b < plants[j]){\n b = capacityB;\n re++;\n }\n \n //reduce water in can which is poured\n a -= plants[i];\n b -= plants[j];\n \n j--;\n \n //in even number of plants, all are watered here\n if(i==j)\n break;\n }\n return re;\n }\n}\n\n\n\n**C++:**\n\nclass Solution {\npublic:\n\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n //number of refills\n int re = 0;\n \n int a = capacityA, b = capacityB;\n int n = plants.size();\n \n if(n==1) return 0;\n \n int j=n-1;\n for (int i = 0; i < n; ++i) {\n \n //if they are at the same plant\n if(i==j){\n \n //if both have equal water or alice has more water\n if(a>=b){\n if (a < plants[i]) {\n a = capacityA;\n re++;\n break;\n }\n }\n \n //if bob has more water\n else if(b>a){\n if(b < plants[j]){\n b = capacityB;\n re++;\n break;\n }\n }\n \n //we have watered all plants\n break;\n }\n \n //if less water in alice\'s can than required refill it\n if (a < plants[i]) {\n a = capacityA;\n re++;\n }\n \n //if less water in bob\'s can than required refill it\n if(b < plants[j]){\n b = capacityB;\n re++;\n }\n \n //reduce water in can which is poured\n a -= plants[i];\n b -= plants[j];\n \n j--;\n \n //in even number of plants, all are watered here\n if(i==j)\n break;\n }\n return re;\n }\n}; | 6 | 0 | ['Two Pointers', 'C', 'Java'] | 1 |
watering-plants-ii | c++ solution | c-solution-by-manishya1669-7j53 | smjh\n\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int i=0;\n int j=plants.size()-1;\n int a=capacityA;\n | manishya1669 | NORMAL | 2022-01-05T07:22:51.941471+00:00 | 2022-01-05T07:22:51.941513+00:00 | 307 | false | smjh\n```\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int i=0;\n int j=plants.size()-1;\n int a=capacityA;\n int b=capacityB;\n int ans=0;\n while(i<j){\n if(plants[i]<=a){\n a-=plants[i];\n \n }\n else{\n a=capacityA;\n ans++;\n a-=plants[i];\n }\n if(plants[j]<=b){\n b-=plants[j];\n \n }\n else{\n b=capacityB;\n ans++;\n b-=plants[j];\n }\n i++;\n j--;\n \n }\n if(i==j){\n int mx=max(a,b);\n if(mx<plants[i]){\n ans++;\n }\n }\n return ans;\n }\n```\nDo upvote | 4 | 0 | ['C'] | 0 |
watering-plants-ii | JAVA || Very Easy to Understand | java-very-easy-to-understand-by-kannan_2-o9n2 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTwo Pointer\n\n# Complexity\n- Time complexity:\nO(log n)\n\n- Space comp | kannan_27 | NORMAL | 2023-05-14T01:35:54.725940+00:00 | 2023-05-14T01:35:54.725970+00:00 | 252 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTwo Pointer\n\n# Complexity\n- Time complexity:\nO(log n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int minimumRefill(int[] p,int A, int B) {\n int n=p.length;\n int x=A,y=B;\n int i=0,j=n-1,c=0;\n while(i<j){\n if(x<p[i]){\n c++;\n x=A;\n }\n if(y<p[j]){\n c++;\n y=B;\n }\n x=x-p[i];\n y=y-p[j];\n i++;\n j--;\n }\n if(i==j && n%2!=0){\n if(Math.max(x,y)<p[i])\n c++;\n }\n return c;\n }\n}\n``` | 2 | 0 | ['Two Pointers', 'Java'] | 1 |
watering-plants-ii | C++ || Two Pointer || O(N) | c-two-pointer-on-by-neeraj_jm-9zhi | ```\nclass Solution {\npublic:\n int minimumRefill(vector& plants, int capacityA, int capacityB) {\n int i = 0;\n int j = plants.size() - 1;\n | neeraj_jm | NORMAL | 2022-10-24T07:23:37.327700+00:00 | 2022-10-24T07:23:37.327724+00:00 | 526 | false | ```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int i = 0;\n int j = plants.size() - 1;\n int tot_refill = 0;\n int capA = capacityA;\n int capB = capacityB;\n while(i<j){\n \n if(plants[i]<=capacityA)\n {\n capacityA-=plants[i];\n i++;\n }\n else{\n tot_refill++;\n capacityA = capA-plants[i];\n i++;\n }\n if(plants[j]<=capacityB)\n {\n capacityB-=plants[j];\n j--;\n }\n else{\n tot_refill++;\n capacityB = capB-plants[j];\n j--;\n }\n }\n if(i==j){\n if(capacityA<plants[i] && capacityB<plants[i])\n tot_refill++;\n }\n return tot_refill;\n }\n};\n | 2 | 0 | ['Two Pointers', 'C', 'C++'] | 0 |
watering-plants-ii | java solution 5ms || simple and easy | java-solution-5ms-simple-and-easy-by-sis-g4d2 | //please upvote if you like my approach\n\nclass Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n int count=0;\n | Sisvanth | NORMAL | 2022-01-25T12:43:22.747855+00:00 | 2022-01-25T12:43:22.747886+00:00 | 282 | false | **//please upvote if you like my approach**\n```\nclass Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n int count=0;\n int c1=capacityA,c2=capacityB;\n for(int start=0,end=plants.length-1;start<=plants.length/2&&end>=plants.length/2;start++,end--){\n if(start==end||start>end)break;\n if(c1>=plants[start]){\n c1-=plants[start];\n }\n else{\n count++;\n c1=capacityA;\n c1-=plants[start];\n }\n if(c2>=plants[end]){\n c2-=plants[end];\n }\n else{\n count++;\n c2=capacityB;\n c2-=plants[end];\n }\n }\n if((c1>c2||c1==c2)&&plants.length%2!=0){\n if(plants[plants.length/2]>c1)count++;\n }\n else if(c1<c2&&plants.length%2!=0){\n if(plants[plants.length/2]>c2)count++;\n }\n return count;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
watering-plants-ii | ✔Simple O(N) Two-Pointer. | simple-on-two-pointer-by-sahilanower-ex8y | \nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int n=plants.size();\n int alice=0,bob=n | SahilAnower | NORMAL | 2021-12-24T17:08:41.610023+00:00 | 2021-12-24T17:08:41.610063+00:00 | 139 | false | ```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int n=plants.size();\n int alice=0,bob=n-1,temp1=capacityA,temp2=capacityB;\n int count=0;\n \n while(alice<bob){\n if(temp1<plants[alice]){\n count++;\n temp1=capacityA-plants[alice]; // refill Alice, and move forward after watering this.\n }else{\n temp1-=plants[alice];\n }\n if(temp2<plants[bob]){\n count++;\n temp2=capacityB-plants[bob]; // refill Bob, and move forward after watering this.\n }else{\n temp2-=plants[bob];\n }\n alice++,bob--;\n }\n \n if(alice==bob){\n if(max(temp1,temp2)<plants[alice]) // only in case of odd elements, both alice and bob hit same element.\n count++;\n }\n return count;\n }\n};\n``` | 2 | 0 | ['Two Pointers'] | 0 |
watering-plants-ii | (C++), easy to understand | c-easy-to-understand-by-priyanshupundhir-cm3x | \n\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) \n {\n int n=plants.size();\n int n1=capacityA;\n | PriyanshuPundhir | NORMAL | 2021-12-12T11:30:20.200835+00:00 | 2021-12-12T11:30:20.200865+00:00 | 246 | false | ```\n\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) \n {\n int n=plants.size();\n int n1=capacityA;\n int n2=capacityB;\n int i=0;\n int j=n-1;\n int count=0;\n while(i<=j)\n {\n if(i==j)\n {\n if(n1<plants[i] && n2<plants[i]) \n count++;\n }\n else \n {\n if(plants[i]<=n1)\n {\n n1=n1-plants[i];\n }\n else if(plants[i]>n1)\n {\n n1=capacityA;\n count++;\n n1=n1-plants[i];\n }\n if(plants[j]<=n2)\n {\n n2=n2-plants[j];\n }\n else if(plants[j]>n2)\n {\n n2=capacityB;\n count++;\n n2=n2-plants[j];\n }\n }\n i++;\n j--;\n }\n return count;\n }\n``` | 2 | 0 | ['Two Pointers', 'C', 'C++'] | 0 |
watering-plants-ii | C++ EASY TWO_POINTERS | c-easy-two_pointers-by-the_expandable-iui1 | ```\nclass Solution {\npublic:\n #define ll long long int \n int minimumRefill(vector& p, int ca, int cb) {\n int n = p.size();\n int i = 0 | the_expandable | NORMAL | 2021-12-12T08:35:14.445800+00:00 | 2021-12-12T08:35:14.445826+00:00 | 78 | false | ```\nclass Solution {\npublic:\n #define ll long long int \n int minimumRefill(vector<int>& p, int ca, int cb) {\n int n = p.size();\n int i = 0 ; int j = n-1;\n ll a = ca ;\n ll b = cb ; \n ll ans=0;\n while(i <= j)\n {\n //cout<<ca<<" "<<cb<<endl;\n if(i==j)\n {\n \n ca = max(ca , cb);\n if(ca >= p[i]){i++;break;}\n else\n {\n a = max(a,b);\n if(a >= p[i])\n {\n ans++; break;\n }\n ans+=ceil(p[i]/a);\n }\n \n }\n if(ca < p[i])\n {\n ans++;\n ca = a ; \n \n }\n if(cb < p[j])\n {\n ans++;\n cb = b ; \n }\n \n if(ca >= p[i])\n {\n ca-=p[i];\n i++;\n }\n if(cb >= p[j])\n {\n cb-=p[j];\n j--;\n }\n }\n return ans;\n }\n}; | 2 | 0 | [] | 0 |
watering-plants-ii | C++ || Two pointers || Easy | c-two-pointers-easy-by-rajdeep_nagar-tn9g | \nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int A, int B) {\n \n int x=A,y=B;\n int n=plants.size();\n int i=0 | Rajdeep_Nagar | NORMAL | 2021-12-12T04:23:16.038414+00:00 | 2021-12-12T04:24:53.055466+00:00 | 125 | false | ```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int A, int B) {\n \n int x=A,y=B;\n int n=plants.size();\n int i=0,j=n-1;\n int c=0;\n \n while(i<=j){\n if(i==j){\n if(A< plants[i] && B < plants[i])\n c++;\n }\n else{\n \n if(A < plants[i]){\n A=x;\n c++;\n A=A-plants[i];\n }\n else if(A>= plants[i]){\n A=A-plants[i];\n } \n if(B < plants[j]){\n B=y;\n c++;\n B=B-plants[j];\n }\n else if(B >= plants[j]){\n B=B-plants[j];\n }\n }\n i++;\n j--;\n \n }\n return c;\n }\n};\n``` | 2 | 1 | ['Two Pointers', 'C++'] | 2 |
watering-plants-ii | Just Brute Force !! | just-brute-force-by-rishabh_devbanshi-9h46 | \nint minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n typedef long long ll;\n \n ll n = size(plants);\n ll cnt | rishabh_devbanshi | NORMAL | 2021-12-12T04:22:46.544322+00:00 | 2021-12-12T04:22:46.544351+00:00 | 236 | false | ```\nint minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n typedef long long ll;\n \n ll n = size(plants);\n ll cnt = 0;\n \n ll al = 0 , bob = n-1;\n \n ll tal = capacityA , tbob = capacityB;\n \n while(al < bob)\n {\n if(tal >= plants[al])\n {\n tal -= plants[al];\n }\n else\n {\n tal = capacityA , cnt++;\n tal -= plants[al];\n }\n \n if(tbob >= plants[bob])\n {\n tbob -= plants[bob];\n }\n else\n {\n tbob = capacityB , cnt++;\n tbob -= plants[bob];\n }\n \n al++ , bob--;\n }\n \n if(al == bob)\n {\n if(tal == tbob)\n {\n if(tal >= plants[al]) tal -= plants[al];\n else cnt++;\n }\n else\n {\n ll mx = max(tal,tbob);\n if(mx >= plants[al]) mx -= plants[al];\n else cnt++;\n }\n }\n \n return cnt;\n \n }\n```\n\n**Time Complexity :** O(n)\n**Space Complexity** : O(1) | 2 | 0 | [] | 2 |
watering-plants-ii | Two Pointer Solution | two-pointer-solution-by-kartikaydhingra-gujo | \nint sum = 0;\n int alice = capacityA;\n int bob = capacityB;\n for(int i = 0, j = plants.length - 1; i <= j; i++, j--){\n if(i | kartikaydhingra | NORMAL | 2021-12-12T04:02:36.856758+00:00 | 2021-12-12T04:02:36.856796+00:00 | 144 | false | ```\nint sum = 0;\n int alice = capacityA;\n int bob = capacityB;\n for(int i = 0, j = plants.length - 1; i <= j; i++, j--){\n if(i == j){\n if(alice >= bob){\n if(alice >= plants[i]){\n alice -= plants[i];\n plants[i] = 0; \n }\n else{\n alice = capacityA;\n sum++;\n alice -= plants[i];\n plants[i] = 0;\n }\n }\n else{\n if(bob >= plants[j]){\n bob -= plants[j];\n plants[j] = 0;\n }\n else{\n bob = capacityB;\n sum++;\n bob -= plants[j];\n plants[j] = 0;\n }\n }\n break;\n }\n if(alice >= plants[i]){\n alice -= plants[i];\n plants[i] = 0; \n }\n else{\n alice = capacityA;\n sum++;\n alice -= plants[i];\n plants[i] = 0; \n }\n if(bob >= plants[j]){\n bob -= plants[j];\n plants[j] = 0;\n }\n else{\n bob = capacityB;\n sum++;\n bob -= plants[j];\n plants[j] = 0;\n }\n }\n return sum;\n }\n``` | 2 | 0 | ['Array', 'Two Pointers', 'Java'] | 0 |
watering-plants-ii | Java easy | o(n) | two pointer | java-easy-on-two-pointer-by-xavi_an-md4k | ```\nclass Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n int cA = capacityA;\n int cB = capacityB;\n | xavi_an | NORMAL | 2021-12-12T04:01:59.758141+00:00 | 2021-12-12T04:03:04.295266+00:00 | 74 | false | ```\nclass Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n int cA = capacityA;\n int cB = capacityB;\n int a=0;\n int b=plants.length-1;\n int refill = 0;\n while(a < b){\n if(cA >= plants[a]){\n cA -= plants[a];\n }else {\n refill++; //increment count when can is less than plant[i]\n cA = capacityA-plants[a];\n }\n a++;\n if(cB >= plants[b]){\n cB -= plants[b];\n }else {\n refill++; //increment count when can is less than plant[i]\n cB = capacityB-plants[b];\n }\n b--;\n }\n if(a == b){\n if(cB > cA){\n if(plants[a] > cB)\n refill++; //increment for last plant\n }else if(plants[a] > cA){\n refill++; //increment for last plant\n }\n }\n return refill;\n }\n} | 2 | 1 | [] | 0 |
watering-plants-ii | C++ | two pointer | with explanation | c-two-pointer-with-explanation-by-aman28-qclq | Explanation:-\n1. This is a two pointer problem \n2. Start watering the plants as said from both the ends ,when there is insufficient water then refill the can. | aman282571 | NORMAL | 2021-12-12T04:00:51.872480+00:00 | 2021-12-12T04:00:51.872514+00:00 | 211 | false | **Explanation:-**\n1. This is a **two pointer problem** \n2. Start watering the plants as said from both the ends ,when there is ```insufficient water then refill the can```.\n3. If we have even number of plants then ```alice and bob will water equal number of plants(n/2)```.\n4. If we have odd number of plants then for middle plant check if either of them can water it, if not then just ```increase the answer (we only care about refilling, we don\'t care who will water the plant)```\n\n**Time Complexity:-** O(n)\n**Space Complexity:-** O(1)\n\n```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& p, int ca, int cb) {\n int l=0,r=p.size()-1,a=ca,b=cb,ans=0;\n while(l<r){\n // insufficient water the refill\n if(ca<p[l]){\n ca=a;\n ans++;\n } \n if(cb<p[r]){\n cb=b;\n ans++;\n }\n ca-=p[l]; \n cb-=p[r];\n l++;r--;\n }\n // only happen when we have odd number of plants\n if(l==r)\n if(max(ca,cb)<p[l]) // deciding if either of them have to refill the container\n ans++;\n return ans; \n }\n};\n```\nDo **UPVOTE** if it helps :)\n | 2 | 1 | ['C'] | 0 |
watering-plants-ii | Functions ka sahi istemaal koi iss solution se sekhai :))) #best solution so far | functions-ka-sahi-istemaal-koi-iss-solut-9x3g | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Mohd-Arish-Khan | NORMAL | 2025-03-27T17:40:22.921303+00:00 | 2025-03-27T17:40:22.921303+00:00 | 18 | 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
```cpp []
class Solution {
public:
void refill(int &capacity,int maxcap, int &count) {
capacity = maxcap;
count++;
}
int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {
int left = 0;
int right = plants.size()-1;
int count =0;
int cap = capacityA;
int cap2 = capacityB;
while(left<right){
if(capacityA<plants[left]){
refill(capacityA,cap,count);
}
if(capacityB<plants[right]){
refill(capacityB,cap2,count);
}
capacityA -= plants[left];
capacityB -= plants[right];
left++;
right--;
}
if (left == right) {
if (capacityA >= capacityB) {
if (capacityA < plants[left]) {
refill(capacityA, cap, count);
}
capacityA -= plants[left];
} else {
if (capacityB < plants[left]) {
refill(capacityB, cap2, count);
}
capacityB -= plants[left];
}
}
return count;
}
};
``` | 1 | 0 | ['C++'] | 1 |
watering-plants-ii | two pointers | two-pointers-by-alokitkapoor-hr6g | Intuitionimulate Alice watering from the left and Bob from the right, refilling when needed, and handle the middle plant separately if they meet.ApproachTwo Poi | Alokitkapoor | NORMAL | 2025-02-27T14:26:30.186668+00:00 | 2025-02-27T14:26:30.186668+00:00 | 50 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
imulate Alice watering from the left and Bob from the right, refilling when needed, and handle the middle plant separately if they meet.
# Approach
<!-- Describe your approach to solving the problem. -->
Two Pointers: Use al (Alice) starting from the left and bob (Bob) from the right.
Simulate Watering: Each waters their respective plant if they have enough capacity; otherwise, they refill and increment the refill count.
Handle Middle Plant: If both reach the same plant, check if neither has enough water; if so, increment the refill count.
Update Capacity: Deduct water used for each plant and reset it to the original when refilling.
Continue Until Done: Move pointers inward until all plants are watered.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1)
# Code
```cpp []
class Solution {
public:
int minimumRefill(vector<int>& plants, int ca, int cb) {
int len = plants.size();
int times = 0;
int al = 0;
int bob = len -1;
int oca = ca;
int ocb = cb;
while( al <= bob){
// edge case when they are on the same plant
if(al == bob){
// if both did not have enough water then increase times by one
if( ca < plants[al] && cb < plants[al]){
times++;
}
break;
}
if(plants[al] <= ca){
ca = ca - plants[al];
al++;
}
else{
times++;
ca = oca;
ca = ca - plants[al];
al++;
}
if(plants[bob] <= cb){
cb = cb - plants[bob];
bob--;
}
else{
times++;
cb = ocb;
cb = cb - plants[bob];
bob--;
}
}
return times;
}
};
``` | 1 | 0 | ['C++'] | 1 |
watering-plants-ii | C++ || Beats 61% || 2 pointer | c-beats-61-2-pointer-by-manral_0203-156e | 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 | Manral_0203 | NORMAL | 2024-08-05T16:08:12.953954+00:00 | 2024-08-05T16:12:44.517457+00:00 | 34 | 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 Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int refil=0,Bob=capacityB,Alice=capacityA;\n for(int i=0,j=plants.size()-1;i<=j;i++,j--){\n if(i==j){\n int ma=max(capacityA,capacityB);\n if(ma<plants[i]){\n refil++;\n }\n }else{\n if(capacityA<plants[i]){\n refil++;\n capacityA=Alice;\n }\n if(capacityB<plants[j]){\n refil++;\n capacityB=Bob;\n }\n capacityA-=plants[i];\n capacityB-=plants[j];\n\n }\n }\n return refil;\n }\n};\n``` | 1 | 0 | ['Array', 'Two Pointers', 'Simulation', 'C++'] | 0 |
watering-plants-ii | Easy C++ solution | easy-c-solution-by-nehagupta_09-epnz | \n\n# Code\n\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int capA=capacityA;\n int ca | NehaGupta_09 | NORMAL | 2024-07-07T12:44:15.032812+00:00 | 2024-07-07T12:44:15.032834+00:00 | 27 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int capA=capacityA;\n int capB=capacityB;\n int alice=0;\n int bob=plants.size()-1;\n int ans=0;\n while(alice<bob)\n {\n if(plants[alice]<=capA)\n {\n capA-=plants[alice];\n alice++;\n }\n else \n {\n capA=capacityA-plants[alice];\n alice++;\n ans++;\n }\n if(capB>=plants[bob])\n {\n capB-=plants[bob];\n bob--;\n }\n else\n {\n capB=capacityB-plants[bob];\n bob--;\n ans++;\n }\n }\n if(alice==bob and plants[alice]>capA and plants[alice]>capB)\n ans++;\n return ans;\n }\n};\n``` | 1 | 0 | ['Array', 'Two Pointers', 'Simulation', 'C++'] | 0 |
watering-plants-ii | EASY AND BASIC SOLUTION ✅✅ | easy-and-basic-solution-by-coder_96677-jfsa | \n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int cap | Coder_96677 | NORMAL | 2023-08-25T11:23:07.607765+00:00 | 2023-08-25T11:23:07.607782+00:00 | 374 | false | \n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int n = plants.size();\n int count =0;\n int start =0;\n int end =n-1;\n int aliceCC = capacityA;\n int bobCC = capacityB;\n while(start<=end){\n \n if(start==end){\n if(aliceCC>=bobCC){\n if(aliceCC>=plants[start]){\n aliceCC-=plants[start];\n }\n else{\n aliceCC=capacityA;\n count+=1;\n }\n }\n else{\n if(bobCC>=plants[end]){\n bobCC-=plants[end];\n }\n else{\n bobCC=capacityB;\n count+=1;\n }\n }\n break;\n }\n if(aliceCC>=plants[start]){\n aliceCC-=plants[start];\n }\n else{\n aliceCC=capacityA;\n aliceCC-=plants[start];\n count+=1;\n }\n if(bobCC>=plants[end]){\n bobCC-=plants[end];\n }\n else{\n bobCC=capacityB;\n bobCC-=plants[end];\n count+=1;\n }\n\n\n start++;\n end--;\n }\n return count; \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
watering-plants-ii | Two pointer approach | two-pointer-approach-by-teenuburi-x7wo | \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\n func minimumRefill(_ plants: [Int], _ capacityA: Int, | teenuburi | NORMAL | 2023-08-25T08:45:26.702494+00:00 | 2023-08-25T08:45:26.702517+00:00 | 160 | false | \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n func minimumRefill(_ plants: [Int], _ capacityA: Int, _ capacityB: Int) -> Int {\n var ans = 0\n var i = 0\n var aliceWater = capacityA\n var bobWater = capacityB\n var j = plants.count-1\n \n while i < j {\n if plants[i] > aliceWater {\n ans += 1\n aliceWater = capacityA\n }\n \n if plants[j] > bobWater {\n ans += 1\n bobWater = capacityB\n }\n aliceWater -= plants[i]\n bobWater -= plants[j]\n i += 1\n j -= 1\n }\n if plants[j] > bobWater && plants[i] > aliceWater && i == j {\n ans += 1\n bobWater = capacityB\n }\n return ans\n }\n}\n``` | 1 | 0 | ['Swift'] | 0 |
watering-plants-ii | 🔥🔥🔥C++ | super easy | clean code | two pointers | beats 100% runtime🔥🔥🔥 | c-super-easy-clean-code-two-pointers-bea-drbl | 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 | Algo-Messihas | NORMAL | 2023-08-16T16:52:16.483026+00:00 | 2023-08-16T16:57:14.657671+00:00 | 58 | 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 Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n \n int n = plants.size();\n int i = 0;\n int j = n-1;\n int capA = capacityA;\n int capB = capacityB;\n int cnt = 0;\n while(i < j){\n capA -= plants[i];\n capB -= plants[j];\n\n if(capA < 0){\n cnt++;\n capA = capacityA - plants[i];\n } \n if(capB < 0){\n capB = capacityB - plants[j];\n cnt++;\n }\n\n i++;\n j--;\n }\n\n if(i == j){\n capA = max(capA,capB);\n if(capA < plants[i]) cnt++;\n }\n return cnt;\n }\n};\n``` | 1 | 0 | ['Array', 'Two Pointers', 'Simulation', 'C++'] | 0 |
watering-plants-ii | Recursion Solution || Java || Easy to Understand | recursion-solution-java-easy-to-understa-oihe | \n# Approach\n\n---\n> Two Pointers + Recursion\n\n- Two pointers denoting respective positions of Alice and Bob.\n\n- Whenever they run out of water, their can | virendras996 | NORMAL | 2023-07-12T15:56:30.902029+00:00 | 2023-07-12T15:57:07.897551+00:00 | 9 | false | \n# Approach\n\n---\n> Two Pointers + Recursion\n\n- Two pointers denoting respective positions of Alice and Bob.\n\n- Whenever they run out of water, their cans are refilled with the original water capacity.\n\n- Refilling is being tracked and stored in **count**.\n\n---\n\n\n\n\n# Code\n```\nclass Solution {\n\n public static int count;\n public static int cAfull;\n public static int cBfull;\n\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n\n count = 0;\n cAfull = capacityA;\n cBfull = capacityB;\n\n helper(plants, capacityA, capacityB, 0, plants.length-1);\n\n return count;\n \n }\n\n public static void helper(int plants[], int cA, int cB, int i, int j){\n\n// Base Condition\n\n if(i > j){\n return;\n }\n\n// If both of them reach at a single plant position.\n\n if(i == j){\n if(cA >= cB && cA < plants[i] || cA < cB && cB < plants[j]){\n count++;\n }\n return;\n }\n\n// Checking Alice capacity\n\n if(plants[i] > cA){\n count++;\n cA = cAfull;\n }\n\n//Checking Bob capacity\n\n if(plants[j] > cB){\n count++;\n cB = cBfull;\n }\n\n cB -= plants[j];\n cA -= plants[i];\n\n helper(plants, cA, cB, i+1, j-1);\n }\n}\n``` | 1 | 0 | ['Two Pointers', 'Recursion', 'Java'] | 0 |
watering-plants-ii | Straightforward C++ solution || Clean and simple code || O(N) time complexity | straightforward-c-solution-clean-and-sim-9qjg | Code\n\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int n = plants.size(), i = 0, j = n-1, A | prathams29 | NORMAL | 2023-07-02T04:21:01.051052+00:00 | 2023-07-02T04:23:01.802612+00:00 | 191 | false | # Code\n```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int n = plants.size(), i = 0, j = n-1, A = capacityA, B = capacityB, count = 0;\n while(i<=j)\n {\n if(A>=plants[i]) \n A -= plants[i++];\n else{ \n A = capacityA;\n count++;\n A -= plants[i++];\n }\n if(B>=plants[j])\n B -= plants[j--];\n else{\n B = capacityB;\n count++;\n B -= plants[j--];\n }\n if(i==j)\n {\n if(A>=B){\n if(A>=plants[i]) A -= plants[i++];\n else{\n A = capacityA;\n count++;\n A -= plants[i++];\n }\n }\n else{\n if(B>=plants[j]) B -= plants[j--];\n else{\n B = capacityB;\n count++;\n B -= plants[j--];\n }\n } \n }\n }\n return count;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
watering-plants-ii | Simple C++ Solution || 2 Pointer Approach || Time - O(N) || Space - O(1) | simple-c-solution-2-pointer-approach-tim-8qsu | 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 | astro-here | NORMAL | 2023-05-12T06:54:00.190378+00:00 | 2023-05-12T06:54:00.190418+00:00 | 28 | 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 O(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int waterA = capacityA, waterB = capacityB, s = 0, e = plants.size() - 1, count = 0;\n while(s<e)\n {\n if(waterA < plants[s])\n {\n waterA = capacityA;\n count++;\n }\n waterA -= plants[s++];\n if(waterB < plants[e])\n {\n waterB = capacityB;\n count++;\n }\n waterB -= plants[e--];\n } \n if(s==e)\n {\n int maxWater =0;\n if(waterA >= waterB) maxWater = waterA;\n else maxWater = waterB;\n if(maxWater < plants[s]) count++;\n } \n return count;\n }\n};\n``` | 1 | 0 | ['Array', 'Two Pointers', 'Simulation', 'C++'] | 0 |
watering-plants-ii | Easy & Simple Solution | C++ | easy-simple-solution-c-by-shekhar_k_s-jnky | 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 | Shekhar_k_s | NORMAL | 2023-02-21T04:48:54.925341+00:00 | 2023-02-21T04:48:54.925376+00:00 | 282 | 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:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {\n int n=plants.size();\n int cnt=0;\n int start=0;\n int end=n-1;\n int a=capacityA;\n int b=capacityB;\n while(1)\n {\n if(end<start)\n break;\n if(end==start)\n {\n if(a<plants[start] && b<plants[end])\n cnt++;\n break;\n }\n if(plants[start]>a)\n {\n cnt++;\n a=capacityA-plants[start];\n }else if(plants[start]<=a)\n {\n a-=plants[start];\n }\n if(plants[end]>b)\n {\n cnt++;\n b=capacityB-plants[end];\n }else if(plants[end]<=b)\n {\n b-=plants[end];\n }\n start++;\n end--;\n }\n return cnt;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
watering-plants-ii | Two pointer Approach | two-pointer-approach-by-nikhil240808-m9aj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nif plants.length i.e n is even they do not meet they will crossover each | nikhil240808 | NORMAL | 2023-01-23T15:48:16.490843+00:00 | 2023-01-23T15:48:16.490898+00:00 | 320 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nif plants.length i.e n is even they do not meet they will crossover each other otherwise they will meet at the middle which is last iteration check if any one of them has sufficient water then continue otherwise increment refill++\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n //TimeComplexity-O(N) spaceComplexity-O(1)\n int n=plants.length;\n int fulla=capacityA;\n int fullb=capacityB;\n int start=0;\n int end=n-1;\n int refill=0;\n while(start<=end){\n if(start==end){\n if(capacityA<plants[start] && capacityB<plants[start]){\n refill++;\n }\n }\n else{\n if(capacityA>=plants[start]){\n capacityA=capacityA-plants[start];\n }else{\n capacityA=fulla;\n capacityA=capacityA-plants[start];\n refill++;\n }\n if(capacityB>=plants[end]){\n capacityB=capacityB-plants[end];\n }else{\n capacityB=fullb;\n capacityB=capacityB-plants[end];\n refill++;\n }\n }\n start++;\n end--;\n }\n return refill;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
watering-plants-ii | Python Two Pointers | python-two-pointers-by-shtanriverdi-vd2s | \nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n n = len(plants)\n \n alice = 0\ | shtanriverdi | NORMAL | 2022-11-25T14:16:55.809572+00:00 | 2022-11-25T14:16:55.809607+00:00 | 63 | false | ```\nclass Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n n = len(plants)\n \n alice = 0\n bob = n - 1\n \n alicesCan = capacityA\n bobsCan = capacityB\n \n answer = 0 \n while alice < bob:\n # Alice\n if alicesCan >= plants[alice]:\n alicesCan -= plants[alice]\n else:\n alicesCan = capacityA - plants[alice]\n answer += 1\n # Bob\n if bobsCan >= plants[bob]:\n bobsCan -= plants[bob]\n else:\n bobsCan = capacityB - plants[bob]\n answer += 1\n alice += 1\n bob -= 1\n \n if n % 2 == 1:\n # Alice\n if max(alicesCan, bobsCan) < plants[alice]:\n answer += 1\n \n return answer\n``` | 1 | 0 | ['Two Pointers', 'Python'] | 0 |
watering-plants-ii | Very Simple Java Solution | very-simple-java-solution-by-sanyamjain7-40xb | \nclass Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n int n = plants.length, ai = 0, bi = n - 1, ac = capacity | Sanyamjain77 | NORMAL | 2022-09-23T18:23:34.024890+00:00 | 2022-09-23T18:23:34.024929+00:00 | 281 | false | ```\nclass Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n int n = plants.length, ai = 0, bi = n - 1, ac = capacityA, bc = capacityB, c = 0;\n // ai is alice\'s current index and bi for bob. Same for capacity\n\t\t\n while(ai < bi){\n\t\t\t// If there is not enough water in the can, then refill it and increment the count\n if(ac < plants[ai]){ ac = capacityA; c++; }\n ac -= plants[ai++];\n \n if(bc < plants[bi]){ bc = capacityB; c++; }\n bc -= plants[bi--];\n }\n\t\t\n // If alice and bob are on the same plant and both don\'t have sufficient water in their cans.\n\t\t// Then increment the count because one will have to refill.\n\t\t\n if(ai == bi && ac < plants[ai] && bc < plants[bi]) c++;\n \n return c;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
watering-plants-ii | C++||Two Pointers||Easy to Understand | ctwo-pointerseasy-to-understand-by-retur-1moa | ```\nclass Solution {\npublic:\n int minimumRefill(vector& plants, int capacityA, int capacityB) \n {\n int i = 0, j = plants.size() - 1, canA = ca | return_7 | NORMAL | 2022-09-03T14:21:25.380615+00:00 | 2022-09-03T14:21:25.380645+00:00 | 190 | false | ```\nclass Solution {\npublic:\n int minimumRefill(vector<int>& plants, int capacityA, int capacityB) \n {\n int i = 0, j = plants.size() - 1, canA = capacityA, canB = capacityB, res = 0;\n while (i < j) {\n res += (canA < plants[i]) + (canB < plants[j]);\n canA = canA < plants[i] ? capacityA : canA;\n canB = canB < plants[j] ? capacityB : canB;\n canA -= plants[i++];\n canB -= plants[j--];\n }\n return res + (i == j && max(canA, canB) < plants[i]);\n }\n\n};\n//if you like the solution plz upvote. | 1 | 0 | ['Two Pointers', 'C'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.