title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Depth-First Search✅ | O( n^2)✅ | Python(Step by step explanation)✅
subtree-of-another-tree
0
1
# Intuition\nThe problem is to determine if one binary tree (subRoot) is a subtree of another binary tree (root). A subtree of a tree T is a tree consisting of a node in T and all of its descendants. The intuition is to perform a recursive comparison for each node in the root tree. If any subtree of the root tree matches the structure and values of the subRoot tree, then subRoot is considered a subtree of the root.\n\n# Approach\nThe approach is to implement two functions: `isSubtree` and `same`. \n\n1. `isSubtree(root, subRoot)`:\n - If `subRoot` is `None`, return `True` since an empty tree is always a subtree.\n - If `root` is `None`, return `False` since an empty tree cannot have a subtree.\n - If the current node in the `root` tree matches the structure and values of the `subRoot` tree (using the `same` function), return `True`.\n - Recursively call `isSubtree` on the left and right subtrees of the `root` tree.\n - If any of the recursive calls returns `True`, then `subRoot` is a subtree, and the function returns `True`.\n\n2. `same(r, s)`:\n - If both `r` and `s` are `None`, return `True` since two empty trees are the same.\n - If either `r` or `s` is `None` (but not both), return `False` since one tree is non-empty, and the other is empty.\n - If the values of the current nodes in `r` and `s` are equal:\n - Recursively call `same` on the left subtrees of `r` and `s`.\n - Recursively call `same` on the right subtrees of `r` and `s`.\n - If both recursive calls return `True`, then the subtrees rooted at `r` and `s` are the same.\n\n# Complexity\n- Time complexity: O(n * m)\n - `n` is the number of nodes in the `root` tree.\n - `m` is the number of nodes in the `subRoot` tree.\n - In the worst case, the algorithm may need to compare each node in the `root` tree with the entire `subRoot` tree.\n- Space complexity: O(h)\n - `h` is the height of the call stack during the recursive traversal.\n - In the worst case, when the trees are skewed (completely unbalanced), the space complexity is O(n).\n - In the best case, when the trees are perfectly balanced, the space complexity is O(log(n)).\n\n```python\nclass Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n if subRoot == None :\n return True\n\n if root == None :\n return False\n\n if self.same(root , subRoot):\n return True\n return self.isSubtree(root.left , subRoot) or self.isSubtree(root.right , subRoot) \n\n def same(self , r , s):\n if r == None and s == None :\n return True\n\n if r and s and r.val == s.val:\n return self.same(r.right , s.right) and self.same(r.left , s.left) \n\n return False\n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/0161dd3b-ad9f-4cf6-8c43-49c2e670cc21_1699210823.334661.jpeg)\n
9
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Depth-First Search✅ | O( n^2)✅ | Python(Step by step explanation)✅
subtree-of-another-tree
0
1
# Intuition\nThe problem is to determine if one binary tree (subRoot) is a subtree of another binary tree (root). A subtree of a tree T is a tree consisting of a node in T and all of its descendants. The intuition is to perform a recursive comparison for each node in the root tree. If any subtree of the root tree matches the structure and values of the subRoot tree, then subRoot is considered a subtree of the root.\n\n# Approach\nThe approach is to implement two functions: `isSubtree` and `same`. \n\n1. `isSubtree(root, subRoot)`:\n - If `subRoot` is `None`, return `True` since an empty tree is always a subtree.\n - If `root` is `None`, return `False` since an empty tree cannot have a subtree.\n - If the current node in the `root` tree matches the structure and values of the `subRoot` tree (using the `same` function), return `True`.\n - Recursively call `isSubtree` on the left and right subtrees of the `root` tree.\n - If any of the recursive calls returns `True`, then `subRoot` is a subtree, and the function returns `True`.\n\n2. `same(r, s)`:\n - If both `r` and `s` are `None`, return `True` since two empty trees are the same.\n - If either `r` or `s` is `None` (but not both), return `False` since one tree is non-empty, and the other is empty.\n - If the values of the current nodes in `r` and `s` are equal:\n - Recursively call `same` on the left subtrees of `r` and `s`.\n - Recursively call `same` on the right subtrees of `r` and `s`.\n - If both recursive calls return `True`, then the subtrees rooted at `r` and `s` are the same.\n\n# Complexity\n- Time complexity: O(n * m)\n - `n` is the number of nodes in the `root` tree.\n - `m` is the number of nodes in the `subRoot` tree.\n - In the worst case, the algorithm may need to compare each node in the `root` tree with the entire `subRoot` tree.\n- Space complexity: O(h)\n - `h` is the height of the call stack during the recursive traversal.\n - In the worst case, when the trees are skewed (completely unbalanced), the space complexity is O(n).\n - In the best case, when the trees are perfectly balanced, the space complexity is O(log(n)).\n\n```python\nclass Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n if subRoot == None :\n return True\n\n if root == None :\n return False\n\n if self.same(root , subRoot):\n return True\n return self.isSubtree(root.left , subRoot) or self.isSubtree(root.right , subRoot) \n\n def same(self , r , s):\n if r == None and s == None :\n return True\n\n if r and s and r.val == s.val:\n return self.same(r.right , s.right) and self.same(r.left , s.left) \n\n return False\n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg](https://assets.leetcode.com/users/images/0161dd3b-ad9f-4cf6-8c43-49c2e670cc21_1699210823.334661.jpeg)\n
9
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Unique O(|s| + |t|) solution using Eytzinger layout
subtree-of-another-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe base idea is to encode whether left or right matches a part of the subtree by storing the Eytzinger value of that node.\nWe can then check if we would match an even bigger part of the subtree by including the current node. To check if this is valid,\nWe check if there is any way in which we can match up eytzinger values of the left child and right child, and if the expected parent of both left and right child have the same node value as the current node. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$(O(|s| + |t|))$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$(O(|s| + |t|))$$\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\n\nfrom collections import defaultdict\nclass Solution:\n\n # Computes eytzinger values of leaves and intializes parent pointers for each node.\n def compute_eytzinger_and_parents(self, node, node_to_parent_dict, eytzinger_dict):\n q = [(None, 1, node)]\n while len(q) > 0:\n parent, eytzinger, curr = q.pop()\n node_to_parent_dict[curr] = parent\n if curr.left:\n q.append((curr, eytzinger * 2, curr.left))\n if curr.right:\n q.append((curr, eytzinger*2 + 1, curr.right))\n if (curr.left is None) and (curr.right is None):\n eytzinger_dict[curr.val].append((eytzinger, curr))\n \n def compute_node_heights(self, curr, height_map, height = 0):\n height_map[height].append(curr)\n max_height = height\n if curr.left:\n max_height = max(max_height, self.compute_node_heights(curr.left, height_map, height + 1))\n if curr.right:\n max_height = max(max_height, self.compute_node_heights(curr.right, height_map, height + 1))\n return max_height\n\n\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n # Stores pointers from nodes in subRoot to their parents.\n subRoot_to_parent = dict()\n # Stores for each node value of leaves in subRoot its eytzinger value and the corresponding TreeNode.\n eytzinger_of_subroot = defaultdict(list)\n self.compute_eytzinger_and_parents(subRoot, subRoot_to_parent, eytzinger_of_subroot)\n # For each height of the tree from the root, stores all nodes on that height.\n by_height = defaultdict(list)\n max_height = self.compute_node_heights(root, by_height)\n \n # For each node, contains the matching eytzinger values in the subroot and the parent value of the node in the subroot.\n partial_subtree_matches = defaultdict(lambda: dict())\n while max_height >= 0:\n curr_nodes = by_height[max_height]\n # check if current leaves match leaves of subtree\n for node in curr_nodes:\n if node.left is None and node.right is None:\n for eytzinger, subroot_node in eytzinger_of_subroot[node.val]:\n subroot_parent = subRoot_to_parent[subroot_node]\n # The parent of the matching node is None. We just matched with the sub-tree root.\n if subroot_parent is None:\n return True\n partial_subtree_matches[node][eytzinger] = subroot_parent\n \n # check if the children of the nodes have matching eytzinger values, and the expected parent value is the same.\n if node.left and node.right:\n left_subtree_matches = partial_subtree_matches[node.left]\n right_subtree_matches = partial_subtree_matches[node.right]\n for left_eytzinger, expected_left_parent in left_subtree_matches.items():\n expected_right_eytzinger = left_eytzinger + 1\n if expected_right_eytzinger in right_subtree_matches:\n expected_right_parent = right_subtree_matches[expected_right_eytzinger]\n if expected_left_parent.val == node.val and expected_right_parent.val == node.val:\n subroot_parent = subRoot_to_parent[expected_left_parent]\n # The parent of the matching node is None. We just matched with the sub-tree root.\n if subroot_parent is None:\n return True\n partial_subtree_matches[node][left_eytzinger // 2] = subroot_parent\n elif node.left:\n left_subtree_matches = partial_subtree_matches[node.left]\n for left_eytzinger, expected_left_parent in left_subtree_matches.items():\n if expected_left_parent.val == node.val and (expected_left_parent.right is None):\n subroot_parent = subRoot_to_parent[expected_left_parent]\n # The parent of the matching node is None. We just matched with the sub-tree root.\n if subroot_parent is None:\n return True\n partial_subtree_matches[node][left_eytzinger // 2] = subroot_parent\n elif node.right:\n right_subtree_matches = partial_subtree_matches[node.right]\n for right_eytzinger, expected_right_parent in right_subtree_matches.items():\n if expected_right_parent.val == node.val and (expected_right_parent.left is None):\n subroot_parent = subRoot_to_parent[expected_right_parent]\n # The parent of the matching node is None. We just matched with the sub-tree root.\n if subroot_parent is None:\n return True\n partial_subtree_matches[node][(right_eytzinger - 1) // 2] = subroot_parent\n\n max_height -= 1\n return False\n```
0
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Unique O(|s| + |t|) solution using Eytzinger layout
subtree-of-another-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe base idea is to encode whether left or right matches a part of the subtree by storing the Eytzinger value of that node.\nWe can then check if we would match an even bigger part of the subtree by including the current node. To check if this is valid,\nWe check if there is any way in which we can match up eytzinger values of the left child and right child, and if the expected parent of both left and right child have the same node value as the current node. \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$(O(|s| + |t|))$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$(O(|s| + |t|))$$\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\n\nfrom collections import defaultdict\nclass Solution:\n\n # Computes eytzinger values of leaves and intializes parent pointers for each node.\n def compute_eytzinger_and_parents(self, node, node_to_parent_dict, eytzinger_dict):\n q = [(None, 1, node)]\n while len(q) > 0:\n parent, eytzinger, curr = q.pop()\n node_to_parent_dict[curr] = parent\n if curr.left:\n q.append((curr, eytzinger * 2, curr.left))\n if curr.right:\n q.append((curr, eytzinger*2 + 1, curr.right))\n if (curr.left is None) and (curr.right is None):\n eytzinger_dict[curr.val].append((eytzinger, curr))\n \n def compute_node_heights(self, curr, height_map, height = 0):\n height_map[height].append(curr)\n max_height = height\n if curr.left:\n max_height = max(max_height, self.compute_node_heights(curr.left, height_map, height + 1))\n if curr.right:\n max_height = max(max_height, self.compute_node_heights(curr.right, height_map, height + 1))\n return max_height\n\n\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n # Stores pointers from nodes in subRoot to their parents.\n subRoot_to_parent = dict()\n # Stores for each node value of leaves in subRoot its eytzinger value and the corresponding TreeNode.\n eytzinger_of_subroot = defaultdict(list)\n self.compute_eytzinger_and_parents(subRoot, subRoot_to_parent, eytzinger_of_subroot)\n # For each height of the tree from the root, stores all nodes on that height.\n by_height = defaultdict(list)\n max_height = self.compute_node_heights(root, by_height)\n \n # For each node, contains the matching eytzinger values in the subroot and the parent value of the node in the subroot.\n partial_subtree_matches = defaultdict(lambda: dict())\n while max_height >= 0:\n curr_nodes = by_height[max_height]\n # check if current leaves match leaves of subtree\n for node in curr_nodes:\n if node.left is None and node.right is None:\n for eytzinger, subroot_node in eytzinger_of_subroot[node.val]:\n subroot_parent = subRoot_to_parent[subroot_node]\n # The parent of the matching node is None. We just matched with the sub-tree root.\n if subroot_parent is None:\n return True\n partial_subtree_matches[node][eytzinger] = subroot_parent\n \n # check if the children of the nodes have matching eytzinger values, and the expected parent value is the same.\n if node.left and node.right:\n left_subtree_matches = partial_subtree_matches[node.left]\n right_subtree_matches = partial_subtree_matches[node.right]\n for left_eytzinger, expected_left_parent in left_subtree_matches.items():\n expected_right_eytzinger = left_eytzinger + 1\n if expected_right_eytzinger in right_subtree_matches:\n expected_right_parent = right_subtree_matches[expected_right_eytzinger]\n if expected_left_parent.val == node.val and expected_right_parent.val == node.val:\n subroot_parent = subRoot_to_parent[expected_left_parent]\n # The parent of the matching node is None. We just matched with the sub-tree root.\n if subroot_parent is None:\n return True\n partial_subtree_matches[node][left_eytzinger // 2] = subroot_parent\n elif node.left:\n left_subtree_matches = partial_subtree_matches[node.left]\n for left_eytzinger, expected_left_parent in left_subtree_matches.items():\n if expected_left_parent.val == node.val and (expected_left_parent.right is None):\n subroot_parent = subRoot_to_parent[expected_left_parent]\n # The parent of the matching node is None. We just matched with the sub-tree root.\n if subroot_parent is None:\n return True\n partial_subtree_matches[node][left_eytzinger // 2] = subroot_parent\n elif node.right:\n right_subtree_matches = partial_subtree_matches[node.right]\n for right_eytzinger, expected_right_parent in right_subtree_matches.items():\n if expected_right_parent.val == node.val and (expected_right_parent.left is None):\n subroot_parent = subRoot_to_parent[expected_right_parent]\n # The parent of the matching node is None. We just matched with the sub-tree root.\n if subroot_parent is None:\n return True\n partial_subtree_matches[node][(right_eytzinger - 1) // 2] = subroot_parent\n\n max_height -= 1\n return False\n```
0
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Solution
subtree-of-another-tree
1
1
```C++ []\nclass Solution {\npublic:\n\tbool isSame(TreeNode* p, TreeNode* q){\n\t\tif(p == NULL || q == NULL){\n\t\t\treturn (p == q);\n\t\t} \n\t\treturn (p->val == q->val) && isSame(p->left, q->left) && isSame(p->right, q->right);\n\t}\n\tbool isSubtree(TreeNode* root, TreeNode* subRoot) {\n\t\tif(root == NULL){\n\t\t\treturn false;\n\t\t}\n\t\tif(subRoot == NULL){ \n\t\t\treturn true;\n\t\t}\n\t\tif(isSame(root, subRoot)){\n\t\t\treturn true;\n\t\t}\n\t\treturn isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);\n\t}\n};\n```\n\n```Python3 []\nclass Solution:\n def isSubtree(\n self,\n root: Optional[TreeNode],\n subRoot: Optional[TreeNode]\n ) -> bool:\n def helper(node: Optional[TreeNode], subNode: Optional[TreeNode]):\n if node is None:\n return subNode is None\n if subNode is None:\n return (helper(node.left, subRoot) or\n helper(node.right, subRoot))\n if (node.val == subNode.val and\n helper(node.left, subNode.left) and\n helper(node.right, subNode.right)):\n return True\n elif (node.val == subRoot.val and\n helper(node.left, subRoot.left) and\n helper(node.right, subRoot.right)):\n return True\n return (helper(node.left, subRoot) or\n helper(node.right, subRoot))\n\n return helper(root, subRoot)\n```\n\n```Java []\nclass Solution {\n private boolean isSubtreePresent = false;\n public boolean isSubtree(TreeNode root, TreeNode subRoot) {\n \n int leftSubtreeDepth = getDepth(subRoot.left);\n int rightSubtreeDepth = getDepth(subRoot.right);\n int treeDepth = getDepthForTree(root, subRoot, leftSubtreeDepth, rightSubtreeDepth);\n return this.isSubtreePresent;\n }\n private int getDepthForTree(TreeNode node, TreeNode subRoot, int leftSubtreeDepth, int rightSubtreeDepth){\n if (node == null){\n return 0;\n }\n int leftTreeDepth = getDepthForTree(node.left, subRoot, leftSubtreeDepth, rightSubtreeDepth);\n int rightTreeDepth = getDepthForTree(node.right, subRoot, leftSubtreeDepth, rightSubtreeDepth);\n\n if (!this.isSubtreePresent && node.val == subRoot.val && leftTreeDepth == leftSubtreeDepth && rightTreeDepth == rightSubtreeDepth){\n this.isSubtreePresent = areEqual(node, subRoot);\n }\n return 1 + Math.max(leftTreeDepth, rightTreeDepth);\n }\n private int getDepth(TreeNode node){\n if (node == null){\n return 0;\n }\n return 1 + Math.max(getDepth(node.left), getDepth(node.right));\n };\n private boolean areEqual(TreeNode parentTreeNode, TreeNode subTreeNode){\n if (parentTreeNode == null && subTreeNode == null){\n return true;\n }\n if (parentTreeNode == null || subTreeNode == null || parentTreeNode.val != subTreeNode.val){\n return false;\n }\n return areEqual(parentTreeNode.left, subTreeNode.left) && areEqual(parentTreeNode.right, subTreeNode.right);\n }\n}\n```\n
2
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Solution
subtree-of-another-tree
1
1
```C++ []\nclass Solution {\npublic:\n\tbool isSame(TreeNode* p, TreeNode* q){\n\t\tif(p == NULL || q == NULL){\n\t\t\treturn (p == q);\n\t\t} \n\t\treturn (p->val == q->val) && isSame(p->left, q->left) && isSame(p->right, q->right);\n\t}\n\tbool isSubtree(TreeNode* root, TreeNode* subRoot) {\n\t\tif(root == NULL){\n\t\t\treturn false;\n\t\t}\n\t\tif(subRoot == NULL){ \n\t\t\treturn true;\n\t\t}\n\t\tif(isSame(root, subRoot)){\n\t\t\treturn true;\n\t\t}\n\t\treturn isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot);\n\t}\n};\n```\n\n```Python3 []\nclass Solution:\n def isSubtree(\n self,\n root: Optional[TreeNode],\n subRoot: Optional[TreeNode]\n ) -> bool:\n def helper(node: Optional[TreeNode], subNode: Optional[TreeNode]):\n if node is None:\n return subNode is None\n if subNode is None:\n return (helper(node.left, subRoot) or\n helper(node.right, subRoot))\n if (node.val == subNode.val and\n helper(node.left, subNode.left) and\n helper(node.right, subNode.right)):\n return True\n elif (node.val == subRoot.val and\n helper(node.left, subRoot.left) and\n helper(node.right, subRoot.right)):\n return True\n return (helper(node.left, subRoot) or\n helper(node.right, subRoot))\n\n return helper(root, subRoot)\n```\n\n```Java []\nclass Solution {\n private boolean isSubtreePresent = false;\n public boolean isSubtree(TreeNode root, TreeNode subRoot) {\n \n int leftSubtreeDepth = getDepth(subRoot.left);\n int rightSubtreeDepth = getDepth(subRoot.right);\n int treeDepth = getDepthForTree(root, subRoot, leftSubtreeDepth, rightSubtreeDepth);\n return this.isSubtreePresent;\n }\n private int getDepthForTree(TreeNode node, TreeNode subRoot, int leftSubtreeDepth, int rightSubtreeDepth){\n if (node == null){\n return 0;\n }\n int leftTreeDepth = getDepthForTree(node.left, subRoot, leftSubtreeDepth, rightSubtreeDepth);\n int rightTreeDepth = getDepthForTree(node.right, subRoot, leftSubtreeDepth, rightSubtreeDepth);\n\n if (!this.isSubtreePresent && node.val == subRoot.val && leftTreeDepth == leftSubtreeDepth && rightTreeDepth == rightSubtreeDepth){\n this.isSubtreePresent = areEqual(node, subRoot);\n }\n return 1 + Math.max(leftTreeDepth, rightTreeDepth);\n }\n private int getDepth(TreeNode node){\n if (node == null){\n return 0;\n }\n return 1 + Math.max(getDepth(node.left), getDepth(node.right));\n };\n private boolean areEqual(TreeNode parentTreeNode, TreeNode subTreeNode){\n if (parentTreeNode == null && subTreeNode == null){\n return true;\n }\n if (parentTreeNode == null || subTreeNode == null || parentTreeNode.val != subTreeNode.val){\n return false;\n }\n return areEqual(parentTreeNode.left, subTreeNode.left) && areEqual(parentTreeNode.right, subTreeNode.right);\n }\n}\n```\n
2
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Python Easy to Understand
subtree-of-another-tree
0
1
```\nclass Solution:\n def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:\n if not s: \n return False\n if self.isSameTree(s, t): \n return True\n return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)\n\n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n if p and q:\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n return p is q\n\n
94
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Python Easy to Understand
subtree-of-another-tree
0
1
```\nclass Solution:\n def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:\n if not s: \n return False\n if self.isSameTree(s, t): \n return True\n return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)\n\n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n if p and q:\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n return p is q\n\n
94
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Python 98% speed with comments
subtree-of-another-tree
0
1
So this is just the implementation of the 1. solution in the problem.\nWe make a recursive `traverse_tree` function that will return a string representation of a tree, and then we just need to convert both trees to strings and check if tree `t` is substring of tree `s`\n```\nclass Solution:\n def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:\n string_s = self.traverse_tree(s)\n string_t = self.traverse_tree(t)\n if string_t in string_s:\n return True\n return False\n \n \n def traverse_tree(self, s):\n if s:\n return f"#{s.val} {self.traverse_tree(s.left)} {self.traverse_tree(s.right)}"\n return None\n```
58
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Python 98% speed with comments
subtree-of-another-tree
0
1
So this is just the implementation of the 1. solution in the problem.\nWe make a recursive `traverse_tree` function that will return a string representation of a tree, and then we just need to convert both trees to strings and check if tree `t` is substring of tree `s`\n```\nclass Solution:\n def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:\n string_s = self.traverse_tree(s)\n string_t = self.traverse_tree(t)\n if string_t in string_s:\n return True\n return False\n \n \n def traverse_tree(self, s):\n if s:\n return f"#{s.val} {self.traverse_tree(s.left)} {self.traverse_tree(s.right)}"\n return None\n```
58
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Python DFS + Recursive comparison [faster than 99%]
subtree-of-another-tree
0
1
* First, find all possible starting nodes, which are equal to subRoot\n\t* consider the tree: [1,1] and subRoot [1]\n\t* we would find starting nodes as two \'1\', the second one == SubRoot\n\n* for every possible starting node, compare the subtrees\n\n `def isSubtree_helper(self, root1, root2):`\n \n if root1 is None and root2 is None:\n return True\n \n if root1 is not None and root2 is not None and root1.val == root2.val:\n # check left and right\n return self.isSubtree_helper(root1.left, root2.left) and self.isSubtree_helper(root1.right, root2.right)\n else:\n return False\n \n \n \n ` def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:`\n \n if root is None:\n return subRoot is None\n \n # find subRoot in the original tree\n curr = root\n stack = [root]\n possible_starts = set()\n while stack:\n \n curr = stack.pop()\n \n if curr.val == subRoot.val:\n possible_starts.add(curr)\n \n if curr.left:\n stack.append(curr.left)\n \n if curr.right:\n stack.append(curr.right)\n \n if len(possible_starts) == 0:\n return False\n \n # check the subtree\n for start in possible_starts:\n if self.isSubtree_helper(start, subRoot):\n return True\n \n return False\n
0
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Python DFS + Recursive comparison [faster than 99%]
subtree-of-another-tree
0
1
* First, find all possible starting nodes, which are equal to subRoot\n\t* consider the tree: [1,1] and subRoot [1]\n\t* we would find starting nodes as two \'1\', the second one == SubRoot\n\n* for every possible starting node, compare the subtrees\n\n `def isSubtree_helper(self, root1, root2):`\n \n if root1 is None and root2 is None:\n return True\n \n if root1 is not None and root2 is not None and root1.val == root2.val:\n # check left and right\n return self.isSubtree_helper(root1.left, root2.left) and self.isSubtree_helper(root1.right, root2.right)\n else:\n return False\n \n \n \n ` def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:`\n \n if root is None:\n return subRoot is None\n \n # find subRoot in the original tree\n curr = root\n stack = [root]\n possible_starts = set()\n while stack:\n \n curr = stack.pop()\n \n if curr.val == subRoot.val:\n possible_starts.add(curr)\n \n if curr.left:\n stack.append(curr.left)\n \n if curr.right:\n stack.append(curr.right)\n \n if len(possible_starts) == 0:\n return False\n \n # check the subtree\n for start in possible_starts:\n if self.isSubtree_helper(start, subRoot):\n return True\n \n return False\n
0
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
572: Solution with step by step explanation
subtree-of-another-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a function checkEqual to check if two trees are equal in value and structure. The function takes two tree nodes root1 and root2 as input and returns a boolean value.\n\n2. Within the checkEqual function, check if both root1 and root2 are None. If so, return True.\n\n3. Check if either root1 or root2 is None. If so, return False.\n\n4. Check if the values of root1 and root2 are different. If so, return False.\n\n5. Recursively check if the left subtree of root1 is equal to the left subtree of root2 and if the right subtree of root1 is equal to the right subtree of root2. If either of these checks returns False, return False. Otherwise, return True.\n\n6. Define the isSubtree function that takes two tree nodes root and subRoot as input and returns a boolean value.\n\n7. Check if root is None. If so, return False.\n\n8. Check if root is equal to subRoot. If so, return True.\n\n9. Recursively check if the left subtree of root or the right subtree of root is equal to subRoot. If either of these checks returns True, return True. Otherwise, return False.\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:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n # Helper function to check if two trees are equal in value and structure\n def checkEqual(root1, root2):\n if not root1 and not root2:\n return True\n elif not root1 or not root2:\n return False\n elif root1.val != root2.val:\n return False\n else:\n return checkEqual(root1.left, root2.left) and checkEqual(root1.right, root2.right)\n \n # Traverse through the root tree and check if any subtree matches the subRoot tree\n if not root:\n return False\n elif checkEqual(root, subRoot):\n return True\n else:\n return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)\n```
5
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
572: Solution with step by step explanation
subtree-of-another-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a function checkEqual to check if two trees are equal in value and structure. The function takes two tree nodes root1 and root2 as input and returns a boolean value.\n\n2. Within the checkEqual function, check if both root1 and root2 are None. If so, return True.\n\n3. Check if either root1 or root2 is None. If so, return False.\n\n4. Check if the values of root1 and root2 are different. If so, return False.\n\n5. Recursively check if the left subtree of root1 is equal to the left subtree of root2 and if the right subtree of root1 is equal to the right subtree of root2. If either of these checks returns False, return False. Otherwise, return True.\n\n6. Define the isSubtree function that takes two tree nodes root and subRoot as input and returns a boolean value.\n\n7. Check if root is None. If so, return False.\n\n8. Check if root is equal to subRoot. If so, return True.\n\n9. Recursively check if the left subtree of root or the right subtree of root is equal to subRoot. If either of these checks returns True, return True. Otherwise, return False.\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:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n # Helper function to check if two trees are equal in value and structure\n def checkEqual(root1, root2):\n if not root1 and not root2:\n return True\n elif not root1 or not root2:\n return False\n elif root1.val != root2.val:\n return False\n else:\n return checkEqual(root1.left, root2.left) and checkEqual(root1.right, root2.right)\n \n # Traverse through the root tree and check if any subtree matches the subRoot tree\n if not root:\n return False\n elif checkEqual(root, subRoot):\n return True\n else:\n return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)\n```
5
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
🔥Python||Python3|| esay soultion to understand🔥
distribute-candies
0
1
# Approach\nMy approach was to loop over the candys, each candy I see I will add to the result counter and save it in a hashset. If we see a candy that already was seen then we skip it, else we add it. we do it until we reached n/2 candys or we got to the end of the list.\n\n# Complexity\n- Time complexity:\nO(n) becuase we went over the array once\n\n- Space complexity:\nO(n) becuase we saved at most n/2 numbers.\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n seen = {}\n i = 0\n amount_allowed = 0\n while(i<len(candyType) and amount_allowed<len(candyType)//2):\n if seen.get(candyType[i],0)==0:\n amount_allowed+=1\n seen[candyType[i]] = 1\n i+=1\n return amount_allowed\n\n\n\n```
1
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_. **Example 1:** **Input:** candyType = \[1,1,2,2,3,3\] **Output:** 3 **Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. **Example 2:** **Input:** candyType = \[1,1,2,3\] **Output:** 2 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types. **Example 3:** **Input:** candyType = \[6,6,6,6\] **Output:** 1 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. **Constraints:** * `n == candyType.length` * `2 <= n <= 104` * `n` is even. * `-105 <= candyType[i] <= 105`
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
575: Time 92.8%, Solution with step by step explanation
distribute-candies
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a set to store unique candy types.\n2. Traverse through the input array and add each candy type to the set.\n3. Find the length of the input array and divide it by 2 to get the maximum number of candies Alice can eat.\n4. Find the length of the set of unique candy types.\n5. Return the minimum between the length of the set of unique candy types and the maximum number of candies Alice can eat.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n # Use set to count the number of unique candies\n unique_candies = set(candyType)\n \n # Return the minimum between the number of unique candies and half the length of the input array\n return min(len(unique_candies), len(candyType)//2)\n\n```
5
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_. **Example 1:** **Input:** candyType = \[1,1,2,2,3,3\] **Output:** 3 **Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. **Example 2:** **Input:** candyType = \[1,1,2,3\] **Output:** 2 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types. **Example 3:** **Input:** candyType = \[6,6,6,6\] **Output:** 1 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. **Constraints:** * `n == candyType.length` * `2 <= n <= 104` * `n` is even. * `-105 <= candyType[i] <= 105`
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
Python 3-lines ✅✅✅ || Faster than 98.93% || Simple + Explained
distribute-candies
0
1
**Note:** In the tags, I put Ordered Set there but the set doesn\'t actually have any order.\n## Please \uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB\uD83D\uDC4D\uD83C\uDFFB if u like!!\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType):\n n = len(candyType) // 2 # just get the number of candies you can eat\n LEN = len(set(candyType)) # types of different candies\n return min(n, LEN) # use min() to get the max types we can get\n```\n![image.png](https://assets.leetcode.com/users/images/2214ba90-c367-4ae0-b62a-c44c309bd34e_1671929564.8890448.png)
2
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_. **Example 1:** **Input:** candyType = \[1,1,2,2,3,3\] **Output:** 3 **Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. **Example 2:** **Input:** candyType = \[1,1,2,3\] **Output:** 2 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types. **Example 3:** **Input:** candyType = \[6,6,6,6\] **Output:** 1 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. **Constraints:** * `n == candyType.length` * `2 <= n <= 104` * `n` is even. * `-105 <= candyType[i] <= 105`
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
✔Beats 100% TC || Simple if else || Easily Understandable Python Solution
distribute-candies
0
1
# Approach\n - Converts the array ```candyType``` to a set which gonna contain only discrete values\n - if ```eat <= len(dis_candyType)``` it means there are enough options available (i.e. Here every candy Alice eats is of different type)\n - elif ```eat > len(dis_candyType)``` not enough options available \n (i.e. Here Alice will have ```len(dis_candyType)``` different types of candies)\n# Complexity\n- Time complexity:\nBeats 100%\n\n# Code\n```\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n l = len(candyType)\n eat = l//2\n dis_candyType = set(candyType)\n\n if eat <= len(dis_candyType):\n return eat\n\n elif eat > len(dis_candyType):\n return len(dis_candyType) \n\n# Please Upvote if you like it :)\n```
3
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_. **Example 1:** **Input:** candyType = \[1,1,2,2,3,3\] **Output:** 3 **Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. **Example 2:** **Input:** candyType = \[1,1,2,3\] **Output:** 2 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types. **Example 3:** **Input:** candyType = \[6,6,6,6\] **Output:** 1 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. **Constraints:** * `n == candyType.length` * `2 <= n <= 104` * `n` is even. * `-105 <= candyType[i] <= 105`
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
Python | Easy Solution✅
distribute-candies
0
1
```\ndef distributeCandies(self, candyType: List[int]) -> int:\n # half length of candyType list\n candy_len = int(len(candyType)/2)\n # no of of unique candies \n unique_candy_len = len(set(candyType))\n return min(candy_len,unique_candy_len)\n```
9
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_. **Example 1:** **Input:** candyType = \[1,1,2,2,3,3\] **Output:** 3 **Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. **Example 2:** **Input:** candyType = \[1,1,2,3\] **Output:** 2 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types. **Example 3:** **Input:** candyType = \[6,6,6,6\] **Output:** 1 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. **Constraints:** * `n == candyType.length` * `2 <= n <= 104` * `n` is even. * `-105 <= candyType[i] <= 105`
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
single line python code :
distribute-candies
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe take the given array and make it a set and compare it with half of the length of the given array and take the least value among them \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:\n def distributeCandies(self, candyType: List[int]) -> int:\n return min(len(set(candyType)),len(candyType)//2)\n```
2
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_. **Example 1:** **Input:** candyType = \[1,1,2,2,3,3\] **Output:** 3 **Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. **Example 2:** **Input:** candyType = \[1,1,2,3\] **Output:** 2 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types. **Example 3:** **Input:** candyType = \[6,6,6,6\] **Output:** 1 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. **Constraints:** * `n == candyType.length` * `2 <= n <= 104` * `n` is even. * `-105 <= candyType[i] <= 105`
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
Solution
distribute-candies
1
1
```C++ []\nclass Solution {\n public:\n int distributeCandies(vector<int>& candies) {\n bitset<200001> bitset;\n\n for (const int candy : candies)\n bitset.set(candy + 100000);\n\n return min(candies.size() / 2, bitset.count());\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n a=len(candyType)//2\n b=len(set(candyType))\n return min(a,b)\n```\n\n```Java []\nclass Solution {\n public int distributeCandies(int[] candyType) {\n\n int n= candyType.length;\n int min= Integer.MAX_VALUE;\n int max= Integer.MIN_VALUE;\n \n int typesOfNum= 0;\n\n for(int i : candyType) {\n min= Math.min(min, i);\n max= Math.max(max, i);\n }\n boolean arr[]= new boolean[max-min+1];\n\n for(int i : candyType) {\n int j= i - min;\n\n if(!arr[j]) {\n arr[j]= true;\n typesOfNum++;\n }\n }\n return Math.min(n/2, typesOfNum);\n }\n}\n```\n
2
Alice has `n` candies, where the `ith` candy is of type `candyType[i]`. Alice noticed that she started to gain weight, so she visited a doctor. The doctor advised Alice to only eat `n / 2` of the candies she has (`n` is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice. Given the integer array `candyType` of length `n`, return _the **maximum** number of different types of candies she can eat if she only eats_ `n / 2` _of them_. **Example 1:** **Input:** candyType = \[1,1,2,2,3,3\] **Output:** 3 **Explanation:** Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type. **Example 2:** **Input:** candyType = \[1,1,2,3\] **Output:** 2 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Whether she eats types \[1,2\], \[1,3\], or \[2,3\], she still can only eat 2 different types. **Example 3:** **Input:** candyType = \[6,6,6,6\] **Output:** 1 **Explanation:** Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type. **Constraints:** * `n == candyType.length` * `2 <= n <= 104` * `n` is even. * `-105 <= candyType[i] <= 105`
To maximize the number of kinds of candies, we should try to distribute candies such that sister will gain all kinds. What is the upper limit of the number of kinds of candies sister will gain? Remember candies are to distributed equally. Which data structure is the most suitable for finding the number of kinds of candies? Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit.
Solution
out-of-boundary-paths
1
1
```C++ []\nclass Solution {\npublic:\n int dp[51][51][51];\n long mod = 1e9+7;\n \n int dfs(int m,int n,int mvs,int row,int col){\n if(row >= m || col >= n || row < 0 || col < 0)\n return 1;\n if(!mvs)\n return 0;\n if(dp[row][col][mvs] != -1)\n return dp[row][col][mvs];\n \n long res = 0;\n \n res += dfs(m,n,mvs-1,row-1,col);\n res += dfs(m,n,mvs-1,row,col+1);\n res += dfs(m,n,mvs-1,row+1,col);\n res += dfs(m,n,mvs-1,row,col-1);\n \n return dp[row][col][mvs] = res % mod;\n }\n int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n memset(dp,-1,sizeof(dp));\n \n return dfs(m,n,maxMove,startRow,startColumn);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n MOD = 1000000007\n @cache\n def recur(r, c, moves):\n if r < 0 or c < 0 or r >= m or c >= n: return 1\n if moves == 0: return 0\n return recur(r+1,c, moves-1) + recur(r-1,c,moves-1) + recur(r,c-1, moves-1) + recur(r,c+1, moves-1)\n \n return recur(startRow, startColumn, maxMove) % MOD\n```\n\n```Java []\nclass Solution {\n public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n int memo[][][] = new int[m][n][maxMove+1];\n int mod=(int) Math.pow(10,9)+7;\n return topDown(m,n,maxMove,startRow,startColumn,memo,mod)%mod;\n }\n public int topDown(int m,int n,int rest,int i,int j,int memo[][][],int mod)\n {\n if (i>=m || j>=n || i<0 || j<0 ) return 1;\n if (m-i-1>rest && i>rest && n-j-1>rest && j>rest) return memo[i][j][rest]=0; \n if (rest<=0) return 0;\n if (memo[i][j][rest]!=0) return memo[i][j][rest];\n int ret=0;\n ret+=topDown(m,n,rest-1,i-1,j,memo,mod);\n ret=ret%mod;\n ret+=topDown(m,n,rest-1,i+1,j,memo,mod);\n ret=ret%mod;\n ret+=topDown(m,n,rest-1,i,j-1,memo,mod);\n ret=ret%mod;\n ret+=topDown(m,n,rest-1,i,j+1,memo,mod);\n ret=ret%mod;\n return memo[i][j][rest]=ret;\n }\n}\n```\n
1
There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 **Output:** 6 **Example 2:** **Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 **Output:** 12 **Constraints:** * `1 <= m, n <= 50` * `0 <= maxMove <= 50` * `0 <= startRow < m` * `0 <= startColumn < n`
Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways. Can you use this thing to solve the problem?
Solution
out-of-boundary-paths
1
1
```C++ []\nclass Solution {\npublic:\n int dp[51][51][51];\n long mod = 1e9+7;\n \n int dfs(int m,int n,int mvs,int row,int col){\n if(row >= m || col >= n || row < 0 || col < 0)\n return 1;\n if(!mvs)\n return 0;\n if(dp[row][col][mvs] != -1)\n return dp[row][col][mvs];\n \n long res = 0;\n \n res += dfs(m,n,mvs-1,row-1,col);\n res += dfs(m,n,mvs-1,row,col+1);\n res += dfs(m,n,mvs-1,row+1,col);\n res += dfs(m,n,mvs-1,row,col-1);\n \n return dp[row][col][mvs] = res % mod;\n }\n int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n memset(dp,-1,sizeof(dp));\n \n return dfs(m,n,maxMove,startRow,startColumn);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n MOD = 1000000007\n @cache\n def recur(r, c, moves):\n if r < 0 or c < 0 or r >= m or c >= n: return 1\n if moves == 0: return 0\n return recur(r+1,c, moves-1) + recur(r-1,c,moves-1) + recur(r,c-1, moves-1) + recur(r,c+1, moves-1)\n \n return recur(startRow, startColumn, maxMove) % MOD\n```\n\n```Java []\nclass Solution {\n public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n int memo[][][] = new int[m][n][maxMove+1];\n int mod=(int) Math.pow(10,9)+7;\n return topDown(m,n,maxMove,startRow,startColumn,memo,mod)%mod;\n }\n public int topDown(int m,int n,int rest,int i,int j,int memo[][][],int mod)\n {\n if (i>=m || j>=n || i<0 || j<0 ) return 1;\n if (m-i-1>rest && i>rest && n-j-1>rest && j>rest) return memo[i][j][rest]=0; \n if (rest<=0) return 0;\n if (memo[i][j][rest]!=0) return memo[i][j][rest];\n int ret=0;\n ret+=topDown(m,n,rest-1,i-1,j,memo,mod);\n ret=ret%mod;\n ret+=topDown(m,n,rest-1,i+1,j,memo,mod);\n ret=ret%mod;\n ret+=topDown(m,n,rest-1,i,j-1,memo,mod);\n ret=ret%mod;\n ret+=topDown(m,n,rest-1,i,j+1,memo,mod);\n ret=ret%mod;\n return memo[i][j][rest]=ret;\n }\n}\n```\n
1
There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 **Output:** 6 **Example 2:** **Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 **Output:** 12 **Constraints:** * `1 <= m, n <= 50` * `0 <= maxMove <= 50` * `0 <= startRow < m` * `0 <= startColumn < n`
Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways. Can you use this thing to solve the problem?
576: Solution with step by step explanation
out-of-boundary-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define the variable MOD as 10**9 + 7.\n2. Initialize a 3D list dp of dimensions m x n x (maxMove+1) with all elements as 0.\n3. Set dp[startRow][startColumn][0] to 1 since we start from the given startRow and startColumn.\n4. Initialize a variable count to 0 which keeps track of the total number of paths that go out of the grid.\n5. Use three nested loops to iterate over all possible positions and moves.\n6. Check if the current position dp[i][j][k] is greater than 0. If it is, then we can move from this position to other adjacent positions.\n7. Use another loop to iterate over all possible directions, namely, right, left, up, and down.\n8. Calculate the new position (ni, nj) by adding the direction (di, dj) to the current position (i, j).\n9. Check if the new position (ni, nj) is inside the grid. If it is, then add the number of paths that can reach (i, j, k) to (ni, nj, k+1).\n10. If the new position (ni, nj) is outside the grid, then add the number of paths that can reach (i, j, k) to count.\n11. After all the iterations are complete, the value of count gives the total number of paths that go out of the grid. Return count.\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:\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n MOD = 10**9 + 7\n dp = [[[0] * (maxMove+1) for _ in range(n)] for _ in range(m)]\n dp[startRow][startColumn][0] = 1\n count = 0\n\n for k in range(maxMove):\n for i in range(m):\n for j in range(n):\n if dp[i][j][k] > 0:\n for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n ni, nj = i+di, j+dj\n if 0 <= ni < m and 0 <= nj < n:\n dp[ni][nj][k+1] = (dp[ni][nj][k+1] + dp[i][j][k]) % MOD\n else:\n count = (count + dp[i][j][k]) % MOD\n\n return count\n```
2
There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 **Output:** 6 **Example 2:** **Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 **Output:** 12 **Constraints:** * `1 <= m, n <= 50` * `0 <= maxMove <= 50` * `0 <= startRow < m` * `0 <= startColumn < n`
Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways. Can you use this thing to solve the problem?
576: Solution with step by step explanation
out-of-boundary-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define the variable MOD as 10**9 + 7.\n2. Initialize a 3D list dp of dimensions m x n x (maxMove+1) with all elements as 0.\n3. Set dp[startRow][startColumn][0] to 1 since we start from the given startRow and startColumn.\n4. Initialize a variable count to 0 which keeps track of the total number of paths that go out of the grid.\n5. Use three nested loops to iterate over all possible positions and moves.\n6. Check if the current position dp[i][j][k] is greater than 0. If it is, then we can move from this position to other adjacent positions.\n7. Use another loop to iterate over all possible directions, namely, right, left, up, and down.\n8. Calculate the new position (ni, nj) by adding the direction (di, dj) to the current position (i, j).\n9. Check if the new position (ni, nj) is inside the grid. If it is, then add the number of paths that can reach (i, j, k) to (ni, nj, k+1).\n10. If the new position (ni, nj) is outside the grid, then add the number of paths that can reach (i, j, k) to count.\n11. After all the iterations are complete, the value of count gives the total number of paths that go out of the grid. Return count.\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:\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n MOD = 10**9 + 7\n dp = [[[0] * (maxMove+1) for _ in range(n)] for _ in range(m)]\n dp[startRow][startColumn][0] = 1\n count = 0\n\n for k in range(maxMove):\n for i in range(m):\n for j in range(n):\n if dp[i][j][k] > 0:\n for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n ni, nj = i+di, j+dj\n if 0 <= ni < m and 0 <= nj < n:\n dp[ni][nj][k+1] = (dp[ni][nj][k+1] + dp[i][j][k]) % MOD\n else:\n count = (count + dp[i][j][k]) % MOD\n\n return count\n```
2
There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 **Output:** 6 **Example 2:** **Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 **Output:** 12 **Constraints:** * `1 <= m, n <= 50` * `0 <= maxMove <= 50` * `0 <= startRow < m` * `0 <= startColumn < n`
Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways. Can you use this thing to solve the problem?
Python3 || recursion , one grid w/ explanation || T/M: 89%/49%
out-of-boundary-paths
0
1
```\nclass Solution: # The plan is to accrete the number of paths from the starting cell, which\n # is the sum of (a) the number of adjacent positions that are off the grid\n # and (b) the number of paths from the adjacent cells in the grid within \n # maxMove steps. We determine (b) recursively.\n\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n\n @lru_cache(None) # <-- Many cells are revisited so we cache the previous calls\n def dp (x,y,steps = maxMove):\n if x not in range(m) or y not in range(n): # <-- Moved off the grid so increment the tally\n return 1\n if not steps: # <-- Ran out of the maxMove steps\n return 0\n\n ans, dx, dy = 0, 1, 0\n for _ in range(4):\n ans+= dp(x+dx, y+dy, steps-1) # <-- visit the adjacent cells\n dx, dy = dy,-dx # <-- iterates thru the directions:\n\t\t\t\t # south => east => north => west \n\n return ans \n\n return dp (startRow, startColumn)%1000000007\n\t\t\n\t\t# Thanks to XixiangLiu for fixing a number of my errors in the original post.
5
There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 **Output:** 6 **Example 2:** **Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 **Output:** 12 **Constraints:** * `1 <= m, n <= 50` * `0 <= maxMove <= 50` * `0 <= startRow < m` * `0 <= startColumn < n`
Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways. Can you use this thing to solve the problem?
Python3 || recursion , one grid w/ explanation || T/M: 89%/49%
out-of-boundary-paths
0
1
```\nclass Solution: # The plan is to accrete the number of paths from the starting cell, which\n # is the sum of (a) the number of adjacent positions that are off the grid\n # and (b) the number of paths from the adjacent cells in the grid within \n # maxMove steps. We determine (b) recursively.\n\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n\n @lru_cache(None) # <-- Many cells are revisited so we cache the previous calls\n def dp (x,y,steps = maxMove):\n if x not in range(m) or y not in range(n): # <-- Moved off the grid so increment the tally\n return 1\n if not steps: # <-- Ran out of the maxMove steps\n return 0\n\n ans, dx, dy = 0, 1, 0\n for _ in range(4):\n ans+= dp(x+dx, y+dy, steps-1) # <-- visit the adjacent cells\n dx, dy = dy,-dx # <-- iterates thru the directions:\n\t\t\t\t # south => east => north => west \n\n return ans \n\n return dp (startRow, startColumn)%1000000007\n\t\t\n\t\t# Thanks to XixiangLiu for fixing a number of my errors in the original post.
5
There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 **Output:** 6 **Example 2:** **Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 **Output:** 12 **Constraints:** * `1 <= m, n <= 50` * `0 <= maxMove <= 50` * `0 <= startRow < m` * `0 <= startColumn < n`
Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways. Can you use this thing to solve the problem?
Just sort the array | Python
shortest-unsorted-continuous-subarray
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf a number is not in it\'s poisition then we need to start the sorting from there. This is form left to right, same thing for right to left. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust sort the array, compare the position of the array with original array. Do left to righ and sdo right to left. simple !! \n\n# Complexity\n- Time complexity: O(NlogN), max for the sorting the the numbers. \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) for additional array \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n temp = sorted(nums)\n if temp[:] == nums[:]:return 0\n l, r = 0, len(nums)-1\n for i, x in enumerate(nums):\n if temp[i] != x:\n l = i\n break \n while temp[r] == nums[r]:\n r-=1\n return r-l+1\n```
1
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
Solution
shortest-unsorted-continuous-subarray
1
1
```C++ []\nclass Solution {\npublic:\n\n bool outOfOrder(vector<int> &nums, int i){\n if(nums.size() == 1) return 0;\n int x = nums[i];\n\n if(i == 0) return x > nums[1];\n if(i == nums.size()-1) return x < nums[i-1];\n\n return x > nums[i+1] or x < nums[i-1];\n }\n int findUnsortedSubarray(vector<int>& nums) {\n int s = INT_MAX, l = INT_MIN;\n\n for(int i = 0; i<nums.size(); i++){\n int x = nums[i];\n\n if(outOfOrder(nums, i)){\n s = min(s, x);\n l = max(l, x);\n }\n }\n if(s == INT_MAX) return 0;\n\n int left = 0;\n while(s >= nums[left]) left++;\n\n int right = nums.size() - 1;\n while(l <= nums[right]) right--;\n\n return right - left + 1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n front = 0\n while front < len(nums) -1 and nums[front] <= nums[front+1]:\n front +=1\n \n if front == len(nums)-1:\n return 0\n \n back = len(nums) -1\n while nums[back] >= nums[back-1]:\n back -=1\n \n max_ = max(nums[front:back+1])\n min_ = min(nums[front:back+1])\n\n while front >0 and nums[front-1] > min_:\n front -=1\n \n while back < len(nums)-1 and nums[back+1] < max_:\n back +=1\n \n return back - front + 1\n```\n\n```Java []\nclass Solution {\npublic int findUnsortedSubarray(int[] nums) {\n int minVal = Integer.MAX_VALUE, maxVal = Integer.MIN_VALUE;\n int n = nums.length;\n for(int i = 1; i < n; i++) {\n if(nums[i] < nums[i-1]) {\n minVal = Math.min(minVal, nums[i]);\n }\n }\n for(int i = n-2; i >= 0; i--) {\n if(nums[i] > nums[i+1]) {\n maxVal = Math.max(maxVal, nums[i]);\n }\n }\n if(minVal == Integer.MAX_VALUE && maxVal == Integer.MIN_VALUE) return 0;\n\n int start = 0, end = n-1;\n for(; start < n; start++) {\n if(nums[start] > minVal) break;\n }\n for(; end >= 0; end--) {\n if(nums[end] < maxVal) break;\n }\n return end - start + 1;\n}\n}\n```\n
2
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
581: Solution with step by step explanation
shortest-unsorted-continuous-subarray
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Make a sorted copy of the input array nums and store it in the variable sorted_nums.\n2. Initialize two variables start and end to invalid indices. We will use these to keep track of the start and end of the shortest unsorted subarray.\n3. Use a loop to iterate over all elements of the input array nums.\n4. Check if the current element nums[i] is not equal to the corresponding element in the sorted array sorted_nums[i].\n5. Update start to be the minimum of its current value and i.\n6. Update end to be the maximum of its current value and i.\n7. After the loop completes, check if end - start >= 0. If it is, then the array has at least one unsorted subarray, so return end - start + 1.\n8. If end - start < 0, then the array is already sorted, so return 0.\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:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n sorted_nums = sorted(nums) # make a sorted copy of the original array\n start, end = len(nums), 0 # initialize start and end to invalid indices\n \n # find the leftmost element that is out of order\n for i in range(len(nums)):\n if nums[i] != sorted_nums[i]:\n start = min(start, i)\n end = max(end, i)\n \n return end - start + 1 if end - start >= 0 else 0 # Return length of shortest unsorted subarray, or 0 if array is already sorted\n```
4
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
simplest solution
shortest-unsorted-continuous-subarray
0
1
# 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:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n sort = sorted(nums)\n left = 0\n right = len(nums)-1\n if sort == nums or len(nums)==1:\n return 0\n for x in range(len(nums)): \n if nums[left] == sort[left]:\n left +=1\n if nums[right] == sort[right]:\n right -=1\n if left == right:\n return 0\n return right-left+1\n \n```
2
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
O(n) CPP + O(nlogn) Python With Explanation From Scratch
shortest-unsorted-continuous-subarray
0
1
## Explanation\n```\n nums = 1 3 2 4 7 6 8 9\nsorted_nums = 1 2 3 4 6 7 8 9 -- This is an increasing array, where every nums[i]\nis greater than all of its left side values.\n\n In nums = 1 3 2 4 7 6 8 9\n 0 1 2 3 4 5 6 7 (indexes)\n\n 1. nums[0] & nums[1] are in increasing order as an increasing array should be.\n ->\'2\'. So nums[2] also should be greater than all of its left side values? But here it\'s not.\n 3. nums[3] and nums[4] are increasing order.\n -> 4. But nums[5] is not.\n 5. nums[6] and nums[7] are increasing order.\n \n nums = 1 3 2 4 7 6 8 9\n 0 1 2 3 4 5 6 7 (indexes)\n i i\n\n At step 2 & 4, we will assume that maybe it\'s the "last value which is not increased".\n so we will store their current "i" in the variable "end" if the condition passed.\n (if nums[i] < maxSoFar) -> if nums[i] less than all of its left side values.\n\n Now think reversely for finding the \'starting index\' from where the sorting should start.\n nums[7] is the maximum value, so nums[6] is obviously less than nums[7]? \n similarly nums[5] < nums[6] for an increasing array......\n "So if we iterate from the end, all number should be in decreasing order"\n But nums[4] and nums[1] are not in decreasing order. \n\n nums = 1 3 2 4 7 6 8 9\n 0 1 2 3 4 5 6 7 (indexes)\n i i\n\n Store the "i" in the variable "start" when (if nums[i] > minSoFar) condition fail.\n\n Eventually :\n nums = 1 3 2 4 7 6 8 9\n 0 1 2 3 4 5 6 7 (indexes)\n | |\n start end\n\nreturn end - start + 1 = total values to be sorted.\n```\n### I did this O(n) code in CPP which you can convert to python easily and the O(nlogn) process in Python with Pythonic Syntax.\n```\nIn python here next() is applied on a generator expression, when the generator returns\nit\'s first value, the next() take the value and break the process of the generator expression.\nIf the generator expression doesn\'t return any value, then next() returns None \n```\n```CPP []\nclass Solution {\npublic:\n int findUnsortedSubarray(vector<int>& nums) \n {\n int end = -1, maxSoFar = nums[0], n = nums.size();\n for(int i=1; i<n; i++)\n {\n maxSoFar = max(maxSoFar, nums[i]);\n if(nums[i] < maxSoFar)\n end = i;\n }\n\n int start = 0, minSoFar = nums[n-1];\n for(int i=n-2; i>-1; i--)\n {\n minSoFar = min(minSoFar, nums[i]);\n if(nums[i] > minSoFar)\n start = i;\n }\n\n return end - start + 1;\n }\n};\n```\n```Python []\nclass Solution:\n def findUnsortedSubarray(self, nums):\n sorted_nums = sorted(nums)\n start = next( (i for i in range(len(nums)) if nums[i]!=sorted_nums[i]), None)\n end = next( (i for i in range(len(nums)-1,-1,-1) if nums[i]!=sorted_nums[i]), None)\n return end - start + 1 if start is not None else 0\n```\n## I write a lengthy post trying to explain from scratch. Thank you for reading it, if the post was helpful an upvote will really make me happy:)
3
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
Python Simple Two Approaches
shortest-unsorted-continuous-subarray
0
1
1. ***Sorting***\nThe algorithm goes like this:\n\t1. Create a sorted clone of the original list. \n\t2. Compare the elements at same index in both the list. Once you encounter a mismatch, use that to find the lower and upper bounds of the unsorted subarray.\n\n\n```\nclass Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n sorted_nums = sorted(nums)\n \n l, u = len(nums) - 1,0\n for i in range(len(nums)):\n if nums[i]!=sorted_nums[i]:\n l=min(l, i)\n u=max(u, i)\n \n \n return 0 if l>=u else u-l+1\n```\n\n**Time = O(nlogn)** - for sorting \n**Space = O(n)** - for storing the sorted copy\n\n2. ***Stack***\n\nThere is a follow-up question to solve this in **O(n)** time. For this, we can use stack to track the first inconsistencies and find the lower and upper bounds of the subarray.\n\n```\nclass Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n \n l,u = len(nums)-1, 0\n stck=[]\n for i in range(len(nums)):\n while stck and nums[stck[-1]]>nums[i]:\n l = min(l, stck.pop())\n stck.append(i)\n \n stck=[] \n for i in range(len(nums)-1,-1, -1):\n while stck and nums[stck[-1]]<nums[i]:\n u = max(u, stck.pop())\n stck.append(i)\n \n return 0 if l>=u else u-l+1\n```\n**Time = O(n)** \n**Space = O(n)**\n\n---\n\n***Please upvote if you find it useful***
12
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
Python 3 solution using a sort and two pointers
shortest-unsorted-continuous-subarray
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to know: where does nums first differ from a sorted list of the same elements, when comparing from the left and from the right?\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Make a sorted copy of **nums** as a basis for comparison\n- Compare the elements of the original and sorted lists, starting from the left and proceding rightward, until a difference is found. This is the beginning of the unsorted subarray.\n- Compare the elements of the original and sorted lists, starting from the right and proceding leftward, until a difference is found. This is the end of the unsorted subarray.\n- Return the difference plus 1 as the length of the unsorted subarray.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(*n log n*) because of the sort.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(*n*) for the sorted copy of nums.\n# Code\n```\nclass Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n # Left and right index pointers will mark the unsorted subarray\n left, right = 0, len(nums) - 1\n # At a time cost of O(n log n) we can compare nums with a fully sorted version\n sorted_nums = sorted(nums)\n while left < len(nums):\n if nums[left] != sorted_nums[left]: # First difference from the left\n break\n left += 1\n while right > left:\n if nums[right] != sorted_nums[right]: # First differnece from the right\n break\n right -= 1\n return right - left + 1 # Unsorted subarray length\n```
1
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
Python (99.64 %beats) || Tabulation || DP || Using LCS
delete-operation-for-two-strings
0
1
\n> **First Solve Leetcode Ques No. ->> 1143 - Longest Common Subsequence** \n\n[Navigate to Leetcode problem 1143. ](https://leetcode.com/problems/longest-common-subsequence/solutions/4122297/python-96-beats-tabulation-dp-memorization-optimize-way-2d-matrix-way/)\n\n# Code\n```\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n l1 = len(word1)\n l2 = len(word2)\n\n prev = [0 for k in range(l2+1)]\n\n for i in range(1, l1+1):\n curr = [0 for k in range(l2+1)]\n for j in range(1, l2+1):\n if word1[i-1] == word2[j-1]:\n curr[j] = prev[j-1] + 1\n else:\n curr[j] = max(curr[j-1], prev[j])\n prev = curr\n\n return l1+ l2 - (2 * curr[l2])\n\n # OR\n common_subseq= curr[l2]\n a = l1 - common_subseq\n b = l2 - common_subseq\n return a+b\n\n\n```\n# Your upvote is my motivation!\n\n.\n
1
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
Solution
delete-operation-for-two-strings
1
1
```C++ []\nclass Solution {\npublic:\n int lengthLcs(string text1, string text2) {\n short int l1 = text1.size()+1;\n short int l2 = text2.size()+1;\n short int count[l2][l1], i, j;\n for(i=0; i<l1; i++) count[0][i]=0;\n for(i=0; i<l2; i++) count[i][0]=0;\n for(i=1; i<l2; i++){\n for(j=1; j<l1; j++){\n if(text2[i-1]==text1[j-1])\n count[i][j]=count[i-1][j-1]+1;\n else count[i][j]=max(count[i][j-1],count[i-1][j]);\n }\n }\n return count[l2-1][l1-1];\n }\n int minDistance(string word1, string word2) {\n int length = lengthLcs(word1,word2);\n int total = word1.size() + word2.size() - 2*length;\n\n return total;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n pattern_dict = {}\n for i,l in enumerate(word2):\n if l in pattern_dict:\n pattern_dict[l].append(i)\n else:\n pattern_dict[l] = [i]\n \n n = max(len(word1),len(word2))\n dp = [n+1] * (n+1)\n for l in word1:\n if l not in pattern_dict:\n continue\n for i in reversed(pattern_dict[l]):\n index = bisect.bisect_left(dp,i)\n dp[index] = i\n return len(word1)+len(word2)-2*bisect.bisect_left(dp,n+1)\n```\n\n```Java []\nclass Solution {\n public int minDistance(String s1, String s2) {\n int n = s1.length();\n int m = s2.length();\n\n if (n < m) minDistance(s2, s1);\n\n char[] WA1 = s1.toCharArray();\n char[] WA2 = s2.toCharArray();\n \n int[] dpLast = new int[m + 1];\n int[] dpCurr = new int[m + 1];\n \n for (char c1 : WA1) {\n for (int j = 0; j < m; j++) {\n if (c1 == WA2[j]) {\n dpCurr[j + 1] = dpLast[j] + 1;\n } else {\n dpCurr[j + 1] = Math.max(dpCurr[j], dpLast[j + 1]);\n }\n }\n int[] tempArr = dpLast;\n dpLast = dpCurr;\n dpCurr = tempArr;\n }\n \n return n + m - 2 * dpLast[m];\n }\n}\n```\n
1
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
Python || easy solu|| using DP bottomup
delete-operation-for-two-strings
0
1
```\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m=len(word1)\n n=len(word2)\n dp=[]\n for i in range (m+1):\n dp.append([0]*(n+1))\n for i in range (m+1):\n dp[i][0]=i\n for i in range (n+1):\n dp[0][i]=i\n for i in range (1,m+1):\n for j in range (1,n+1):\n if word1[i-1]==word2[j-1]:\n dp[i][j]=dp[i-1][j-1]\n else:\n dp[i][j]=min(dp[i][j-1],dp[i-1][j])+1\n return dp[-1][-1]\n \n```
1
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
583: Solution with step by step explanation
delete-operation-for-two-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Get the lengths of the two input strings and store them in variables m and n.\n2. Initialize a dynamic programming table dp of size (m + 1) x (n + 1) with all entries initialized to 0.\n3. Use a nested loop to iterate over all entries of the dynamic programming table dp.\n4. If the characters word1[i-1] and word2[j-1] are the same, set dp[i][j] to be one greater than dp[i-1][j-1].\n5. Otherwise, set dp[i][j] to be the maximum of dp[i-1][j] and dp[i][j-1].\n6. After the loop completes, return the minimum number of deletions required to convert word1 to word2. This is equal to m + n - 2 * dp[m][n].\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:\n def minDistance(self, word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n \n # fill in the dynamic programming table\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n if word1[i - 1] == word2[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])\n \n # return the minimum number of deletions required\n return m + n - 2 * dp[m][n]\n```
2
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
Python || 98.80% Faster || DP || Space Optimization || LCS
delete-operation-for-two-strings
0
1
```\n#Tabulation(Top-Down)\n#Time Complexity: O(m*n)\n#Space Complexity: O(m*n)\nclass Solution1:\n def minDistance(self, word1: str, word2: str) -> int:\n m,n=len(word1),len(word2)\n dp=[[0 for j in range(n+1)] for i in range(m+1)]\n for i in range(1,m+1):\n for j in range(1,n+1):\n if word1[i-1]==word2[j-1]:\n dp[i][j]=1+dp[i-1][j-1]\n else:\n dp[i][j]=max(dp[i-1][j],dp[i][j-1])\n k=dp[m][n] # Longest Common Subsequence\n return (n-k)+(m-k)\n\n#Space Optimization\n#Time Complexity: O(m*n)\n#Space Complexity: O(n) \nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m,n=len(word1),len(word2)\n prev=[0]*(n+1)\n for i in range(1,m+1):\n curr=[0]*(n+1)\n for j in range(1,n+1):\n if word1[i-1]==word2[j-1]:\n curr[j]=1+prev[j-1]\n else:\n curr[j]=max(prev[j],curr[j-1])\n prev=curr[:]\n k=prev[n] # Longest Common Subsequence\n return (n-k)+(m-k)\n```\n**An upvote will be encouraging**
1
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
Python DP 2 approaches using LCS ✅
delete-operation-for-two-strings
0
1
The prerequisite for this problem is [Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/solution/). Please check and solve that problem first before you solve this. Once you have mastered LCS, this problem is easy.\n\n>eg: Input strings: **s1**="sea", **s2**="eat"\n\n**LCS** for above inputs is "ea"\nSo the number of characters that needs to be deleted from both the strings can be calculated as :\n> ***Required number of deletions = length of s1 + length of s2 - 2 * length of LCS***\n\nThe LCS can be solved using DP both the methods. I have provided the solutions using two approaches:\n\n## \u2714\uFE0F*Solution I - Memoization - Top Down*\n```\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m,n=len(word1),len(word2)\n @cache\n def lcs(i, j): # find longest common subsequence\n if i==m or j==n:\n return 0 \n return 1 + lcs(i+1, j+1) if word1[i]==word2[j] else max(lcs(i+1, j), lcs(i,j+1)) \n # subtract the lcs length from both the strings \n # the difference is the number of characters that has to deleted\n return m + n - 2*lcs(0,0)\n```\n**Time - O(m * n)** - to explore all paths\n**Space - O(m * n)** - for cache and recursive call stack\n\n----\n\n## \u2714\uFE0F*Solution I I - Tabulation - Bottom Up*\n```\nclass Solution: \n def minDistance(self, word1: str, word2: str) -> int:\n if len(word1)>len(word2):\n word2,word1=word1,word2 \n \n m,n=len(word1),len(word2)\n prev=[0] * (m+1)\n \n for i in range(n-1, -1, -1):\n curr=[0] * (m+1)\n for j in range(m-1, -1, -1):\n if word1[j] == word2[i]:\n curr[j]=1 + prev[j+1]\n else:\n curr[j]=max(curr[j+1], prev[j])\n prev=curr\n return m + n - 2*prev[0]\n```\n\n**Time - O(m * n)**\n**Space - O(min(m,n))** - for the dp array\n\n---\n\n\n***Please upvote if you find it useful***
51
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
Simple DP || Python || Exact LCS Code
delete-operation-for-two-strings
0
1
# Intuition\nThe intuition is pretty similar to finding Longest Common subsequence and then delete all those characters which are extra and count all delete operations as number of steps required.\n\n# Approach\nWe need to make word1 == word2 but by deleting characters.\nFind the longest Common Subsequence and store its length.\nNow find the total length of the string and count the difference from the longest common Subsequnce length => gives u no of deletion steps required.\n`Why LenLongestSub * 2?`\n`You can look it as deleted Steps Required= ((len(word1) - LCS) + (len(word2) - LCS))`\n\n# Code\n```\nclass Solution:\n def minDistance(self, w1: str, w2: str) -> int:\n n = len(w1)\n m = len(w2)\n dp = [[0]*(m +1) for _ in range(n+1)]\n for i in range(n):\n for j in range(m):\n if w1[i] == w2[j]:\n dp[i+1][j+1] = 1 + dp[i][j]\n else:\n dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])\n lenLongestSub = (dp[-1][-1]) * 2\n totalLen = m + n\n deleteOperations = totalLen - lenLongestSub\n # print(deleteOperations)\n return deleteOperations\n \n```
1
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
[Python 3] 5 Lines with top down DP, faster than 81.75%
delete-operation-for-two-strings
0
1
**Appreciate if you could upvote this solution**\n\n```\ndef minDistance(self, word1: str, word2: str) -> int:\n\tmin_distance_dp = [[i for i in range(len(word2)+1)]] + [[i] + [math.inf] * (len(word2)) for i in range(1, len(word1)+1)]\n\n\tfor i in range(len(word1)):\n\t\tfor j in range(len(word2)):\n\t\t\tmin_distance_dp[i + 1][j + 1] = min_distance_dp[i][j] if word1[i] == word2[j] else min(min_distance_dp[i+1][j], min_distance_dp[i][j+1]) + 1\n\n\treturn min_distance_dp[-1][-1]\n```
29
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
✔️ PYTHON || EXPLAINED || ;]
delete-operation-for-two-strings
0
1
**UPVOTE IF HELPFuuL**\n\nFrom both strings ```word1``` and ```word2``` only those haracter will be deleted which are not present in the other string.\n\nFor this we find ```LCS``` i.e. Longest Common Subsequence.\n\nWe create a matrix of size ```(m+1)*(n+1)``` and make first row and column equal to zero.\n\n* If ```i``` element of ```word1``` is equal to ```j``` element of ```word2``` we make the index of matrix[ i + 1 ][ j + 1 ] equal to ```1 + diagonally previous element``` \n* If they are n0t equal equal then matrix value at that index will be maximum of element above or to the left of that matrix.\n\nThe very last element of that matrix will give us the length of **LONGEST COMMON SUBSEQUENCE**\n\n![image](https://assets.leetcode.com/users/images/04eec89a-635d-4bd2-8823-4728982c7ece_1655180622.129215.jpeg)\n\n\nThe very last element of that matrix will give us the length of **LONGEST COMMON SUBSEQUENCE**\n\n```\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m = len(word1)\n n = len(word2)\n a = []\n for i in range(m+1):\n a.append([])\n for j in range(n+1):\n a[-1].append(0)\n \n for i in range(m):\n for j in range(n):\n if word1[i]==word2[j]:\n a[i+1][j+1] = 1 + a[i][j]\n else:\n a[i+1][j+1] = max( a[i][j+1], a[i+1][j])\n\t\t\t\t\t\n return m + n - ( 2 * a [-1][-1] )\n```\n![image](https://assets.leetcode.com/users/images/9b2fa610-c7b8-49bb-a725-8da7579eb1a7_1655180197.5408206.jpeg)\n
24
Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_. In one **step**, you can delete exactly one character in either string. **Example 1:** **Input:** word1 = "sea ", word2 = "eat " **Output:** 2 **Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ". **Example 2:** **Input:** word1 = "leetcode ", word2 = "etco " **Output:** 4 **Constraints:** * `1 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of only lowercase English letters.
null
✔️ Python Simple and Easy Way to Solve | 99% Faster 🔥
erect-the-fence
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nimport itertools\n\n# Monotone Chain Algorithm\nclass Solution(object):\n def outerTrees(self, points):\n\t\n def ccw(A, B, C):\n return (B[0]-A[0])*(C[1]-A[1]) - (B[1]-A[1])*(C[0]-A[0])\n\n if len(points) <= 1:\n return points\n\n hull = []\n points.sort()\n for i in itertools.chain(range(len(points)), reversed(range(len(points)-1))):\n while len(hull) >= 2 and ccw(hull[-2], hull[-1], points[i]) < 0:\n hull.pop()\n hull.append(points[i])\n hull.pop()\n\n for i in range(1, (len(hull)+1)//2):\n if hull[i] != hull[-1]:\n break\n hull.pop()\n return hull\n```\n\n**For Leetcode Solution with Explanation Visit this Blog:\nhttps://www.python-techs.com/\n(Please open this link in new tab)**\n\nThank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.
4
You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**. Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**. **Example 1:** **Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\] **Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\] **Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence. **Example 2:** **Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\] **Output:** \[\[4,2\],\[2,2\],\[1,2\]\] **Explanation:** The fence forms a line that passes through all the trees. **Constraints:** * `1 <= trees.length <= 3000` * `trees[i].length == 2` * `0 <= xi, yi <= 100` * All the given positions are **unique**.
null
Solution
erect-the-fence
1
1
```C++ []\nstruct pt {\n int x, y;\n pt(int x, int y): x(x), y(y){}\n};\nint orientation(pt a, pt b, pt c) {\n int v = a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y);\n if (v < 0) return -1;\n if (v > 0) return +1;\n return 0;\n}\nbool cw(pt a, pt b, pt c, bool include_collinear) {\n int o = orientation(a, b, c);\n return o < 0 || (include_collinear && o == 0);\n}\nbool ccw(pt a, pt b, pt c, bool include_collinear) {\n int o = orientation(a, b, c);\n return o > 0 || (include_collinear && o == 0);\n}\nvoid convex_hull(vector<pt>& a, bool include_collinear = false) {\n if (a.size() == 1)\n return;\n\n sort(a.begin(), a.end(), [](pt a, pt b) {\n return make_pair(a.x, a.y) < make_pair(b.x, b.y);\n });\n pt p1 = a[0], p2 = a.back();\n vector<pt> up, down;\n up.push_back(p1);\n down.push_back(p1);\n for (int i = 1; i < (int)a.size(); i++) {\n if (i == a.size() - 1 || cw(p1, a[i], p2, include_collinear)) {\n while (up.size() >= 2 && !cw(up[up.size()-2], up[up.size()-1], a[i], include_collinear))\n up.pop_back();\n up.push_back(a[i]);\n }\n if (i == a.size() - 1 || ccw(p1, a[i], p2, include_collinear)) {\n while (down.size() >= 2 && !ccw(down[down.size()-2], down[down.size()-1], a[i], include_collinear))\n down.pop_back();\n down.push_back(a[i]);\n }\n }\n if (include_collinear && up.size() == a.size()) {\n reverse(a.begin(), a.end());\n return;\n }\n a.clear();\n for (int i = 0; i < (int)up.size(); i++)\n a.push_back(up[i]);\n for (int i = down.size() - 2; i > 0; i--)\n a.push_back(down[i]);\n}\nclass Solution {\npublic:\n vector<vector<int>> outerTrees(vector<vector<int>>& trees) {\n int n = trees.size();\n vector<pt> res;\n vector<vector<int>> ans;\n for(int i = 0; i < n; ++i) {\n res.push_back(pt(trees[i][0], trees[i][1]));\n }\n convex_hull(res, true);\n for(auto p: res) {\n ans.push_back({p.x, p.y});\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n yToX = {}\n for x,y in trees:\n if y not in yToX:\n yToX[y] = [x]\n else:\n yToX[y].append(x)\n for y in yToX:\n yToX[y].sort()\n lowerYToHigherY = sorted(yToX.keys())\n \n leftresults = []\n for y in lowerYToHigherY:\n curx = yToX[y][0]\n if len(leftresults) < 2:\n leftresults.append((curx, y))\n else:\n lastx, lasty = leftresults[-1]\n lastlastx, lastlasty = leftresults[-2]\n lastdx, lastdy = lastx-lastlastx, lasty-lastlasty\n curdx, curdy = curx-lastlastx, y-lastlasty\n while curdx/curdy < lastdx/lastdy:\n leftresults.pop()\n if len(leftresults) >= 2:\n lastx, lasty = leftresults[-1]\n lastlastx, lastlasty = leftresults[-2]\n lastdx, lastdy = lastx-lastlastx, lasty-lastlasty\n curdx, curdy = curx-lastlastx, y-lastlasty\n else:\n break\n leftresults.append((curx, y))\n rightresults = []\n for y in lowerYToHigherY:\n curx = yToX[y][-1]\n if len(rightresults) < 2:\n rightresults.append((curx, y))\n else:\n lastx, lasty = rightresults[-1]\n lastlastx, lastlasty = rightresults[-2]\n lastdx, lastdy = lastx-lastlastx, lasty-lastlasty\n curdx, curdy = curx-lastlastx, y-lastlasty\n while curdx/curdy > lastdx/lastdy:\n rightresults.pop()\n if len(rightresults) >= 2:\n lastx, lasty = rightresults[-1]\n lastlastx, lastlasty = rightresults[-2]\n lastdx, lastdy = lastx-lastlastx, lasty-lastlasty\n curdx, curdy = curx-lastlastx, y-lastlasty\n else:\n break\n rightresults.append((curx, y))\n res = leftresults[1:-1] + rightresults[1:-1]\n lowest = [(x,lowerYToHigherY[0]) for x in yToX[lowerYToHigherY[0]]]\n highest = [(x,lowerYToHigherY[-1]) for x in yToX[lowerYToHigherY[-1]]]\n res += lowest + highest\n res = set(res)\n return [list(x) for x in res]\n```\n\n```Java []\nclass Solution { \n public int[][] outerTrees(int[][] trees) {\n Arrays.sort(trees, (o1, o2) -> o1[0] != o2[0] ? o1[0] - o2[0] : o1[1] - o2[1]);\n int n = trees.length;\n boolean[] used = new boolean[n];\n int[] hull = new int[n + 2];\n int top = 0;\n for (int i = 0; i < n; i++) {\n while (top >= 2 && area(trees[hull[top - 1]], trees[hull[top]], trees[i]) > 0) {\n used[hull[top--]] = false;\n }\n hull[++top] = i;\n used[i] = true;\n }\n used[0] = false;\n for (int i = n - 1; i >= 0; i--) {\n if (used[i]) continue;\n while (top >= 2 && area(trees[hull[top - 1]], trees[hull[top]], trees[i]) > 0) {\n top--;\n }\n hull[++top] = i;\n }\n top--;\n int[][] res = new int[top][2];\n for (int i = 1; i <= top; i++) res[i - 1] = trees[hull[i]];\n return res;\n }\n private int area(int[] a, int[] b, int[] c) {\n return cross(b[0] - a[0], b[1] - a[1], c[0] - a[0], c[1] - a[1]);\n }\n private int cross(int x1, int y1, int x2, int y2) {\n return x1 * y2 - x2 * y1;\n }\n}\n```\n
1
You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**. Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**. **Example 1:** **Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\] **Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\] **Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence. **Example 2:** **Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\] **Output:** \[\[4,2\],\[2,2\],\[1,2\]\] **Explanation:** The fence forms a line that passes through all the trees. **Constraints:** * `1 <= trees.length <= 3000` * `trees[i].length == 2` * `0 <= xi, yi <= 100` * All the given positions are **unique**.
null
Python = full explanation !
erect-the-fence
0
1
Python3 Solve\nUsing convex hull algorithm with helper function.\n\nSummary:\n\nFind upper hull of polygon.\nFind lower hull of polygon.\nCombine both upper and lower hulls to form full polygon.\n\n---\n\nExplanation:\n\nHelper Function = comparing slopes:\n- Create Helper function to compare slopes of 2 different lines created from 3 sorted points.\n- Compare the slopes of the lines, find the difference between the slopes. \n- ---1-Slope of the new line (made from connecting the new point to the last point) .\n- ---vs \n- ---2-Slope of previous line (created by connecting the last point with the point before that). \n- This comparison decides whether the rotation of the lines is clockwise or counter clockwise.\n- ---If the answer is negative = new line is clockwise. (add to Upper hull)\n- ---If the answer is positive = new line is counter clockwise. (add to Lower hull)\n\nMain Function:\n- Data must be sorted before starting loop.\n- Start looping through the trees.\n- At each tree check if the line formed from this tree to the previous is clockwise or counter clockwise to the line formed from the previous 2 points.\n- ---check for lower and upper separately using while loops.\n- ---if checking for upper hull and value is counter-clockwise = remove by popping from upper.\n- ---if checking for lower hull and value is clockwise = remove by popping from lower.\n- Add for loop\'s current value to each hull so it can be checked on next while loops cycle.\n- After sorting and adding to upper and lower hulls, combine hulls together.\n- Use Set to prevent duplicate trees from entering final result.\n- Return as a list.\n\n\n---\n\n```\nclass Solution:\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n def compare_slopes(point1, point2, point3):\n x_point1, y_point1 = point1\n x_point2, y_point2 = point2\n x_point3, y_point3 = point3\n return ((y_point3 - y_point2)*(x_point2 - x_point1)) - ((y_point2 - y_point1)*(x_point3 - x_point2))\n\n trees.sort()\n upper, lower = [], []\n for point in trees:\n while len(upper) > 1 and compare_slopes(upper[-2], upper[-1], point) > 0:\n upper.pop()\n while len(lower) > 1 and compare_slopes(lower[-2], lower[-1], point) < 0:\n lower.pop()\n upper.append(tuple(point))\n lower.append(tuple(point))\n return list(set(upper + lower))\n```\n-fatalbanana
1
You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**. Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**. **Example 1:** **Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\] **Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\] **Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence. **Example 2:** **Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\] **Output:** \[\[4,2\],\[2,2\],\[1,2\]\] **Explanation:** The fence forms a line that passes through all the trees. **Constraints:** * `1 <= trees.length <= 3000` * `trees[i].length == 2` * `0 <= xi, yi <= 100` * All the given positions are **unique**.
null
#easy-python3 #Erect the Fence🔥🔥🔥🔥🔥🔥🔥🔥🔥
erect-the-fence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing convex hull algorithm also known as Gift wraping algorithm\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing distance formula inbetween the points (y3-y2)/(y2-y1)=(x3-x2)/(x2-x1)\nif value is >0 then it is counter-clockwise \nif it is equal to =0 the it is linear \nelse if value is <0 then it is clockwise , and we have to see only counter clockwise\nif value is <0 then we have to pop() that index, if =0 or >0 then append(), in lst we will have values both in upper and lower so we will be eliminate comman values using set function and returns the value with is sum of both upper hull and lower hull\n#formore you can watch convex hull algorithm\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n T(n) = nh + n = o(nh)\nwhere n = total no. of points \nand h = total no of hull\\\nworst time complexity is o(n^2) when all are in hull\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(h)\n\n# Code\n```\nclass Solution:\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n def clockwise(p1,p2,p3):\n x1,y1=p1\n x2,y2=p2\n x3,y3=p3\n \n return ((y3-y2)*(x2-x1)-(y2-y1)*(x3-x2))\n trees.sort()\n upper=[]\n lower=[]\n for t in trees:\n while len(upper)>1 and clockwise(upper[-2],upper[-1],t)>0:\n upper.pop()\n while len(lower)>1 and clockwise(lower[-2],lower[-1],t)<0:\n lower.pop()\n upper.append(tuple(t))\n lower.append(tuple(t))\n \n return list(set(upper+lower)) \n\n```
1
You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**. Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**. **Example 1:** **Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\] **Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\] **Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence. **Example 2:** **Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\] **Output:** \[\[4,2\],\[2,2\],\[1,2\]\] **Explanation:** The fence forms a line that passes through all the trees. **Constraints:** * `1 <= trees.length <= 3000` * `trees[i].length == 2` * `0 <= xi, yi <= 100` * All the given positions are **unique**.
null
587: Solution with step by step explanation
erect-the-fence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create an empty list hull to store the points on the hull.\n2. Sort the trees list by x-coordinate first, and then y-coordinate (in case of ties).\n3. Define a helper function cross that takes three points as input and returns the cross product of the vectors formed by the three points.\n4. Build the lower hull using a left-to-right scan. For each point tree in trees, check if the last two points in hull and tree form a right turn (i.e., if the cross product of the two vectors is negative). If they do, remove the second-to-last point in hull and repeat until the last two points in hull and tree form a left turn (i.e., if the cross product of the two vectors is non-negative). Finally, add tree to hull.\n5. Build the upper hull using a right-to-left scan. For each point tree in trees (in reverse order), check if the last two points in hull and tree form a right turn (i.e., if the cross product of the two vectors is negative). If they do, remove the second-to-last point in hull and repeat until the last two points in hull and tree form a left turn (i.e., if the cross product of the two vectors is non-negative). Finally, add tree to hull.\n6. Remove duplicates from hull and return it as a list of lists.\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:\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n hull = []\n\n # Sort trees by x-coordinate first, and then y-coordinate (in case of ties)\n trees.sort(key=lambda x: (x[0], x[1]))\n\n def cross(p: List[int], q: List[int], r: List[int]) -> int:\n # Simplify the cross product calculation using tuple unpacking\n px, py = p\n qx, qy = q\n rx, ry = r\n return (qy - py) * (rx - qx) - (qx - px) * (ry - qy)\n\n # Build lower hull: left-to-right scan\n for tree in trees:\n # Use a while loop instead of a for loop to simplify the code\n while len(hull) > 1 and cross(hull[-2], hull[-1], tree) < 0:\n hull.pop()\n hull.append(tree)\n\n # Build upper hull: right-to-left scan\n for tree in reversed(trees):\n while len(hull) > 1 and cross(hull[-2], hull[-1], tree) < 0:\n hull.pop()\n hull.append(tree)\n\n # Remove duplicates and return the hull as a list of lists\n return [list(x) for x in set(tuple(x) for x in hull)]\n\n```
2
You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden. Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**. Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**. **Example 1:** **Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\] **Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\] **Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence. **Example 2:** **Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\] **Output:** \[\[4,2\],\[2,2\],\[1,2\]\] **Explanation:** The fence forms a line that passes through all the trees. **Constraints:** * `1 <= trees.length <= 3000` * `trees[i].length == 2` * `0 <= xi, yi <= 100` * All the given positions are **unique**.
null
Very Easy || 100% || Fully Explained || Java, C++, Python, Python3 || Iterative & Recursive(DFS)
n-ary-tree-preorder-traversal
1
1
# **Java Solution (Iterative Approach):**\n```\nclass Solution {\n public List<Integer> preorder(Node root) {\n // To store the output array...\n List<Integer> output = new ArrayList<Integer>();\n // Base case: if the tree is empty...\n if (root == null) return output;\n // Create a stack of Node and push root to it...\n Stack<Node> st = new Stack<>();\n st.push(root);\n // Traverse till stack is not empty...\n while (!st.isEmpty()) {\n // Pop a Node from the stack and add it to the output list...\n Node node = st.pop();\n output.add(node.val);\n // Push all of the child nodes of the node into the stack from right to left...\n // Push from right to left to get the right preorder traversal...\n for (int idx = node.children.size() - 1; idx >= 0; idx--) {\n Node child = node.children.get(idx);\n st.push(child);\n }\n }\n return output; // Return the output...\n }\n}\n```\n\n# **C++ Solution (Recursive Approach):**\n```\nclass Solution {\npublic:\n // To store the output result...\n vector<int> output;\n void traverse(Node* root) {\n // Base case: if the tree is empty...\n if(root == NULL) return;\n // Push the value of the root node to the output...\n output.push_back(root->val);\n // Recursively traverse each node in the children array...\n for(auto node:root->children)\n traverse(node);\n }\n vector<int> preorder(Node* root) {\n output.clear();\n traverse(root);\n return output;\n }\n};\n```\n\n# **Python/Python3 Solution (Recursive Approach):**\n```\nclass Solution(object):\n def preorder(self, root):\n # To store the output result...\n output = []\n self.traverse(root, output)\n return output\n def traverse(self, root, output):\n # Base case: If root is none...\n if root is None: return\n # Append the value of the root node to the output...\n output.append(root.val)\n # Recursively traverse each node in the children array...\n for child in root.children:\n self.traverse(child, output)\n```\n \n# **JavaScript Solution (Recursive Approach):**\n```\nvar preorder = function(root, output = []) {\n // Base case: if the tree is empty...\n if (!root) return output\n // Push the value of the root node to the output...\n output.push(root.val)\n // Recursively traverse each node in the children array...\n for (let child of root.children)\n preorder(child, output)\n return output // Return the output result...\n};\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...**
126
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[1,3,5,6,2,4\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Very Easy || 100% || Fully Explained || Java, C++, Python, Python3 || Iterative & Recursive(DFS)
n-ary-tree-preorder-traversal
1
1
# **Java Solution (Iterative Approach):**\n```\nclass Solution {\n public List<Integer> preorder(Node root) {\n // To store the output array...\n List<Integer> output = new ArrayList<Integer>();\n // Base case: if the tree is empty...\n if (root == null) return output;\n // Create a stack of Node and push root to it...\n Stack<Node> st = new Stack<>();\n st.push(root);\n // Traverse till stack is not empty...\n while (!st.isEmpty()) {\n // Pop a Node from the stack and add it to the output list...\n Node node = st.pop();\n output.add(node.val);\n // Push all of the child nodes of the node into the stack from right to left...\n // Push from right to left to get the right preorder traversal...\n for (int idx = node.children.size() - 1; idx >= 0; idx--) {\n Node child = node.children.get(idx);\n st.push(child);\n }\n }\n return output; // Return the output...\n }\n}\n```\n\n# **C++ Solution (Recursive Approach):**\n```\nclass Solution {\npublic:\n // To store the output result...\n vector<int> output;\n void traverse(Node* root) {\n // Base case: if the tree is empty...\n if(root == NULL) return;\n // Push the value of the root node to the output...\n output.push_back(root->val);\n // Recursively traverse each node in the children array...\n for(auto node:root->children)\n traverse(node);\n }\n vector<int> preorder(Node* root) {\n output.clear();\n traverse(root);\n return output;\n }\n};\n```\n\n# **Python/Python3 Solution (Recursive Approach):**\n```\nclass Solution(object):\n def preorder(self, root):\n # To store the output result...\n output = []\n self.traverse(root, output)\n return output\n def traverse(self, root, output):\n # Base case: If root is none...\n if root is None: return\n # Append the value of the root node to the output...\n output.append(root.val)\n # Recursively traverse each node in the children array...\n for child in root.children:\n self.traverse(child, output)\n```\n \n# **JavaScript Solution (Recursive Approach):**\n```\nvar preorder = function(root, output = []) {\n // Base case: if the tree is empty...\n if (!root) return output\n // Push the value of the root node to the output...\n output.push(root.val)\n // Recursively traverse each node in the children array...\n for (let child of root.children)\n preorder(child, output)\n return output // Return the output result...\n};\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...**
126
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The number of **local inversions** is the number of indices `i` where: * `0 <= i < n - 1` * `nums[i] > nums[i + 1]` Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. **Example 1:** **Input:** nums = \[1,0,2\] **Output:** true **Explanation:** There is 1 global inversion and 1 local inversion. **Example 2:** **Input:** nums = \[1,2,0\] **Output:** false **Explanation:** There are 2 global inversions and 1 local inversion. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] < n` * All the integers of `nums` are **unique**. * `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
null
easiest solution 59ms
n-ary-tree-preorder-traversal
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- meet root first.\n- now meet children sub-tree and append value.\n- return ans.\n\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:\n def preorder(self, root: \'Node\') -> List[int]:\n ans = []\n def helper(curr=root):\n nonlocal ans\n if curr:\n ans.append(curr.val)\n for i in curr.children:\n helper(i)\n helper()\n return ans\n```\n# Please like and comment below. :-)
4
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[1,3,5,6,2,4\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
easiest solution 59ms
n-ary-tree-preorder-traversal
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- meet root first.\n- now meet children sub-tree and append value.\n- return ans.\n\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:\n def preorder(self, root: \'Node\') -> List[int]:\n ans = []\n def helper(curr=root):\n nonlocal ans\n if curr:\n ans.append(curr.val)\n for i in curr.children:\n helper(i)\n helper()\n return ans\n```\n# Please like and comment below. :-)
4
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The number of **local inversions** is the number of indices `i` where: * `0 <= i < n - 1` * `nums[i] > nums[i + 1]` Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. **Example 1:** **Input:** nums = \[1,0,2\] **Output:** true **Explanation:** There is 1 global inversion and 1 local inversion. **Example 2:** **Input:** nums = \[1,2,0\] **Output:** false **Explanation:** There are 2 global inversions and 1 local inversion. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] < n` * All the integers of `nums` are **unique**. * `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
null
Python || PreOrder Traversal || Easy To Understand 🔥
n-ary-tree-preorder-traversal
0
1
# Code\n```\nclass Solution:\n def preorder(self, root: \'Node\') -> List[int]:\n arr = []\n def order(root):\n if root is None: return None\n arr.append(root.val)\n for i in root.children:\n order(i) \n order(root)\n return arr\n```
3
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[1,3,5,6,2,4\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Python || PreOrder Traversal || Easy To Understand 🔥
n-ary-tree-preorder-traversal
0
1
# Code\n```\nclass Solution:\n def preorder(self, root: \'Node\') -> List[int]:\n arr = []\n def order(root):\n if root is None: return None\n arr.append(root.val)\n for i in root.children:\n order(i) \n order(root)\n return arr\n```
3
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The number of **local inversions** is the number of indices `i` where: * `0 <= i < n - 1` * `nums[i] > nums[i + 1]` Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. **Example 1:** **Input:** nums = \[1,0,2\] **Output:** true **Explanation:** There is 1 global inversion and 1 local inversion. **Example 2:** **Input:** nums = \[1,2,0\] **Output:** false **Explanation:** There are 2 global inversions and 1 local inversion. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] < n` * All the integers of `nums` are **unique**. * `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
null
BEATS 90% of Submissions, EASY approach
n-ary-tree-preorder-traversal
0
1
# Approach\n\nRecursive solution with a while loop\n\n# Complexity\n- Time complexity: Beats 90%\n\n- Space complexity: Beats 55%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n"""\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n"""\n\nclass Solution:\n def preorder(self, root: \'Node\') -> List[int]:\n\n\n pre = [] #array\n \n def check(node, arr):\n if node == None: #base call 1\n return 0\n \n arr.append(node.val) #add val to list\n\n if node.children == None: #base call 2\n return 0\n \n i = 0\n while i < len(node.children): #recursive call\n check(node.children[i], arr)\n i += 1\n\n check(root, pre)\n return pre\n \n \n\n```
4
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[1,3,5,6,2,4\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
BEATS 90% of Submissions, EASY approach
n-ary-tree-preorder-traversal
0
1
# Approach\n\nRecursive solution with a while loop\n\n# Complexity\n- Time complexity: Beats 90%\n\n- Space complexity: Beats 55%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n"""\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n"""\n\nclass Solution:\n def preorder(self, root: \'Node\') -> List[int]:\n\n\n pre = [] #array\n \n def check(node, arr):\n if node == None: #base call 1\n return 0\n \n arr.append(node.val) #add val to list\n\n if node.children == None: #base call 2\n return 0\n \n i = 0\n while i < len(node.children): #recursive call\n check(node.children[i], arr)\n i += 1\n\n check(root, pre)\n return pre\n \n \n\n```
4
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The number of **local inversions** is the number of indices `i` where: * `0 <= i < n - 1` * `nums[i] > nums[i + 1]` Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. **Example 1:** **Input:** nums = \[1,0,2\] **Output:** true **Explanation:** There is 1 global inversion and 1 local inversion. **Example 2:** **Input:** nums = \[1,2,0\] **Output:** false **Explanation:** There are 2 global inversions and 1 local inversion. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] < n` * All the integers of `nums` are **unique**. * `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
null
python3, simple DFS
n-ary-tree-preorder-traversal
0
1
ERROR: type should be string, got "https://leetcode.com/submissions/detail/869247259/ \\nRuntime: 48 ms, faster than 95.05% of Python3 online submissions for N-ary Tree Preorder Traversal. \\nMemory Usage: 16 MB, less than 97.63% of Python3 online submissions for N-ary Tree Preorder Traversal. \\n```\\n\"\"\"\\n# Definition for a Node.\\nclass Node:\\n def __init__(self, val=None, children=None):\\n self.val = val\\n self.children = children\\n\"\"\"\\nclass Solution:\\n def preorder(self, root: \\'Node\\') -> List[int]:\\n if not root: return\\n vals, l = [], [root]\\n while l:\\n node = l.pop(0)\\n vals.append(node.val)\\n l = node.children + l\\n return vals\\n```"
6
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[1,3,5,6,2,4\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
python3, simple DFS
n-ary-tree-preorder-traversal
0
1
ERROR: type should be string, got "https://leetcode.com/submissions/detail/869247259/ \\nRuntime: 48 ms, faster than 95.05% of Python3 online submissions for N-ary Tree Preorder Traversal. \\nMemory Usage: 16 MB, less than 97.63% of Python3 online submissions for N-ary Tree Preorder Traversal. \\n```\\n\"\"\"\\n# Definition for a Node.\\nclass Node:\\n def __init__(self, val=None, children=None):\\n self.val = val\\n self.children = children\\n\"\"\"\\nclass Solution:\\n def preorder(self, root: \\'Node\\') -> List[int]:\\n if not root: return\\n vals, l = [], [root]\\n while l:\\n node = l.pop(0)\\n vals.append(node.val)\\n l = node.children + l\\n return vals\\n```"
6
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The number of **local inversions** is the number of indices `i` where: * `0 <= i < n - 1` * `nums[i] > nums[i + 1]` Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. **Example 1:** **Input:** nums = \[1,0,2\] **Output:** true **Explanation:** There is 1 global inversion and 1 local inversion. **Example 2:** **Input:** nums = \[1,2,0\] **Output:** false **Explanation:** There are 2 global inversions and 1 local inversion. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] < n` * All the integers of `nums` are **unique**. * `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
null
✔️ Python 2 Easy Way To Solve | 96% Faster | Recursive and Iterative Approach
n-ary-tree-preorder-traversal
0
1
**IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\n**Recursion:**\n\n```\nclass Solution:\n def preorder(self, root: \'Node\') -> List[int]:\n \n def dfs(root, output):\n if not root:\n return None\n output.append(root.val)\n for child in root.children:\n dfs(child, output)\n return output\n \n return dfs(root, [])\n```\n\n**Iterative:**\n```\nclass Solution:\n def preorder(self, root: \'Node\') -> List[int]:\n if not root:\n return []\n stack = [root]\n output = []\n \n while stack:\n top = stack.pop()\n output.append(top.val)\n stack.extend(reversed(top.children))\n \n return output\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/**
20
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[1,3,5,6,2,4\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
✔️ Python 2 Easy Way To Solve | 96% Faster | Recursive and Iterative Approach
n-ary-tree-preorder-traversal
0
1
**IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\n**Recursion:**\n\n```\nclass Solution:\n def preorder(self, root: \'Node\') -> List[int]:\n \n def dfs(root, output):\n if not root:\n return None\n output.append(root.val)\n for child in root.children:\n dfs(child, output)\n return output\n \n return dfs(root, [])\n```\n\n**Iterative:**\n```\nclass Solution:\n def preorder(self, root: \'Node\') -> List[int]:\n if not root:\n return []\n stack = [root]\n output = []\n \n while stack:\n top = stack.pop()\n output.append(top.val)\n stack.extend(reversed(top.children))\n \n return output\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/**
20
You are given an integer array `nums` of length `n` which represents a permutation of all the integers in the range `[0, n - 1]`. The number of **global inversions** is the number of the different pairs `(i, j)` where: * `0 <= i < j < n` * `nums[i] > nums[j]` The number of **local inversions** is the number of indices `i` where: * `0 <= i < n - 1` * `nums[i] > nums[i + 1]` Return `true` _if the number of **global inversions** is equal to the number of **local inversions**_. **Example 1:** **Input:** nums = \[1,0,2\] **Output:** true **Explanation:** There is 1 global inversion and 1 local inversion. **Example 2:** **Input:** nums = \[1,2,0\] **Output:** false **Explanation:** There are 2 global inversions and 1 local inversion. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `0 <= nums[i] < n` * All the integers of `nums` are **unique**. * `nums` is a permutation of all the numbers in the range `[0, n - 1]`.
null
Python || PostOrder Traversal || Easy To Understand 🔥
n-ary-tree-postorder-traversal
0
1
# Code\n```\nclass Solution:\n def postorder(self, root: \'Node\') -> List[int]:\n arr = []\n def order(root):\n if root is None: return None\n for i in root.children:\n order(i) \n arr.append(root.val)\n order(root)\n return arr\n```
1
Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[5,6,3,2,4,1\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Solution
n-ary-tree-postorder-traversal
1
1
```C++ []\nclass Solution {\npublic:\n void post(Node* root,vector<int> &v)\n {\n if(root==NULL)\n return;\n for(auto temp : root->children)\n {\n post(temp,v); \n }\n v.push_back(root->val);\n }\n vector<int> postorder(Node* root) {\n vector<int> v;\n post(root,v);\n return v;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def postorder(self, root: \'Node\') -> List[int]:\n out = []\n\n def helper(node):\n if node:\n for child in node.children:\n helper(child)\n out.append(node.val)\n\n helper(root)\n return out\n```\n\n```Java []\nclass Solution {\n List<Integer> ans= new ArrayList<>(); \n public List<Integer> postorder(Node root) {\n helper(root); \n return ans; \n }\n private void helper (Node root){\n if (root==null) return ; \n for (Node i: root.children){\n helper(i); \n }\n ans.add(root.val); \n }\n}\n```\n
2
Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[5,6,3,2,4,1\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Python3 easiest solution 87% fast
n-ary-tree-postorder-traversal
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- traverse left to right children sub tree.\n- then append root.\n- return ans\n\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:\n def postorder(self, root: \'Node\') -> List[int]:\n ans = []\n def postOrder(curr = root):\n nonlocal ans\n if curr:\n for i in curr.children:\n postOrder(i)\n ans.append(curr.val)\n postOrder()\n return ans\n```\n# Please like and comment below :-)
3
Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[5,6,3,2,4,1\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
590: Time 94.11%, Solution with step by step explanation
n-ary-tree-postorder-traversal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. If the root is None, return an empty list.\n\n2. Initialize a stack called stack with the root node as its only element.\n\n3. Initialize an empty list called res to store the result.\n\n4. While the stack is not empty, pop the top element of the stack and append its value to the res list.\n\n5. For each child of the node, push the child onto the stack.\n\n6. Return the res list in reverse order using slicing.\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:\n def postorder(self, root: \'Node\') -> List[int]:\n if not root:\n return []\n \n stack = [root]\n res = []\n \n while stack:\n node = stack.pop()\n res.append(node.val)\n \n for child in node.children:\n stack.append(child)\n \n return res[::-1]\n\n```
3
Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[5,6,3,2,4,1\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Both iterative and recursive | Faster than 95% | Easy to Understand | Simple | Python
n-ary-tree-postorder-traversal
0
1
```\n def iterative(self, root):\n if not root: return []\n stack = [root]\n out = []\n while len(stack):\n top = stack.pop()\n out.append(top.val)\n stack.extend(top.children or [])\n return out[::-1]\n \n \n```\n\t\t\t\n\t\t\t\n \n def recursive(self, root):\n def rec(root):\n if root:\n for c in root.children:\n rec(c)\n out.append(root.val)\n \n out = []\n rec(root)\n return out\n\t\t\n\t\t\n**I hope that you\'ve found them useful.**\n*Please do upvote, it only motivates me to write more such post\uD83D\uDE03*
33
Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[5,6,3,2,4,1\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Python3 || easy method uses
n-ary-tree-postorder-traversal
0
1
\t\ttraversal = list()\n \n if root:\n for child in root.children:\n traversal+=self.postorder(child)\n \n traversal.append(root.val)\n \n return traversal
4
Given the `root` of an n-ary tree, return _the postorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[5,6,3,2,4,1\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[2,6,14,11,7,3,12,8,4,13,9,10,5,1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Solution
tag-validator
1
1
```C++ []\nclass Solution {\npublic:\n bool isValid(string code) {\n int i = 0;\n return validTag(code, i) && i == code.size();\n }\nprivate:\n bool validTag(string s, int& i) {\n int j = i;\n string tag = parseTagName(s, j);\n if (tag.empty()) return false;\n if (!validContent(s, j)) return false;\n int k = j + tag.size() + 2; // expecting j = pos of "</" , k = pos of \'>\'\n if (k >= s.size() || s.substr(j, k + 1 - j) != "</" + tag + ">") return false;\n i = k + 1;\n return true;\n }\n string parseTagName(string s, int& i) {\n if (s[i] != \'<\') return "";\n int j = s.find(\'>\', i);\n if (j == string::npos || j - 1 - i < 1 || 9 < j - 1 - i) return "";\n string tag = s.substr(i + 1, j - 1 - i);\n for (char ch : tag) {\n if (ch < \'A\' || \'Z\' < ch) return "";\n }\n i = j + 1;\n return tag;\n }\n bool validContent(string s, int& i) {\n int j = i;\n while (j < s.size()) {\n if (!validText(s, j) && !validCData(s, j) && !validTag(s, j)) break;\n }\n i = j;\n return true;\n }\n bool validText(string s, int& i) {\n int j = i;\n while (i < s.size() && s[i] != \'<\') { i++; }\n return i != j;\n }\n bool validCData(string s, int& i) {\n if (s.find("<![CDATA[", i) != i) return false;\n int j = s.find("]]>", i);\n if (j == string::npos) return false;\n i = j + 3;\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def isValid(self, code: str) -> bool:\n tags = []\n i = 0\n while i < len(code):\n if i > 0 and len(tags) == 0:\n return False\n elif code.startswith("<![CDATA[", i):\n j = code.find("]]>", i)\n if j == -1:\n return False\n i = j + len("]]>")\n elif code.startswith("</", i):\n j = code.find(\'>\', i)\n if j == -1:\n return False\n tag_tail = code[i+2:j]\n if tags and tags[-1] == tag_tail:\n i = j + 1\n tags.pop()\n else:\n return False\n elif code[i] == \'<\':\n j = code.find(\'>\', i)\n if j == -1: \n return False\n tag_head = code[i+1:j]\n if 1 <= len(tag_head) <= 9 and tag_head.isupper() and tag_head.isalpha():\n tags.append(tag_head)\n i = j + 1\n else:\n return False\n else:\n i += 1\n return len(tags) == 0\n```\n\n```Java []\nclass Solution {\n public boolean isValid(String exp) {\n int length = exp.length();\n Stack S=new Stack();\n for (int i = 0; i < length; i++) {\n if(i>0 && S.empty())\n return false;\n if(exp.startsWith("<![CDATA[",i)){\n int pos=exp.indexOf("]]>",i+9);\n if (pos==-1)\n return false;\n else\n i=pos+2;\n }\n else if(exp.startsWith("</",i)){\n int pos=exp.indexOf(\'>\',i+2);\n if (pos==-1) {\n return false;\n }\n String to_be_matched=exp.substring(i+2,pos);\n if(S.empty())\n return false;\n if(!to_be_matched.equals((String)S.pop()))\n return false;\n i=pos;\n }\n else if (exp.charAt(i) == \'<\') {\n int pos=exp.indexOf(\'>\',i+1);\n if (pos==-1)\n return false;\n String to_be_pushed=exp.substring(i+1, pos);\n if(!(to_be_pushed.length() >=1 && to_be_pushed.length() <=9))\n return false;\n for(int k=0;k<to_be_pushed.length();k++) {\n char temp = to_be_pushed.charAt(k);\n if (!(temp >= 65 && temp <= 90))\n return false;\n }\n S.push(to_be_pushed);\n i=pos;\n }\n else\n {\n int pos=exp.indexOf(\'<\',i);\n if (pos!=-1) {\n i=pos-1;\n }\n }\n }\n if(S.empty())\n return true;\n else\n return false;\n }\n}\n```\n
1
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: 1. The code must be wrapped in a **valid closed tag**. Otherwise, the code is invalid. 2. A **closed tag** (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, is the start tag, and is the end tag. The TAG\_NAME in start and end tags should be the same. A closed tag is **valid** if and only if the TAG\_NAME and TAG\_CONTENT are valid. 3. A **valid** `TAG_NAME` only contain **upper-case letters**, and has length in range \[1,9\]. Otherwise, the `TAG_NAME` is **invalid**. 4. A **valid** `TAG_CONTENT` may contain other **valid closed tags**, **cdata** and any characters (see note1) **EXCEPT** unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG\_NAME. Otherwise, the `TAG_CONTENT` is **invalid**. 5. A start tag is unmatched if no end tag exists with the same TAG\_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. 6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or ``, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).`` ``` * The cdata has the following format : . The range of `CDATA_CONTENT` is defined as the characters between ``and the **first subsequent** `]]>`.`` ``* `CDATA_CONTENT` may contain **any characters**. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as **regular characters**.`` ``` ``` `` **Example 1:** **Input:** code = " This is the first line ]]> " **Output:** true **Explanation:** The code is wrapped in a closed tag : and . The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. **Example 2:** **Input:** code = " >> ![cdata[]] ]>]]>]]>>] " **Output:** true **Explanation:** We first separate the code into : start_tag|tag_content|end_tag. start_tag -> ** "** **"** end_tag -> ** "** **"** tag_content could also be separated into : text1|cdata|text2. text1 -> ** ">> ![cdata[]] "** cdata -> ** "]>]]> "**, where the CDATA_CONTENT is ** "** **]> "** text2 -> ** "]]>>] "** The reason why start_tag is NOT ** "** **>> "** is because of the rule 6. The reason why cdata is NOT ** "]>]]>]]> "** is because of the rule 7. **Example 3:** **Input:** code = " " **Output:** false **Explanation:** Unbalanced. If " " is closed, then " **" must be unmatched, and vice versa.** ** **Constraints:** * `1 <= code.length <= 500` * `code` consists of English letters, digits, `'<'`, `'>'`, `'/'`, `'!'`, `'['`, `']'`, `'.'`, and `' '`. **`` ```
null
591: Solution with step by step explanation
tag-validator
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. The function starts by checking if the input code starts and ends with \'<\' and \'>\', respectively. If it does not, it returns False since code must contain at least one tag.\n\n2. The function initializes two variables: containsTag and stack. containsTag is a flag that is set to True if code contains at least one tag. stack is a list that will be used to keep track of the tags that have been opened but not closed yet.\n\n3. Two helper functions are defined: isValidCdata and isValidTagName. isValidCdata checks if a given string is a valid CDATA section, which starts with \'<![CDATA[\' and ends with \']]>\'. isValidTagName checks if a given tag name is valid. A tag name is valid if it is not empty, has a length of at most 9 characters, and all characters are uppercase. If isEndTag is True, it also checks if the corresponding start tag is at the top of the stack.\n\n4. The function loops through each character in code. If the stack is empty and containsTag is True, it means that code contains a tag that has not been closed yet, so the function returns False.\n\n5. If the current character is \'<\', the function checks if it is a CDATA section, an end tag, or a start tag. If it is a CDATA section, the function checks if it is valid by looking for the closing \']]>\' sequence. If it is an end tag, the function checks if it is valid by looking for the corresponding start tag at the top of the stack. If it is a start tag, the function checks if it is valid by looking for the closing \'>\' character. If any of these checks fail, the function returns False.\n\n6. If the current character is not \'<\', the function moves on to the next character.\n\n7. If the function reaches the end of code and the stack is not empty, it means that some tags were not closed, so the function returns False.\n\n8. If the function reaches the end of code and containsTag is False, it means that code did not contain any tags, so the function returns False.\n\n9. If none of the above conditions are met, it means that code is valid, so the function returns True.\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:\n def isValid(self, code: str) -> bool:\n if code[0] != \'<\' or code[-1] != \'>\':\n return False\n containsTag = False # Flag to check if code contains a tag\n stack = [] # Stack to keep track of tags\n\n def isValidCdata(s: str) -> bool: # Check if a given string is valid CDATA\n return s.find(\'[CDATA[\') == 0\n\n def isValidTagName(tagName: str, isEndTag: bool) -> bool: # Check if a given tag name is valid\n nonlocal containsTag\n if not tagName or len(tagName) > 9: # Check tag name length\n return False\n if any(not c.isupper() for c in tagName): # Check if all characters in tag name are uppercase\n return False\n\n if isEndTag: # Check if end tag is valid\n return stack and stack.pop() == tagName\n\n containsTag = True # Set flag to True\n stack.append(tagName) # Push tag to stack\n return True\n\n i = 0\n while i < len(code):\n if not stack and containsTag: # If stack is empty but code contains a tag, return False\n return False\n if code[i] == \'<\':\n if stack and code[i + 1] == \'!\': # Check if CDATA\n closeIndex = code.find(\']]>\', i + 2)\n if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]): # Check if CDATA is valid\n return False\n elif code[i + 1] == \'/\': # Check if end tag\n closeIndex = code.find(\'>\', i + 2)\n if closeIndex == -1 or not isValidTagName(code[i + 2:closeIndex], True): # Check if end tag is valid\n return False\n else: # Check if start tag\n closeIndex = code.find(\'>\', i + 1)\n if closeIndex == -1 or not isValidTagName(code[i + 1:closeIndex], False): # Check if start tag is valid\n return False\n i = closeIndex # Set index to end of tag\n i += 1\n\n return not stack and containsTag # Check if stack is empty and code contains a tag\n\n```
3
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: 1. The code must be wrapped in a **valid closed tag**. Otherwise, the code is invalid. 2. A **closed tag** (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, is the start tag, and is the end tag. The TAG\_NAME in start and end tags should be the same. A closed tag is **valid** if and only if the TAG\_NAME and TAG\_CONTENT are valid. 3. A **valid** `TAG_NAME` only contain **upper-case letters**, and has length in range \[1,9\]. Otherwise, the `TAG_NAME` is **invalid**. 4. A **valid** `TAG_CONTENT` may contain other **valid closed tags**, **cdata** and any characters (see note1) **EXCEPT** unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG\_NAME. Otherwise, the `TAG_CONTENT` is **invalid**. 5. A start tag is unmatched if no end tag exists with the same TAG\_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. 6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or ``, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).`` ``` * The cdata has the following format : . The range of `CDATA_CONTENT` is defined as the characters between ``and the **first subsequent** `]]>`.`` ``* `CDATA_CONTENT` may contain **any characters**. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as **regular characters**.`` ``` ``` `` **Example 1:** **Input:** code = " This is the first line ]]> " **Output:** true **Explanation:** The code is wrapped in a closed tag : and . The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. **Example 2:** **Input:** code = " >> ![cdata[]] ]>]]>]]>>] " **Output:** true **Explanation:** We first separate the code into : start_tag|tag_content|end_tag. start_tag -> ** "** **"** end_tag -> ** "** **"** tag_content could also be separated into : text1|cdata|text2. text1 -> ** ">> ![cdata[]] "** cdata -> ** "]>]]> "**, where the CDATA_CONTENT is ** "** **]> "** text2 -> ** "]]>>] "** The reason why start_tag is NOT ** "** **>> "** is because of the rule 6. The reason why cdata is NOT ** "]>]]>]]> "** is because of the rule 7. **Example 3:** **Input:** code = " " **Output:** false **Explanation:** Unbalanced. If " " is closed, then " **" must be unmatched, and vice versa.** ** **Constraints:** * `1 <= code.length <= 500` * `code` consists of English letters, digits, `'<'`, `'>'`, `'/'`, `'!'`, `'['`, `']'`, `'.'`, and `' '`. **`` ```
null
py3 solution beats 50%+
tag-validator
0
1
# 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**class Solution:\n def isValid(self, code: str) -> bool:\n if code[0] != \'<\' or code[-1] != \'>\':\n return False\n containsTag = False # Flag to check if code contains a tag\n stack = [] # Stack to keep track of tags\n\n def isValidCdata(s: str) -> bool: # Check if a given string is valid CDATA\n return s.find(\'[CDATA[\') == 0\n\n def isValidTagName(tagName: str, isEndTag: bool) -> bool: # Check if a given tag name is valid\n nonlocal containsTag\n if not tagName or len(tagName) > 9: # Check tag name length\n return False\n if any(not c.isupper() for c in tagName): # Check if all characters in tag name are uppercase\n return False\n\n if isEndTag: # Check if end tag is valid\n return stack and stack.pop() == tagName\n\n containsTag = True # Set flag to True\n stack.append(tagName) # Push tag to stack\n return True\n\n i = 0\n while i < len(code):\n if not stack and containsTag: # If stack is empty but code contains a tag, return False\n return False\n if code[i] == \'<\':\n if stack and code[i + 1] == \'!\': # Check if CDATA\n closeIndex = code.find(\']]>\', i + 2)\n if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]): # Check if CDATA is valid\n return False\n elif code[i + 1] == \'/\': # Check if end tag\n closeIndex = code.find(\'>\', i + 2)\n if closeIndex == -1 or not isValidTagName(code[i + 2:closeIndex], True): # Check if end tag is valid\n return False\n else: # Check if start tag\n closeIndex = code.find(\'>\', i + 1)\n if closeIndex == -1 or not isValidTagName(code[i + 1:closeIndex], False): # Check if start tag is valid\n return False\n i = closeIndex # Set index to end of tag\n i += 1\n\n return not stack and containsTag # Check if stack is empty and code contains a tag**\n```
0
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: 1. The code must be wrapped in a **valid closed tag**. Otherwise, the code is invalid. 2. A **closed tag** (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, is the start tag, and is the end tag. The TAG\_NAME in start and end tags should be the same. A closed tag is **valid** if and only if the TAG\_NAME and TAG\_CONTENT are valid. 3. A **valid** `TAG_NAME` only contain **upper-case letters**, and has length in range \[1,9\]. Otherwise, the `TAG_NAME` is **invalid**. 4. A **valid** `TAG_CONTENT` may contain other **valid closed tags**, **cdata** and any characters (see note1) **EXCEPT** unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG\_NAME. Otherwise, the `TAG_CONTENT` is **invalid**. 5. A start tag is unmatched if no end tag exists with the same TAG\_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. 6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or ``, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).`` ``` * The cdata has the following format : . The range of `CDATA_CONTENT` is defined as the characters between ``and the **first subsequent** `]]>`.`` ``* `CDATA_CONTENT` may contain **any characters**. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as **regular characters**.`` ``` ``` `` **Example 1:** **Input:** code = " This is the first line ]]> " **Output:** true **Explanation:** The code is wrapped in a closed tag : and . The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. **Example 2:** **Input:** code = " >> ![cdata[]] ]>]]>]]>>] " **Output:** true **Explanation:** We first separate the code into : start_tag|tag_content|end_tag. start_tag -> ** "** **"** end_tag -> ** "** **"** tag_content could also be separated into : text1|cdata|text2. text1 -> ** ">> ![cdata[]] "** cdata -> ** "]>]]> "**, where the CDATA_CONTENT is ** "** **]> "** text2 -> ** "]]>>] "** The reason why start_tag is NOT ** "** **>> "** is because of the rule 6. The reason why cdata is NOT ** "]>]]>]]> "** is because of the rule 7. **Example 3:** **Input:** code = " " **Output:** false **Explanation:** Unbalanced. If " " is closed, then " **" must be unmatched, and vice versa.** ** **Constraints:** * `1 <= code.length <= 500` * `code` consists of English letters, digits, `'<'`, `'>'`, `'/'`, `'!'`, `'['`, `']'`, `'.'`, and `' '`. **`` ```
null
Using Regex to parse & validate code
tag-validator
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nUse regex to parse & validate `code`\n# Code\n```\nfrom ast import Tuple\nimport re\nfrom typing import List\n\ndebug = False\n\nopen_or_close_tag_regex = re.compile(r"<[A-Za-z]*>|<\\/[A-Za-z]*>")\nopen_tag_regex = re.compile(r"<[A-Za-z]*>")\nclose_tag_regex = re.compile(r"<\\/[A-Za-z]*>")\ntag_regex = re.compile(r"(<[A-Z]*>)(.*)(<\\/[A-Z]*>)")\n\nu_open_tag_regex = re.compile(r"<[A-Z]*>")\nu_close_tag_regex = re.compile(r"<\\/[A-Z]*>")\n\n\ndef check_tag_name(tag: str):\n tag_name: str = tag.replace("<", "").replace(">", "").replace("/", "")\n if not tag_name.isupper():\n return False\n if len(tag_name) > 9 or len(tag_name) < 1:\n return False\n\n return True\n # return u_close_tag_regex.match(tag) or u_open_tag_regex.match(tag)\n\n\ndef check_tag_content(tag_content: str) -> bool:\n str_output = re.sub(r"<!\\[CDATA\\[.*\\]\\]>", "", tag_content)\n debug and print(f"NORMALIZE TAG CONTENT: {str_output}")\n\n if bool(tag_regex.findall(tag_content)):\n return True\n\n if "<" in str_output:\n return False\n\n return True\n\n\ndef normalize_cdata(code: str) -> str:\n code = code.strip()\n if "<![CDATA" in code:\n cdata_idxes: List[int] = [m.start() for m in re.finditer(r"<!\\[CDATA", code)]\n cdata_idxes.reverse()\n debug and print(f"CDATA INDEXES: {cdata_idxes}")\n cdata_parts: List[str] = []\n for idx, cdata_idx in enumerate(cdata_idxes):\n part_cdata = code[cdata_idx:]\n if idx >= 1:\n part_cdata = code[cdata_idx : cdata_idxes[idx - 1]]\n n_cdata: str = re.sub(r"<!\\[CDATA\\[.*\\]\\]>", "<![CDATA[abc]]>", part_cdata)\n\n debug and print(f\'PART DATA: "{part_cdata}" to "{n_cdata}"\')\n\n cdata_parts.append(n_cdata)\n\n cdata_parts.reverse()\n debug and print(f"CDATA PARTS: {cdata_parts}")\n\n code = code[: cdata_idxes[-1]] + "".join(cdata_parts)\n\n return code\n\n\ndef check_code(code: str) -> bool:\n code = normalize_cdata(code)\n\n debug and print(f"CHECK CODE: {code}")\n tags: List[str] = open_or_close_tag_regex.findall(code)\n index_tags: List[Tuple[int, int]] = [\n (m.start(0), m.end(0)) for m in re.finditer(open_or_close_tag_regex, code)\n ]\n\n debug and print(f"TAGS: {tags}")\n debug and print(f"INDEX TAGS: {index_tags}")\n\n if code and not tags:\n return False\n\n if index_tags[0][0] != 0 or index_tags[-1][-1] != len(code):\n return False\n # NOTE: None data\n # if index_tags[0][1] == index_tags[-1][0]:\n # return False\n\n tag_stack = []\n tag_index_stack = []\n for idx, tag in enumerate(tags):\n if not check_tag_name(tag):\n return False\n\n if close_tag_regex.match(tag):\n if not tag_stack or tag.replace("/", "") != tag_stack[-1]:\n debug and print("ONE")\n return False\n\n c_tag: str = code[tag_index_stack[-1][1] : index_tags[idx][0]]\n debug and print(f\'CONTENT BETWEEN "{tag}" - "{tag_stack[-1]}": "{c_tag}"\')\n if not check_tag_content(c_tag.strip()):\n debug and print(f"TWO: {c_tag}")\n return False\n\n tag_stack.pop()\n tag_index_stack.pop()\n\n if not tag_stack and idx < len(tags) - 1:\n debug and print("THREE")\n return False\n\n elif open_tag_regex.match(tag):\n tag_stack.append(tag)\n tag_index_stack.append(index_tags[idx])\n\n return not tag_stack\n\n\nclass Solution:\n def isValid(self, code: str) -> bool:\n return check_code(code)\n\n # tag_stack = []\n # tags = tag_regex.findall(code)\n # for tag in tags:\n # print(f"TAG: {tag}")\n # if close_tag_regex.match(tag):\n # # CLOSE TAG\n # if not tag_stack or tag.replace("/", "") != tag_stack[-1]:\n # return False\n\n # tag_stack.pop()\n # elif open_tag_regex.match(tag):\n # # OPENT TAG\n # tag_stack.append(tag)\n\n # return not tag_stack\n\n\n```
0
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: 1. The code must be wrapped in a **valid closed tag**. Otherwise, the code is invalid. 2. A **closed tag** (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, is the start tag, and is the end tag. The TAG\_NAME in start and end tags should be the same. A closed tag is **valid** if and only if the TAG\_NAME and TAG\_CONTENT are valid. 3. A **valid** `TAG_NAME` only contain **upper-case letters**, and has length in range \[1,9\]. Otherwise, the `TAG_NAME` is **invalid**. 4. A **valid** `TAG_CONTENT` may contain other **valid closed tags**, **cdata** and any characters (see note1) **EXCEPT** unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG\_NAME. Otherwise, the `TAG_CONTENT` is **invalid**. 5. A start tag is unmatched if no end tag exists with the same TAG\_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. 6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or ``, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).`` ``` * The cdata has the following format : . The range of `CDATA_CONTENT` is defined as the characters between ``and the **first subsequent** `]]>`.`` ``* `CDATA_CONTENT` may contain **any characters**. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as **regular characters**.`` ``` ``` `` **Example 1:** **Input:** code = " This is the first line ]]> " **Output:** true **Explanation:** The code is wrapped in a closed tag : and . The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. **Example 2:** **Input:** code = " >> ![cdata[]] ]>]]>]]>>] " **Output:** true **Explanation:** We first separate the code into : start_tag|tag_content|end_tag. start_tag -> ** "** **"** end_tag -> ** "** **"** tag_content could also be separated into : text1|cdata|text2. text1 -> ** ">> ![cdata[]] "** cdata -> ** "]>]]> "**, where the CDATA_CONTENT is ** "** **]> "** text2 -> ** "]]>>] "** The reason why start_tag is NOT ** "** **>> "** is because of the rule 6. The reason why cdata is NOT ** "]>]]>]]> "** is because of the rule 7. **Example 3:** **Input:** code = " " **Output:** false **Explanation:** Unbalanced. If " " is closed, then " **" must be unmatched, and vice versa.** ** **Constraints:** * `1 <= code.length <= 500` * `code` consists of English letters, digits, `'<'`, `'>'`, `'/'`, `'!'`, `'['`, `']'`, `'.'`, and `' '`. **`` ```
null
py
tag-validator
0
1
# 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:\n def isValid(self, code: str) -> bool:\n if code[0] != \'<\' or code[-1] != \'>\':\n return False\n\n containsTag = False\n stack = []\n\n def isValidCdata(s: str) -> bool:\n return s.find(\'[CDATA[\') == 0\n\n def isValidTagName(tagName: str, isEndTag: bool) -> bool:\n nonlocal containsTag\n if not tagName or len(tagName) > 9:\n return False\n if any(not c.isupper() for c in tagName):\n return False\n\n if isEndTag:\n return stack and stack.pop() == tagName\n\n containsTag = True\n stack.append(tagName)\n return True\n\n i = 0\n while i < len(code):\n if not stack and containsTag:\n return False\n if code[i] == \'<\':\n # Inside a tag, so we can check if it\'s a cdata\n if stack and code[i + 1] == \'!\':\n closeIndex = code.find(\']]>\', i + 2)\n if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]):\n return False\n elif code[i + 1] == \'/\': # End tag\n closeIndex = code.find(\'>\', i + 2)\n if closeIndex == -1 or not isValidTagName(code[i + 2:closeIndex], True):\n return False\n else: # Start tag\n closeIndex = code.find(\'>\', i + 1)\n if closeIndex == -1 or not isValidTagName(code[i + 1:closeIndex], False):\n return False\n i = closeIndex\n i += 1\n\n return not stack and containsTag\n\n```
0
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: 1. The code must be wrapped in a **valid closed tag**. Otherwise, the code is invalid. 2. A **closed tag** (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, is the start tag, and is the end tag. The TAG\_NAME in start and end tags should be the same. A closed tag is **valid** if and only if the TAG\_NAME and TAG\_CONTENT are valid. 3. A **valid** `TAG_NAME` only contain **upper-case letters**, and has length in range \[1,9\]. Otherwise, the `TAG_NAME` is **invalid**. 4. A **valid** `TAG_CONTENT` may contain other **valid closed tags**, **cdata** and any characters (see note1) **EXCEPT** unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG\_NAME. Otherwise, the `TAG_CONTENT` is **invalid**. 5. A start tag is unmatched if no end tag exists with the same TAG\_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. 6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or ``, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).`` ``` * The cdata has the following format : . The range of `CDATA_CONTENT` is defined as the characters between ``and the **first subsequent** `]]>`.`` ``* `CDATA_CONTENT` may contain **any characters**. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as **regular characters**.`` ``` ``` `` **Example 1:** **Input:** code = " This is the first line ]]> " **Output:** true **Explanation:** The code is wrapped in a closed tag : and . The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. **Example 2:** **Input:** code = " >> ![cdata[]] ]>]]>]]>>] " **Output:** true **Explanation:** We first separate the code into : start_tag|tag_content|end_tag. start_tag -> ** "** **"** end_tag -> ** "** **"** tag_content could also be separated into : text1|cdata|text2. text1 -> ** ">> ![cdata[]] "** cdata -> ** "]>]]> "**, where the CDATA_CONTENT is ** "** **]> "** text2 -> ** "]]>>] "** The reason why start_tag is NOT ** "** **>> "** is because of the rule 6. The reason why cdata is NOT ** "]>]]>]]> "** is because of the rule 7. **Example 3:** **Input:** code = " " **Output:** false **Explanation:** Unbalanced. If " " is closed, then " **" must be unmatched, and vice versa.** ** **Constraints:** * `1 <= code.length <= 500` * `code` consists of English letters, digits, `'<'`, `'>'`, `'/'`, `'!'`, `'['`, `']'`, `'.'`, and `' '`. **`` ```
null
Two Python Solution:(1) linear paring with stack;(2)BNF parsing with pyparsing
tag-validator
0
1
Solution 1:\n```\nclass Solution:\n def isValid(self, code: str) -> bool:\n if code[0] != \'<\' or code[-1] != \'>\': return False\n i, n = 0, len(code)\n stk = []\n while i < n:\n if code[i] == \'<\':\n if i != 0 and code[i: i + 9] == \'<![CDATA[\':\n if not stk: return False\n j = i + 9\n while j + 3 <= n and code[j: j + 3] != \']]>\': j += 1\n if code[j: j + 3] == \']]>\': i = j + 3\n else: return False\n else:\n start = i\n isend = False\n i += 1\n if i >= n: return False\n if code[i] == r\'/\':\n isend = True\n i += 1\n if i >= n: return False\n tag = \'\'\n while i < n and code[i] != \'>\':\n if not code[i].isupper(): return False\n tag += code[i]\n i += 1\n if i >= n or len(tag) == 0 or len(tag) > 9: return False\n if isend:\n if not stk or stk[-1] != tag: return False\n stk.pop(-1)\n else:\n if start != 0 and not stk: return False\n stk.append(tag)\n i += 1\n else:\n if not stk: return False\n while i < n and code[i] != \'<\': i += 1\n return not stk\n```\n\n\nSolution 2:\n```\nfrom string import printable\nfrom pyparsing import alphas, Word, Forward, Regex, OneOrMore\n\n\nclass Solution:\n def isValid(self, code: str) -> bool:\n tags = []\n cdata = Regex(r\'<!\\[CDATA\\[.*\\]\\]>\').setName(\'cdata\')\n closed_tag = Forward().setName(\'closed_tag\')\n plain_tag_content = Word(printable, excludeChars=[\'<\']).setName(\'plain_tag_content\')\n tag_content = OneOrMore(closed_tag | plain_tag_content | cdata).setName(\'tag_content\')\n begin_tag = Word(alphas.upper(), min=1, max=9).setName(\'begin_tag\').setParseAction(lambda t: tags.append((1, t[0])))\n end_tag = Word(alphas.upper(), min=1, max=9).setName(\'end_tag\').setParseAction(lambda t: tags.append((2, t[0])))\n closed_tag << \'<\' + begin_tag + \'>\' + tag_content + \'</\' + end_tag + \'>\'\n closed_tag.debug = True\n try:\n closed_tag.parseString(code, parseAll=True)\n except Exception:\n return False\n stk = []\n for flag, tag in tags:\n if flag == 1: stk.append(tag)\n else:\n if not stk or stk[-1] != tag: return False\n stk.pop(-1)\n return True\n```
1
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: 1. The code must be wrapped in a **valid closed tag**. Otherwise, the code is invalid. 2. A **closed tag** (not necessarily valid) has exactly the following format : `TAG_CONTENT`. Among them, is the start tag, and is the end tag. The TAG\_NAME in start and end tags should be the same. A closed tag is **valid** if and only if the TAG\_NAME and TAG\_CONTENT are valid. 3. A **valid** `TAG_NAME` only contain **upper-case letters**, and has length in range \[1,9\]. Otherwise, the `TAG_NAME` is **invalid**. 4. A **valid** `TAG_CONTENT` may contain other **valid closed tags**, **cdata** and any characters (see note1) **EXCEPT** unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG\_NAME. Otherwise, the `TAG_CONTENT` is **invalid**. 5. A start tag is unmatched if no end tag exists with the same TAG\_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. 6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or ``, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid).`` ``` * The cdata has the following format : . The range of `CDATA_CONTENT` is defined as the characters between ``and the **first subsequent** `]]>`.`` ``* `CDATA_CONTENT` may contain **any characters**. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as **regular characters**.`` ``` ``` `` **Example 1:** **Input:** code = " This is the first line ]]> " **Output:** true **Explanation:** The code is wrapped in a closed tag : and . The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag. So TAG_CONTENT is valid, and then the code is valid. Thus return true. **Example 2:** **Input:** code = " >> ![cdata[]] ]>]]>]]>>] " **Output:** true **Explanation:** We first separate the code into : start_tag|tag_content|end_tag. start_tag -> ** "** **"** end_tag -> ** "** **"** tag_content could also be separated into : text1|cdata|text2. text1 -> ** ">> ![cdata[]] "** cdata -> ** "]>]]> "**, where the CDATA_CONTENT is ** "** **]> "** text2 -> ** "]]>>] "** The reason why start_tag is NOT ** "** **>> "** is because of the rule 6. The reason why cdata is NOT ** "]>]]>]]> "** is because of the rule 7. **Example 3:** **Input:** code = " " **Output:** false **Explanation:** Unbalanced. If " " is closed, then " **" must be unmatched, and vice versa.** ** **Constraints:** * `1 <= code.length <= 500` * `code` consists of English letters, digits, `'<'`, `'>'`, `'/'`, `'!'`, `'['`, `']'`, `'.'`, and `' '`. **`` ```
null
100% WORKING || EASY PYTHON3 SOLUTION || USING THE SIMPLEST MATHEMATICAL APPROACH
fraction-addition-and-subtraction
0
1
# Approach\nIn this approach, what we are doing is listed below step by step:\n1. Firstly we need to import the required libraries\n2. After that, we need to extract the denominator of each term involved in the expression. Using regex, we retrieved and stored it in a list. You can also pass that list directly to the lcm function.\n3. After that, we find the least common multiple (LCM) of all the denominators obtained earlier. This LCM serves as the limit_denominator in the rational-to-fractional conversion.\n4. Finally, we simplified our rational solution (obtained using the evaluate function) into the form of a fractional solution and returned it in the numerator/denominator format.\n\n\n# Code\n```\nfrom fractions import Fraction\nfrom re import findall\nfrom math import lcm\n\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n ln = list(map(int, re.findall(r"\\/(\\w+)+",expression)))\n lm = lcm(*ln)\n m = Fraction(str(eval(expression))).limit_denominator(lm)\n return f"{m.numerator}/{m.denominator}"\n\n\n```
2
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
✅Easy Brute Force Solution✅
fraction-addition-and-subtraction
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code is designed to add fractions together and simplify the result to its simplest form. It handles both positive and negative fractions, and its goal is to perform this addition and provide the result as a simplified fraction.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe input expression is split into a list of strings, where each string represents a fraction to be added. The fractions are separated by the \'+\' sign.\nThe code then iterates through this list, parsing each fraction by splitting it based on the \'/\' character.\nWhile parsing each fraction, it keeps track of the numerators and denominators separately.\nThe code applies a sign depending on whether a \'-\' sign is present within the fraction.\nThe Least Common Denominator (LCD) is calculated for all denominators in the list using the reduce function from the functools module.\nOnce the LCD is determined, each numerator is adjusted to have a common denominator by multiplying it by (d//abs(denominator[i])), ensuring that all fractions have the same denominator.\nThe code sums up all the numerators to get the new numerator for the result.\nIt calculates the greatest common divisor (GCD) of the numerator and denominator using the math.gcd function.\nFinally, the code simplifies the fraction by dividing both the numerator and denominator by their GCD to get the simplest form of the result.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSplitting the input expression by \'+\' characters and then iterating through the list of fractions takes O(n) time, where n is the length of the expression.\nWithin the iteration, parsing each fraction also takes O(n) time.\nCalculating the Least Common Denominator (LCD) using the reduce function takes O(n) time, as it iterates through the list of denominators.\nAdjusting numerators for a common denominator and summing them up also takes O(n) time.\nCalculating the greatest common divisor (GCD) using the math.gcd function takes O(n) time.\nOverall, the time complexity of the code is O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is influenced by the data structures used to store fractions (numerators and denominators), the list of fractions, and other variables.\nThe space used to store fractions and the list of fractions is O(n) in the worst case because they grow linearly with the input length.\nOther variables used for temporary calculations, such as the LCD, numerators, denominators, and the result, do not significantly impact the space complexity.\nTherefore, the overall space complexity is O(n) due to the storage of fractions and the list of fractions.\n\n\u2B06**IF IT FIND\'S HELPFUL PLAESE UPVOTE**\u2B06\n# Code\n```\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n l = expression.split(\'+\')\n\n num = []\n dum = []\n for i in l:\n temp = i.split(\'/\')\n n= True\n\n for i in temp:\n if \'-\' in i and len(i)>2 and i.index(\'-\')>0:\n index = i.index(\'-\')\n\n dum.append(int(i[:index]))\n num.append(int(i[index:]))\n n=False\n else:\n if n:\n num.append(int(i))\n n = False\n else:\n dum.append(int(i))\n n=True\n d = reduce(math.lcm, dum)\n for i in range(len(num)):\n num[i] = num[i]*(d//abs(dum[i]))\n n = sum(num)\n return str(n//gcd(n,d))+"/"+str(d//gcd(n,d))\n```\n\u2B06**IF IT FIND\'S HELPFUL PLAESE UPVOTE**\u2B06
1
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
Solution
fraction-addition-and-subtraction
1
1
```C++ []\nclass Solution {\n public:\n string fractionAddition(string expression) {\n istringstream iss(expression);\n char _;\n int a;\n int b;\n int A = 0;\n int B = 1;\n\n while (iss >> a >> _ >> b) {\n A = A * b + a * B;\n B *= b;\n const int g = abs(__gcd(A, B));\n A /= g;\n B /= g;\n }\n return to_string(A) + "/" + to_string(B);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n pattern = re.compile(r"(.*?)([0-9]+)/([0-9]+)")\n triplets = pattern.findall(expression)\n\n num = 0\n den = 1\n\n for triplet in triplets:\n sign, n, d = triplet\n n = int(n)\n d = int(d)\n\n if sign == "-":\n num = num * d - n * den\n else:\n num = num * d + n * den\n den *= d\n \n while math.gcd(num, den) > 1:\n gcd = math.gcd(num, den)\n num /= gcd\n num = int(num)\n den /= gcd\n den = int(den)\n \n res = ""\n res += str(num)\n res += "/"\n res += str(den)\n \n return res\n```\n\n```Java []\nclass Solution {\n\n class Fraction {\n public boolean isNegative;\n public int numerator;\n public int denominator;\n\n public void placeNumerator(char n) {\n if(numerator > 0) {\n numerator *= 10;\n }\n numerator += Character.getNumericValue(n);\n }\n public void placeDenominator(char n) {\n if(denominator > 0) {\n denominator *= 10;\n }\n denominator += Character.getNumericValue(n);\n }\n public int getSignedNumerator() {\n return isNegative ? -numerator : numerator;\n }\n public void add(Fraction other) {\n int finalResult = this.getSignedNumerator() +\n other.getSignedNumerator();\n\n this.isNegative = (finalResult < 0);\n this.numerator = Math.abs(finalResult);\n\n if(finalResult == 0) {\n this.denominator = 1;\n }\n }\n public void reduce() {\n if(denominator == 1) {\n return;\n }\n if(denominator % numerator == 0) {\n denominator = denominator / numerator;\n numerator = 1;\n return;\n }\n if(numerator % denominator == 0) {\n numerator = numerator / denominator;\n denominator = 1;\n return;\n }\n int multipleCap = Math.min(numerator, denominator) / 2;\n\n for(int i = 2; i <= multipleCap; i++) {\n // If not evenly divisible, continue.\n if(numerator % i != 0 || denominator % i != 0) {\n continue;\n }\n numerator = numerator / i;\n denominator = denominator / i;\n multipleCap = Math.min(numerator, denominator) / 2;\n i = 1;\n }\n }\n public String toString() {\n StringBuilder str = new StringBuilder();\n if(isNegative) {\n str.append(\'-\');\n }\n str.append(numerator);\n str.append(\'/\');\n str.append(denominator);\n return str.toString();\n }\n }\n public String fractionAddition(String expression) {\n\n ArrayList<Fraction> allFractions = parseFractions(expression);\n Fraction baseFraction = allFractions.get(0);\n\n for(int i = 1; i < allFractions.size(); i++) {\n Fraction actedUponFraction = allFractions.get(i);\n\n int baseDenominator = baseFraction.denominator;\n baseFraction.numerator *= actedUponFraction.denominator;\n baseFraction.denominator *= actedUponFraction.denominator;\n actedUponFraction.numerator *= baseDenominator;\n actedUponFraction.denominator *= baseDenominator;\n\n baseFraction.add(actedUponFraction);\n baseFraction.reduce();\n }\n return baseFraction.toString();\n }\n public ArrayList<Fraction> parseFractions(String expression) {\n ArrayList<Fraction> allFractions = new ArrayList<>();\n int i = 0;\n do {\n Fraction fraction = new Fraction();\n char currentChar = expression.charAt(i);\n\n if(currentChar == \'-\') {\n fraction.isNegative = true;\n i = i + 1;\n }\n if(currentChar == \'+\') {\n i = i + 1;\n }\n currentChar = expression.charAt(i);\n do {\n fraction.placeNumerator(currentChar);\n i = i + 1;\n currentChar = expression.charAt(i);\n } while(currentChar != \'/\');\n i = i + 1;\n\n currentChar = expression.charAt(i);\n do {\n fraction.placeDenominator(currentChar);\n i = i + 1;\n\n if(i >= expression.length()) {\n break;\n }\n currentChar = expression.charAt(i);\n\n } while(i < expression.length() && \n currentChar != \'+\' &&\n currentChar != \'-\');\n\n allFractions.add(fraction);\n\n } while(i < expression.length());\n\n return allFractions;\n }\n}\n```\n
1
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
Python Elegant & Short | RegEx | Two lines
fraction-addition-and-subtraction
0
1
\timport re\n\tfrom fractions import Fraction\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(n)\n\t\tMemory: O(n)\n\t\t"""\n\n\t\tFRACTION_PATTERN = r\'([+-]?[^+-]+)\'\n\t\t\n\t\t# First solution\n\t\tdef fractionAddition(self, expression: str) -> str:\n\t\t\tresult_fraction = Fraction(0)\n\n\t\t\tfor exp in re.findall(self.FRACTION_PATTERN, expression):\n\t\t\t\tn, d = map(int, exp.split(\'/\'))\n\t\t\t\tresult_fraction += Fraction(n, d)\n\n\t\t\treturn f\'{result_fraction.numerator}/{result_fraction.denominator}\'\n\n\t\t# Second solution\n\t\tdef fractionAddition(self, expression: str) -> str:\n\t\t\tresult_fraction = sum(\n\t\t\t\t(Fraction(*map(int, exp.split(\'/\'))) for exp in re.findall(self.FRACTION_PATTERN, expression)),\n\t\t\t\tFraction(0)\n\t\t\t)\n\t\t\treturn f\'{result_fraction.numerator}/{result_fraction.denominator}\'\n
4
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
592: Space 98%, Solution with step by step explanation
fraction-addition-and-subtraction
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Split the expression string into individual fractions using the re.findall function and regular expression pattern [+-]?\\d+/\\d+. This will match any fraction in the expression, including negative fractions and fractions with whole numbers.\n2. Convert the list of fraction strings to a list of tuples (numerator, denominator) by splitting each fraction string at the \'/\' character and converting the resulting strings to integers using map.\n3. Find the least common multiple (LCM) of the denominators of all the fractions. To do this, initialize lcm to 1 and loop through each fraction, multiplying lcm by the fraction\'s denominator divided by the greatest common divisor of lcm and the fraction\'s denominator.\n4. Add the numerators of all the fractions, after multiplying each numerator by a factor so that the fractions all have a common denominator equal to the lcm found in step 3.\n5. Simplify the resulting fraction by dividing the numerator and denominator by their greatest common divisor using the math.gcd function.\n6. Return the simplified fraction as a string in the format numerator/denominator.\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:\n def fractionAddition(self, expression: str) -> str:\n # Split the expression into individual fractions\n fractions = re.findall(\'[+-]?\\d+/\\d+\', expression)\n \n # Convert the fractions to a list of tuples (numerator, denominator)\n fractions = [tuple(map(int, fraction.split(\'/\'))) for fraction in fractions]\n \n # Find the LCM of the denominators\n lcm = 1\n for fraction in fractions:\n lcm = lcm * fraction[1] // math.gcd(lcm, fraction[1])\n \n # Add the numerators after multiplying by the appropriate factor\n numerator_sum = sum([fraction[0] * (lcm // fraction[1]) for fraction in fractions])\n \n # Simplify the fraction\n gcd = math.gcd(numerator_sum, lcm)\n numerator = numerator_sum // gcd\n denominator = lcm // gcd\n \n # Return the simplified fraction as a string\n return str(numerator) + \'/\' + str(denominator)\n\n```
5
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
Python two solutions👀. Short and Concise✅. Library and No Library🔥
fraction-addition-and-subtraction
0
1
**1. A short solution using [fractions](https://docs.python.org/3/library/fractions.html) from python stdlib**\n```\nfrom fractions import Fraction\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n ans = Fraction(eval(expression))\n return \'/\'.join(map(str, ans.limit_denominator().as_integer_ratio()))\n```\n\n**2. A consise no library solution**\n```\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n # get all the fractions separately: e.g: "-1/2+1/2" -> [\'-1/2\', \'1/2\']\n fractions = re.findall(r\'-*\\d+/\\d+\', expression)\n \n # separate the numerators and denominators-> [\'-1/2\', \'1/2\'] -> [-1, 1] , [2, 2]\n numerators, denominators = [], []\n for fraction in fractions:\n n, d = map(int, fraction.split(\'/\'))\n numerators.append(n)\n denominators.append(d)\n \n # find the lcm of the denominators\n lcm = reduce(math.lcm, denominators)\n # find with what number the denominators and numerators are to be multipled with\n multiples = [lcm // d for d in denominators]\n # multiply the multipler for each of the numerator\n numerators = [n*m for n, m in zip(numerators, multiples)]\n # multiply the multipler for each of the denominator\n denominators = [d*m for d, m in zip(denominators, multiples)]\n \n # now the denominators are all equal; so take just one; and add the numerator\n numerator, denominator = sum(numerators), denominators[0]\n # find if the numerator and denomitors can further of be reduced...\n gcd = math.gcd(numerator, denominator)\n numerator //= gcd\n denominator //= gcd\n return f\'{numerator}/{denominator}\'\n```
2
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
[Python] Simple Parsing - with example
fraction-addition-and-subtraction
0
1
```html5\n<b>Time Complexity: O(n + log(N&middot;D))</b> where n = expression.length and (N, D) are the unreduced numerator and common denominator &becaus; while-loop and gcd\n<b>Space Complexity: O(n)</b> &becaus; num and den both scale with n and &becaus; when the first fraction is positive: expression = \'+\' + expression\n```\n\nWe will use the example `"-3/1+2/3-3/2+4/7+5/5"` while walking through the approach.\nSteps are also annotated within the code.\n\n**Approach:**\n\nFirst use a while-loop iterate over `expression` once.\nEach loop, we will extract one fraction from the expression:\n1. `expression[i]` will tell us if the numerator is positve or negative\n2. The following characters that are digits will make up the numerator.\n3. Skip the next character, it will always be `\'/\'`.\n4. The following characters that are digits will make up the denominator.\n\nAfter which the cycle either ends because we reached the end of `expression`\nor the cycle repeats starting with a new `+` or `-` denoting the sign of the next fraction.\n\nStore all of the numerators in a list `num` and all of the denominators in a separate list `den`.\nAn easy way to find a common divisor is to just multiply all of the denominators together.\nI.e: `den = [1, 3, 2, 7, 5] -> denominator = 1*3*2*7*5 = 210`\n\nThen multiply each numerator and denominator by `210 / den` so that it can be represented as `new_numerator / 210`.\n```html5\nnum = [-3, 2, -3, 4, 5] -> num = [-3/1, 2/3, -3/2, 4/7, 5/5] * 210 -> num = [-630, 140, -315, 120, 210]\nden = [ 1, 3, 2, 7, 5] -> den = [ 1/1, 3/3, 2/2, 7/7, 5/5] * 210 -> den = [ 210, 210, 210, 210, 210]\n```\n\nNow our numerators and denominators look like this:\n```html5\nnum = [-630, 140, -315, 120, 210]\nden = [ 210, 210, 210, 210, 210]\n```\n\nSince all of the fraction share the same denominator, we can combine them through addition:\n`numerator = -475`\n`denominator = 210`\n\nFinally, all that is left to do is to reduce the fraction.\nThis can be done by dividing the numerator and denominator by their greatest common divisor.\n`gcd(-475, 210) = 5 -> numerator = -475 / 5 = -95 -> denominator = 210 / 5 = 42`\n`gcd(-95, 42) = 1`\n\nHence, the final answer is `"numerator / denominator" = "-95/42"`.\n\n```python\nclass Solution:\n def fractionAddition(self, exp: str) -> str:\n \n if not exp:\n return "0/1"\n \n if exp[0] != \'-\':\n exp = \'+\' + exp\n \n # Parse the expression to get the numerator and denominator of each fraction\n num = []\n den = []\n pos = True\n i = 0\n while i < len(exp):\n # Check sign\n pos = True if exp[i] == \'+\' else False\n \n # Get numerator\n i += 1\n n = 0\n while exp[i].isdigit():\n n = n*10 + int(exp[i])\n i += 1\n num.append(n if pos else -n)\n \n # Get denominator\n i += 1\n d = 0\n while i < len(exp) and exp[i].isdigit():\n d = d*10 + int(exp[i])\n i += 1\n den.append(d)\n \n # Multiply the numerator of all fractions so that they have the same denominator\n denominator = functools.reduce(lambda x, y: x*y, den)\n for i,(n,d) in enumerate(zip(num, den)):\n num[i] = n * denominator // d\n \n # Sum up all of the numerator values\n numerator = sum(num)\n \n # Divide numerator and denominator by the greatest common divisor (gcd)\n g = math.gcd(numerator, denominator)\n numerator = numerator // g\n denominator = denominator // g\n \n return f"{numerator}/{denominator}"\n```
8
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
[ Python ] ✅✅ Simple Python Solution | Basic Approach🥳✌👍
fraction-addition-and-subtraction
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 1836 ms, faster than 5.56% of Python3 online submissions for Fraction Addition and Subtraction.\n# Memory Usage: 16.4 MB, less than 39.58% of Python3 online submissions for Fraction Addition and Subtraction.\n\n\tclass Solution:\n\t\tdef fractionAddition(self, expression: str) -> str:\n\n\t\t\tresult = \'\'\n\n\t\t\tnumbers = []\n\n\t\t\tfor num in expression.split(\'/\'):\n\n\t\t\t\tif len(num) > 2 and num[0] != \'-\':\n\n\t\t\t\t\tif \'+\' in num:\n\n\t\t\t\t\t\tsign_index = num.index(\'+\')\n\t\t\t\t\t\tnumbers.append(int(num[:sign_index]))\n\t\t\t\t\t\tnumbers.append(int(num[sign_index:]))\n\n\t\t\t\t\tif \'-\' in num:\n\n\t\t\t\t\t\tsign_index = num.index(\'-\')\n\t\t\t\t\t\tnumbers.append(int(num[:sign_index]))\n\t\t\t\t\t\tnumbers.append(int(num[sign_index:]))\n\t\t\t\telse:\n\t\t\t\t\tnumbers.append(int(num))\n\n\t\t\tnumerator1 , denominator1 = numbers[0] , numbers[1]\n\n\t\t\tif len(numbers) == 2:\n\t\t\t\tresult = str(str(numerator1) + \'/\' + str(denominator1))\n\n\t\t\tfor index in range(2, len(numbers)-1 , 2):\n\n\t\t\t\tnumerator2 , denominator2 = numbers[index] , numbers[index + 1]\n\n\t\t\t\tnumerator1 = numerator1 * denominator2 + numerator2 * denominator1\n\t\t\t\tdenominator1 = denominator1 * denominator2\n\n\t\t\t\tif numerator1 == 0:\n\t\t\t\t\tdenominator1 = 1\n\n\t\t\tif abs(numerator1) != 1 and abs(denominator1) != 1:\n\n\t\t\t\tdivisor = min(abs(numerator1) , abs(denominator1))\n\n\t\t\t\twhile divisor > 0:\n\n\t\t\t\t\tif numerator1 % divisor == 0 and denominator1 % divisor == 0:\n\t\t\t\t\t\tnumerator1 = numerator1 // divisor\n\t\t\t\t\t\tdenominator1 = denominator1 // divisor\n\n\t\t\t\t\tdivisor = divisor - 1\n\n\t\t\tresult = str(numerator1) + \'/\' + str(denominator1)\n\n\t\t\treturn result\n\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D
0
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
Simple | Easy to understand | Python solution | NO Regular Expression 💯 ✅
fraction-addition-and-subtraction
0
1
# Intuition\nlet\'s think about a brute force idea first. we need to calcualte a minimal common multiple of all the denominators. Then we can add all the numerators and divide the result by the common denominator. reduce them by overall gcd. this is a very naive idea. we can do better. But let me implement it first.\n\n# Approach\n1. implement gcd (for loop, divided by other)\n2. implement lcm using times two number / gcd\n3. implement split expression by split by \'\\\'\n4. add a \'+\' at first if the first char is a number\n5. enter for loop to find each fraction\n6. when getting a \'+\' or \'-\', if we want to find fraction, we need to find next \'+\',\'-\', the string between first \'+\'/\'-\' and next \'+\'/\'-\' is the fraction. put the denominaotr and numerator into to lists.\n7. find the LCM of all denominator.\n8. time each numerator by LCM / its corresponding denominator\n9. sum the new numerator\n10. find the gcd of sum of the new numerator and LCM of all denominator\n11. return sum of the new numerator / gcd and LCM of all denominator / gcd.\n\n# Complexity\nAssume we have N fraction N*digits length of string\n- Time complexity:\nO(Nlog(max(Number))) # GCD \n- Space complexity:\nO(N)\n\n\n# Code\n```\nimport math\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n # find minimum common multiple for denominator\n def lcm(a, b):\n return a * b // math.gcd(a, b)\n # find greatest common divisor for numerator and denominator\n def gcd(a, b):\n return math.gcd(a, b)\n # convert string to integer\n def toInt(expression):\n return int(expression)\n # split expressions\n def split(expression):\n return expression.split(\'/\')\n if expression[0] != \'-\':\n expression = \'+\' + expression\n numerators = []\n denominators = []\n for i in range(len(expression)):\n next = expression.find(\'+\', i + 1)\n if next == -1:\n next = expression.find(\'-\', i + 1)\n else:\n if expression.find(\'-\', i + 1) != -1:\n next = min(next, expression.find(\'-\', i + 1))\n if next == -1:\n next = len(expression)\n if expression[i] == \'+\':\n numerators.append(toInt(split(expression[i + 1:next])[0]))\n denominators.append(toInt(split(expression[i + 1:next])[1]))\n elif expression[i] == \'-\':\n numerators.append(-1*toInt(split(expression[i + 1:next])[0]))\n denominators.append(toInt(split(expression[i + 1:next])[1]))\n # find lcm\n lcm_denominator = 1\n for i in range(len(denominators)):\n lcm_denominator = lcm(lcm_denominator, denominators[i])\n # sum up numerators\n numerator = 0\n for i in range(len(numerators)):\n numerator += numerators[i] * (lcm_denominator // denominators[i])\n # find gcd\n gcd_numerator = gcd(numerator, lcm_denominator)\n # return result\n return str(numerator // gcd_numerator) + \'/\' + str(lcm_denominator // gcd_numerator)\n```
0
Given a string `expression` representing an expression of fraction addition and subtraction, return the calculation result in string format. The final result should be an [irreducible fraction](https://en.wikipedia.org/wiki/Irreducible_fraction). If your final result is an integer, change it to the format of a fraction that has a denominator `1`. So in this case, `2` should be converted to `2/1`. **Example 1:** **Input:** expression = "-1/2+1/2 " **Output:** "0/1 " **Example 2:** **Input:** expression = "-1/2+1/2+1/3 " **Output:** "1/3 " **Example 3:** **Input:** expression = "1/3-1/2 " **Output:** "-1/6 " **Constraints:** * The input string only contains `'0'` to `'9'`, `'/'`, `'+'` and `'-'`. So does the output. * Each fraction (input and output) has the format `±numerator/denominator`. If the first input fraction or the output is positive, then `'+'` will be omitted. * The input only contains valid **irreducible fractions**, where the **numerator** and **denominator** of each fraction will always be in the range `[1, 10]`. If the denominator is `1`, it means this fraction is actually an integer in a fraction format defined above. * The number of given fractions will be in the range `[1, 10]`. * The numerator and denominator of the **final result** are guaranteed to be valid and in the range of **32-bit** int.
null
Python 3 solution || 100% working!!!
valid-square
0
1
# Intuition and Approach\nI tried to find all the possible distances between points(there are 6 combinations). I used dist function from math module to find the distance between two points. Since the dist function takes only tuples as input , I coverted lists to tuples.\n\nAnd since points are not given in order ...I merged them into a single set . Since set contains only distinct values..it should be of length 2 {side length, diagonal}. \n\nAnd in some test cases the two points are same. So, the distance between them would be 0, so I checked for 0 in the set.\n\nThank you and please do UPVOTE if you find it useful.\n\n\n# Code\n```\nclass Solution:\n def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n from math import dist\n a=dist(tuple(p1),tuple(p2))\n b=dist(tuple(p2),tuple(p3))\n c=dist(tuple(p3),tuple(p4))\n d=dist(tuple(p4),tuple(p1))\n e=dist(tuple(p1),tuple(p3))\n f=dist(tuple(p2),tuple(p4))\n\n if len({a,b,c,d,e,f})==2 and 0 not in {a,b,c,d,e,f}:\n return True\n else:\n return False\n```
2
Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). **Example 1:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\] **Output:** true **Example 2:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\] **Output:** false **Example 3:** **Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\] **Output:** true **Constraints:** * `p1.length == p2.length == p3.length == p4.length == 2` * `-104 <= xi, yi <= 104`
null
Beats 93% 🚀💥 PYTHON CODE
valid-square
0
1
\n\n# Code\n```\nclass Solution:\n def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n res=0\n def l(a,b):\n len=(((a[0]-b[0])**2)+((a[1]-b[1])**2))\n return len\n d=[l(p1,p2),l(p1,p3),l(p1,p4),l(p2,p3),l(p2,p4),l(p3,p4)]\n d.sort()\n return True if 0<d[0]==d[1]==d[2]==d[3] and d[4]==d[5] else False \n \n \n```
1
Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). **Example 1:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\] **Output:** true **Example 2:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\] **Output:** false **Example 3:** **Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\] **Output:** true **Constraints:** * `p1.length == p2.length == p3.length == p4.length == 2` * `-104 <= xi, yi <= 104`
null
python easy to understand 3 lines code beats 95%
valid-square
0
1
please upvote if u like\n```\nclass Solution:\n def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n def dist(point1,point2):\n return (point1[0]-point2[0])**2+(point1[1]-point2[1])**2\n \n D=[\n dist(p1,p2),\n dist(p1,p3),\n dist(p1,p4),\n dist(p2,p3),\n dist(p2,p4),\n dist(p3,p4)\n ]\n D.sort()\n return 0<D[0]==D[1]==D[2]==D[3] and D[4]==D[5]\n \n```\nplease upvote if u like
18
Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). **Example 1:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\] **Output:** true **Example 2:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\] **Output:** false **Example 3:** **Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\] **Output:** true **Constraints:** * `p1.length == p2.length == p3.length == p4.length == 2` * `-104 <= xi, yi <= 104`
null
593: Solution with step by step explanation
valid-square
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDefine a function called dist that takes two points as input and returns the square of their Euclidean distance.\n\nThe input points are lists of two integers.\nThe function uses the formula (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 to compute the square of the distance.\nThe function returns the computed value.\nCreate a set called distSet that contains the squares of the distances between all possible pairs of points among the four given points.\n\nUse the itertools.combinations function to generate all possible pairs of points.\nFor each pair of points, call the dist function to compute the square of the distance.\nAdd the computed value to the distSet set.\nCheck if the distSet set contains 0.\n\nIf it does, return False since a square cannot have a side of length 0.\nIf it does not, continue to step 4.\nCheck if the length of the distSet set is 2.\n\nIf it is not, return False since a square must have exactly 2 different side lengths.\nIf it is, continue to step 5.\nReturn True, since the four given points form a valid square.\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:\n def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n def dist(p1: List[int], p2: List[int]) -> int:\n return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2\n\n distSet = set([dist(*pair)\n for pair in list(itertools.combinations([p1, p2, p3, p4], 2))])\n\n return 0 not in distSet and len(distSet) == 2\n```
3
Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). **Example 1:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\] **Output:** true **Example 2:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\] **Output:** false **Example 3:** **Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\] **Output:** true **Constraints:** * `p1.length == p2.length == p3.length == p4.length == 2` * `-104 <= xi, yi <= 104`
null
Solution
valid-square
1
1
```C++ []\nclass Solution {\npublic:\n int helper(vector<int> &A,vector<int> &B){\n return (pow(A[0]-B[0],2)+pow(A[1]-B[1],2));\n }\n bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {\n int a=helper(p1,p2);\n int b=helper(p1,p3);\n int c=helper(p1,p4);\n int d=helper(p2,p3);\n int e=helper(p2,p4);\n int f=helper(p3,p4);\n vector<int> v={a,b,c,d,e,f};\n unordered_map<int,int> mp;\n for(auto i:v)mp[i]++;\n\n if(mp.size()!=2)return 0;\n for(auto i:mp){\n if(i.first==0)return 0;\n return i.second==4 || i.second==2;\n }\n return 0;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n return self.soln1(p1, p2, p3, p4)\n \n def soln1(self, p1, p2, p3, p4):\n count = collections.Counter()\n coordinates = [p1, p2, p3, p4]\n \n for i, (xi, yi) in enumerate(coordinates):\n for xj, yj in coordinates[i+1:]:\n d = (xi-xj)**2 + (yi-yj)**2\n count[d] += 1\n if d==0 or len(count) > 2: return False\n \n return len(count)==2 and all(count[i] in {2, 4} for i in count)\n```\n\n```Java []\nclass Solution {\n public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {\n \tint d12=distance(p1,p2),d13=distance(p1,p3),d23=distance(p2,p3);\n if(d12==0 || d13==0 || d23==0)\n \t\treturn false;\n \tif(d12==d23) {\n \t\treturn sides(p2,p1,p3,p4);\n \t}\n \tif(d12==d13) {\n \t\treturn sides(p1,p2,p3,p4);\n \t}\n \tif(d13==d23) {\n \t\treturn sides(p3,p2,p1,p4);\n \t}\n \treturn false;\n }\n\tprivate boolean sides (int[] p1, int[] p2, int[] p3, int[] p4) {\n\t\tif((p1[0]-p2[0])*(p1[0]-p3[0])+(p1[1]-p2[1])*(p1[1]-p3[1])==0){\n\t\t\treturn p4[0]==p2[0]+p3[0]-p1[0] && p4[1]==p2[1]+p3[1]-p1[1];\n\t\t}else {\n\t\t\treturn false;\n\t\t}\n\t}\n\tprivate int distance(int[] p, int[] q) {\n\t\tint x=p[0]-q[0];\n\t\tint y=p[1]-q[1];\n\t\treturn x*x+y*y;\n\t}\n}\n```\n
3
Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). **Example 1:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\] **Output:** true **Example 2:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\] **Output:** false **Example 3:** **Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\] **Output:** true **Constraints:** * `p1.length == p2.length == p3.length == p4.length == 2` * `-104 <= xi, yi <= 104`
null
3 triangles ^^
valid-square
0
1
![image](https://assets.leetcode.com/users/images/8dc5ca8d-167c-490a-b539-9d2fb2f59e8e_1653589447.8051138.png)\n\nP.S. Actually we need only three triangles to check.\n**c++:**\n```\nclass Solution \n{\n bool f(vector<int>& p1, vector<int>& p2, vector<int>& p3)\n {\n int x = (p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1]),\n y = (p1[0]-p3[0])*(p1[0]-p3[0])+(p1[1]-p3[1])*(p1[1]-p3[1]),\n z = (p3[0]-p2[0])*(p3[0]-p2[0])+(p3[1]-p2[1])*(p3[1]-p2[1]);\n if(x>y) swap(x,y); \n if(x>z) swap(x,z);\n if(y>z) swap(y,z);\n return x and x+y==z and x==y; \n }\n public: \n bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) \n {\n return f(p1,p2,p3) and f(p2,p3,p4) and f(p3,p4,p1); \n }\n};\n```\n**python:**\n```\nclass Solution:\n def validSquare(self, p1, p2, p3, p4) :\n def f(p1, p2, p3) :\n l = sorted([(p1[0]-p2[0])**2+(p1[1]-p2[1])**2, (p1[0]-p3[0])**2+(p1[1]-p3[1])**2, (p3[0]-p2[0])**2+(p3[1]-p2[1])**2])\n return l[0]+l[1]==l[2] and l[0]==l[1]!=0\n return f(p1,p2,p3) and f(p2,p3,p4) and f(p3,p4,p1)\n```
1
Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). **Example 1:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\] **Output:** true **Example 2:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\] **Output:** false **Example 3:** **Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\] **Output:** true **Constraints:** * `p1.length == p2.length == p3.length == p4.length == 2` * `-104 <= xi, yi <= 104`
null
Beats 100% Runtime using count map
longest-harmonious-subsequence
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a count map holding occurences on elements and loop on keys to check if next consecutive element is present in the map.\nIf present, compare the result with the max variable\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def findLHS(self, nums: List[int]) -> int:\n result = 0\n count_map = {}\n for num in nums:\n if num not in count_map:\n count_map[num] = 1\n else:\n count_map[num] += 1\n for num, count in count_map.items():\n if num + 1 in count_map:\n result = max(count + count_map[num + 1], result)\n return result\n\n```
4
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
longest harmonious subsequence - python 3 100% beats in runtime.must watch with tc-O(n) and sc- O(n)
longest-harmonious-subsequence
0
1
# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nThe code defines a class Solution with a method findLHS that takes in a list nums representing an array. It calculates the length of the longest harmonious subsequence in the array.\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\nInitialize a counter (e.g., a dictionary or Counter object) to store the frequency of each element in the array.\r\n\r\nIterate through the elements of the array and update the counter with the frequency of each element.\r\n\r\nInitialize a variable ans to 0, which will store the length of the longest harmonious subsequence.\r\n\r\nIterate through the elements and frequencies in the counter.\r\n\r\nFor each element num in the counter, check if num + 1 exists in the counter. If it does, it means there is a valid harmonious subsequence.\r\n\r\nIf num + 1 exists in the counter, update ans to the maximum value between ans and the sum of the frequencies of num and num + 1.\r\n\r\nAfter iterating through all the elements in the counter, ans will hold the length of the longest harmonious subsequence.\r\n\r\nReturn ans as the result.\r\n\r\nBy using this approach, we count the frequencies of each element in the array and then check for pairs of elements (num and num + 1) that have a difference of 1. If such a pair exists, we update ans with the maximum length of the harmonious subsequence formed by those two elements.\r\n\r\n# Complexity\r\n- Time complexity:O(n)\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\nThe code uses the Counter class from the collections module to count the frequency of each element in the input array nums. The counting operation takes O(n) time, where n is the length of the array.\r\nThe subsequent loop iterates through the elements in the counter dictionary, which contains at most n unique elements. This loop takes O(n) time.\r\nOverall, the time complexity of the code is O(n), where n is the length of the input array.\r\n\r\n- Space complexity:O(n)\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\nThe code uses a Counter object to store the frequency of each element in the array. The Counter object consumes additional space proportional to the number of unique elements in the input array, which can be at most n.\r\nHence, the space complexity is O(n).\r\nNote: The time and space complexity analysis assumes that the operations performed on the Counter object take constant time on average.\r\n\r\n# Code\r\n```\r\nclass Solution:\r\n def findLHS(self, nums: List[int]) -> int:\r\n """\r\n Finds the length of the longest harmonious subsequence in the given array.\r\n Returns the length of the longest harmonious subsequence.\r\n \r\n Time Complexity: O(n)\r\n Space Complexity: O(n)\r\n """\r\n ans = 0\r\n counter = Counter(nums)\r\n \r\n # Iterate through the elements and find the length of the longest harmonious subsequence\r\n for num, freq in counter.items():\r\n if num + 1 in counter:\r\n ans = max(ans, freq + counter[num + 1])\r\n \r\n return ans\r\n\r\n```
2
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
Solution
longest-harmonious-subsequence
1
1
```C++ []\nclass Solution {\npublic:\n int findLHS(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n if (nums.size()==0) return 0;\n int i=0,r=0;\n while(i<nums.size()) {\n int seen=0;\n int low=i;\n int next=i+1;\n while(i<nums.size() && nums[i]==nums[low]) {\n i++;\n }\n next=i;\n while(i<nums.size() && nums[i]==nums[low]+1) i++;\n if (i!=low && nums[i-1]-nums[low]==1) {\n seen+=(i)-low;\n }\n r=max(r, seen);\n i=next;\n }\n return r;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findLHS(self, nums: List[int]) -> int:\n count = collections.Counter(nums)\n return max([count[n] + count[n + 1] for n in count if n + 1 in count] or [0])\n```\n\n```Java []\nclass Solution {\n public int findLHS(int[] nums) {\n Arrays.sort(nums);\n int prev = Integer.MIN_VALUE;\n int prevN = 0;\n int curr = nums[0];\n int currN = 0;\n int max = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] != curr) {\n if (prev+1 == curr)\n max = Math.max(prevN + currN, max);\n prev = curr;\n prevN = currN;\n curr = nums[i];\n currN = 1;\n } else {\n currN++;\n }\n }\n if (prev+1 == curr)\n max = Math.max(prevN + currN, max);\n return max;\n }\n}\n```\n
2
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
594: Time 97.52%, Solution with step by step explanation
longest-harmonious-subsequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCreate a Counter object called freq that counts the frequency of each element in nums.\n\nInitialize a variable called max_length to 0.\n\nIterate through each key in freq.\n\nIf key + 1 is also in freq, update max_length to be the maximum of its current value and the sum of the frequencies of key and key + 1 in freq.\nReturn max_length, which is the length of the longest harmonious subsequence in nums.\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:\n def findLHS(self, nums: List[int]) -> int:\n freq = Counter(nums)\n max_length = 0\n \n for key in freq:\n if key + 1 in freq:\n max_length = max(max_length, freq[key] + freq[key+1])\n \n return max_length\n\n```
6
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
Python. O(n), Cool, easy & clear solution.
longest-harmonious-subsequence
0
1
\tclass Solution:\n\t\tdef findLHS(self, nums: List[int]) -> int:\n\t\t\ttmp = Counter(nums)\n\t\t\tkeys = tmp.keys()\n\t\t\tmax = 0\n\t\t\tfor num in keys:\n\t\t\t\tif num - 1 in keys:\n\t\t\t\t\tif tmp[num - 1] + tmp[num] > max:\n\t\t\t\t\t\tmax = tmp[num - 1] + tmp[num]\n\t\t\treturn max
12
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
Python using dictionary
longest-harmonious-subsequence
0
1
# Intuition\nTo solve this problem, you can iterate through the array and use a hash map to keep track of the frequency of each element in the array. Then, iterate through the hash map and for each element check if there is another element in the hash map whose value is one greater than the current element. If so, add the frequency of the current element to the frequency of the element that is one greater, and update the maximum length of the harmonious subsequence. Finally, return the maximum length of the harmonious subsequence.\n\n# Approach\nIn this implementation, the function first creates a dictionary freq to keep track of the frequency of each element in the input array nums.\nThen it iterates through freq dictionary and checks if there is another element in the dictionary whose value is one greater than the current element. If such element exist, it finds the max_length of the harmonious sub sequence by adding the value of current element and the value of next element in the dictionary and compares it with the previous max_length.\nFinally, it returns the max_length of the harmonious subsequence.\n\n# Complexity\n- Time complexity:\nThe first for loop iterates through the input array nums and populates the frequency dictionary freq, which takes O(n) time.\nThe second for loop iterates through the dictionary freq, which also takes O(n) time.\nAnd in each iteration of the second for loop, we do a constant time lookup in the dictionary to check if an element exists, which also takes O(1) time.\nTherefore, the overall time complexity of the algorithm is O(n) + O(n) + O(1) * O(n) = O(n).\n- Space complexity:\nThe space complexity is O(n) as we are using a dictionary to store the frequency of the element, which can take at most O(n) space in the worst case.\n\n# Code\n```\nclass Solution:\n def findLHS(self, nums: List[int]) -> int:\n freq = {}\n for num in nums:\n freq[num] = freq.get(num, 0) + 1\n max_length = 0\n for num in freq:\n if num + 1 in freq:\n max_length = max(max_length, freq[num] + freq[num + 1])\n return max_length\n\n```
2
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
Python3 Beat 93.80 291ms Explained
longest-harmonious-subsequence
0
1
\n\n# Code\n```\nclass Solution:\n def findLHS(self, nums: List[int]) -> int:\n # You can use a hash table or dictionary to store the frequency of each number. \n # Then, iterate through the keys of the dictionary and check if there is a key \n # whose value is one greater. If there is, compute the sum of the frequencies of \n # those two keys and update the maximum length if necessary. \n\n d, a = {}, 0\n for i in nums:\n if i not in d: d[i] = 1\n else: d[i] += 1\n for i in d:\n if i + 1 in d.keys():\n a = max(a, d[i] + d[i+1])\n return a\n```
2
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
Easy Python 3 Solution without using Counter.
longest-harmonious-subsequence
0
1
```\nclass Solution:\n def findLHS(self, nums: List[int]) -> int:\n letter = {}\n ans = 0\n for i in nums:\n if i not in letter:\n letter[i] = 1\n else:\n letter[i]+=1\n for i in letter:\n if i+1 in letter.keys():\n ans = max(ans, letter[i]+letter[i+1])\n return ans\n \n \n```
6
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
optimal
longest-harmonious-subsequence
0
1
# 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(nlogn)\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```\nfrom collections import Counter\nclass Solution:\n def findLHS(self, nums: List[int]) -> int: \n c = Counter(nums) \n nums.sort()\n ans = 0\n temp = 0\n i = 0\n while i < len(nums): \n temp = c.get(nums[i]) + c.get(nums[i]+1, 0) \n if temp > c.get(nums[i]):\n ans = max(ans, temp)\n i += 1\n return ans\n```
0
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
My Solution :)
longest-harmonious-subsequence
0
1
# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n\r\n# Complexity\r\n- Time complexity:\r\nO(n log n)\r\n\r\n- Space complexity:\r\nO(n)\r\n\r\n# Code\r\n```\r\nclass Solution:\r\n def findLHS(self, nums: List[int]) -> int:\r\n pairs = []\r\n nums = sorted(nums, reverse=True)\r\n for i in range(len(nums)):\r\n if i+1 >= len(nums):\r\n break\r\n if nums[i]-1 == nums[i+1]:\r\n pairs.append([nums[i+1], nums[i]])\r\n maxLength = 0\r\n length = 0\r\n while len(pairs) > 0:\r\n for x in nums:\r\n if x in pairs[0]:\r\n length += 1\r\n if length > maxLength:\r\n maxLength = length\r\n length = 0\r\n pairs.pop(0)\r\n return maxLength\r\n```
0
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`. Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_. A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** nums = \[1,3,2,2,5,2,3,7\] **Output:** 5 **Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\]. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 2 **Example 3:** **Input:** nums = \[1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 2 * 104` * `-109 <= nums[i] <= 109`
null
[ C | C++ | Python | Java | C# | JavaScript | Go ] Same Simple Solution
range-addition-ii
1
1
C:\n```\nint maxCount(int m, int n, int** ops, int opsSize, int* opsColSize){\n int min_row = m;\n int min_col = n;\n for (int i=0; i<opsSize; i++){\n if (ops[i][0]<min_row) min_row=ops[i][0];\n if (ops[i][1]<min_col) min_col=ops[i][1];\n } \n return min_row*min_col;\n}\n```\nC++:\n```\nclass Solution {\npublic:\n int maxCount(int m, int n, vector<vector<int>>& ops) {\n int min_row = m;\n int min_col = n;\n for (int i=0; i<ops.size(); i++){\n if (ops[i][0]<min_row) min_row=ops[i][0];\n if (ops[i][1]<min_col) min_col=ops[i][1];\n } \n return min_row*min_col;\n \n }\n};\n```\nPython:\n```\nclass Solution:\n def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n min_row = m\n min_col = n\n for i in range(len(ops)):\n min_row=min(min_row, ops[i][0])\n min_col=min(min_col, ops[i][1])\n return min_row*min_col\n```\nJava:\n```\nclass Solution {\n public int maxCount(int m, int n, int[][] ops) {\n int min_row = m;\n int min_col = n;\n for (int i=0; i<ops.length; i++){\n if (ops[i][0]<min_row) min_row=ops[i][0];\n if (ops[i][1]<min_col) min_col=ops[i][1];\n } \n return min_row*min_col;\n \n }\n}\n```\nC#\n```\npublic class Solution {\n public int MaxCount(int m, int n, int[][] ops) {\n int min_row = m;\n int min_col = n;\n for (int i=0; i<ops.Length; i++){\n if (ops[i][0]<min_row) min_row=ops[i][0];\n if (ops[i][1]<min_col) min_col=ops[i][1];\n } \n return min_row*min_col;\n \n }\n}\n```\nJavaScript:\n```\nvar maxCount = function(m, n, ops) {\n var min_row = m;\n var min_col = n;\n for (let i=0; i<ops.length; i++){\n if (ops[i][0]<min_row) min_row=ops[i][0];\n if (ops[i][1]<min_col) min_col=ops[i][1];\n } \n return min_row*min_col;\n};\n```\nGo:\n```\nfunc maxCount(m int, n int, ops [][]int) int {\n var min_row int = m;\n var min_col int = n;\n for i:=0; i<len(ops); i++{\n if ops[i][0]<min_row {min_row=ops[i][0]}\n if ops[i][1]<min_col {min_col=ops[i][1]}\n } \n return min_row*min_col;\n \n}\n```
30
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`. Count and return _the number of maximum integers in the matrix after performing all the operations_. **Example 1:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\]\] **Output:** 4 **Explanation:** The maximum integer in M is 2, and there are four of it in M. So return 4. **Example 2:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\]\] **Output:** 4 **Example 3:** **Input:** m = 3, n = 3, ops = \[\] **Output:** 9 **Constraints:** * `1 <= m, n <= 4 * 104` * `0 <= ops.length <= 104` * `ops[i].length == 2` * `1 <= ai <= m` * `1 <= bi <= n`
null
598: Solution with step by step explanation
range-addition-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInitialize two variables min_y and min_x to m and n, respectively.\n\nIterate through each sublist in ops and for each sublist:\n\nUpdate min_y to be the minimum of its current value and the first element of the sublist.\nUpdate min_x to be the minimum of its current value and the second element of the sublist.\nReturn the product of min_x and min_y, which is the maximum value in the resulting matrix.\n\nEnd of the algorithm.\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:\n def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n min_y = m\n min_x = n\n\n for y, x in ops:\n min_y = min(min_y, y)\n min_x = min(min_x, x)\n\n return min_x * min_y\n\n```
3
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`. Count and return _the number of maximum integers in the matrix after performing all the operations_. **Example 1:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\]\] **Output:** 4 **Explanation:** The maximum integer in M is 2, and there are four of it in M. So return 4. **Example 2:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\]\] **Output:** 4 **Example 3:** **Input:** m = 3, n = 3, ops = \[\] **Output:** 9 **Constraints:** * `1 <= m, n <= 4 * 104` * `0 <= ops.length <= 104` * `ops[i].length == 2` * `1 <= ai <= m` * `1 <= bi <= n`
null
Solution
range-addition-ii
1
1
```C++ []\nclass Solution {\npublic:\n int maxCount(int m, int n, vector<vector<int>>& ops) {\n for (auto op : ops){\n m = min(m, op[0]);\n n = min(n, op[1]);\n }\n return m * n;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n minRow = m\n minCol = n\n for x, y in ops:\n minRow = min(x, minRow)\n minCol = min(y, minCol)\n return minRow*minCol\n```\n\n```Java []\nclass Solution {\n public int maxCount(int m, int n, int[][] ops) {\n int k=ops.length;\n for (int i=0;i<k;i++)\n {\n int z=ops[i][0] ,x=ops[i][1];\n n=Math.min(n,x);\n m=Math.min(m,z);\n }\n return (m*n);\n }\n}\n```\n
2
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`. Count and return _the number of maximum integers in the matrix after performing all the operations_. **Example 1:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\]\] **Output:** 4 **Explanation:** The maximum integer in M is 2, and there are four of it in M. So return 4. **Example 2:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\]\] **Output:** 4 **Example 3:** **Input:** m = 3, n = 3, ops = \[\] **Output:** 9 **Constraints:** * `1 <= m, n <= 4 * 104` * `0 <= ops.length <= 104` * `ops[i].length == 2` * `1 <= ai <= m` * `1 <= bi <= n`
null