title
stringlengths 3
77
| title_slug
stringlengths 3
77
| question_content
stringlengths 38
1.55k
⌀ | tag
stringclasses 707
values | level
stringclasses 3
values | question_hints
stringlengths 19
3.98k
⌀ | view_count
int64 8
630k
| vote_count
int64 5
10.4k
| content
stringlengths 0
43.9k
| __index_level_0__
int64 0
109k
|
---|---|---|---|---|---|---|---|---|---|
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 649 | 11 | Code is self explanatory...\nI used hashmap to store node\'s value as key and node as value... so by using key I can access particular node at any time....\nI took nodes set which I pushed all node values in it...\nI took children set which I pushed all children values in it..\n\nIf a node in the nodes set is not present in children set... that means that node is not a children.. i.e, that node doesnt have any parent... so return that particular node as root....\n\n```\n\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n hashmap = {}\n nodes = set()\n children = set()\n for parent,child,isLeft in descriptions:\n nodes.add(parent)\n nodes.add(child)\n children.add(child)\n if parent not in hashmap:\n hashmap[parent] = TreeNode(parent)\n if child not in hashmap:\n hashmap[child] = TreeNode(child)\n if isLeft:\n hashmap[parent].left = hashmap[child]\n if not isLeft:\n hashmap[parent].right = hashmap[child]\n \n for node in nodes:\n if node not in children:\n return hashmap[node]\n\n\n\n```\n\n**PLEASE UPVOTE IF U LIKE IT :).. FEEL FREE TO ASK QUERIES** | 108,125 |
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 1,035 | 9 | \n1) Use unordered_map and unordered_set .\n\n```\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n TreeNode* createBinaryTree(vector<vector<int>>& desc)\n {\n // set contains all the nodes\n set<TreeNode*>contains;\n \n // map which contains child -> parent\n unordered_map<TreeNode*,TreeNode*>childToParentMap;\n \n //map which contains val->Node\n unordered_map<int,TreeNode*>valWithNode;\n\n for(auto &xt : desc)\n {\n int parentVal = xt[0];\n int childVal = xt[1];\n int isLeft = xt[2];\n \n TreeNode* parent;\n \n // if the parent val is already present get that particular node no need to create new \n if(valWithNode.find(parentVal)==valWithNode.end())\n {\n parent = new TreeNode(parentVal);\n valWithNode[parentVal]=parent;\n }\n else\n parent = valWithNode[parentVal];\n \n TreeNode* child;\n \n \n if(valWithNode.find(childVal)==valWithNode.end())\n {\n child = new TreeNode(childVal);\n valWithNode[childVal]=child;\n }\n else\n child = valWithNode[childVal];\n\n contains.insert(parent);\n contains.insert(child);\n\n \n childToParentMap[child] = parent;\n\n if(isLeft)\n {\n parent->left = child;\n }\n else\n {\n parent->right = child;\n }\n \n }\n \n // interate all the nodes in contains set \n for(TreeNode* node : contains)\n {\n // if a node is not present from child->parent map then the node is root \n\t\t\t// return it\n if(childToParentMap.find(node)==childToParentMap.end())\n {\n return node;\n }\n }\n \n return NULL;\n }\n};\n``` | 108,126 |
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 748 | 13 | This is very straightforward problem. Just keep doing as problem says.\nLike for any ***description*** in **descriptions** :\n1. Get the parent node \n\t* So first check whether you\'ve been created parent node earlier or not. If it\'s not created than create it else get the earlier node.\n\t* If child node is in the left of parent than add it left else add it to the right.\n2. Keep memorize these 2 nodes for future process.\n\t3. Once we done with all **description** in **descriptions** than we have challenge part to find the root node. So for this keep tracking the inDegree for every node. And which node have inDegree 0 that will be our root node.\n\n```\nclass Solution {\npublic:\n TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {\n // To store whether we have already created a subtree with give node as key\n unordered_map<int,TreeNode*> created;\n \n // It will help to find the root node\n vector<int> inDegree(100001,0);\n for(auto &d:descriptions) {\n // If already created than get the older once else create new\n TreeNode *parent = created.find(d[0])==created.end() ? new TreeNode(d[0]): created[d[0]];\n TreeNode *child = created.find(d[1])==created.end() ? new TreeNode(d[1]): created[d[1]];\n \n // Do as problem description said\n if(d[2]) {\n parent->left = child;\n } else {\n parent->right = child;\n }\n \n // Store back to use for future\n created[d[0]] = parent;\n created[d[1]] = child;\n inDegree[d[1]]++;\n }\n \n // Find the root node\n for(auto &[key, node]:created) {\n if(inDegree[key] == 0) {\n return node;\n }\n }\n return nullptr;\n }\n};\n```\n# Time Complexity : \n**Since we are going to each description in descriptions only once. So it would take O(N) time. And also finding the root node take O(N) time.**\n\n# Space Complexity :\n**Since we are storing the nodes and storing the inDegree which will take O(N) space.**\n\n**Please upvote if it helps you.**\n\n*Happy Coding!* | 108,131 |
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 179 | 5 | ```\n\nclass Solution {\n \n public TreeNode createBinaryTree(int[][] desc) {\n Map<Integer,TreeNode> map = new HashMap<>();\n Map<Integer,Boolean> children = new HashMap<>();\n TreeNode pp = null;\n for(int i=0;i<desc.length;i++){\n int p = desc[i][0];\n int c = desc[i][1];\n int isleft = desc[i][2];\n children.put( c,true );\n TreeNode parent = map.getOrDefault( p , new TreeNode(p) );\n TreeNode child = map.getOrDefault( c , new TreeNode(c) ); \n \n if(isleft==1){\n parent.left = child;\n }\n else{\n parent.right = child;\n } \n map.put(p , parent );\n map.put(c , child );\n }\n \n // just figure out , the node which is not in children of any node, so it should not present in map\n\t\t\n \n int idx=0;\n for(int i=0;i<desc.length;i++){\n int p = desc[i][0];\n if(!children.containsKey( p ) ){\n idx = p;\n break;\n }\n \n }\n \n return map.get(idx);\n \n }\n \n \n}\n``` | 108,133 |
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 641 | 6 | # Approach\n**Step 1:-** Take a map data Structure that will store the address of each of the nodes formed with their values.\n\n**Step 2:-** Iterate over the given 2D matrix(edgeRelationArray) and see if the parentNode is present in the map or not. \n\n- If the parentNode is present in the map then there is no need of making a new node, Just store the address of the parentNode in a variable. \n- If the parentNode is not present in the map then form a parentNode of the given value and store its address in the map. (Because this parentNode can be the childNode of some other Node). \n\n**Step 3:-** Repeat Step 2 for child Node also i.e.,\n\n- If the childNode is present in the map then there is no need of making a new node, Just store the address of the childNode in a variable.\n- If the childNode is not present in the map then form a childNode of the given value and store its address in the map(Because this childNode can be the parentNode of some other Node). \n\n**Step 4:-** Form the relation between the parentNode and the childNode for each iteration depending on the value of the third value of the array of each iteration. i.e.,\n\n- If the third value of the array in the given iteration is 1 then it means that the childNode is the left child of the parentNode formed for the given iteration.\n- If the third value of the array in the given iteration is 0 then it means that the childNode is the left child of the parentNode formed for the given iteration.\n\nNow here comes a little thinking. We have all the addresses of every node in the map. But How to determine the parentNode. \n\nWe can use the concept of the Tree itself. If carefully observed we know that the root node is the only node that has no Parent.\n\n**Step 5:-** So we can store all the values of the childNode that is present in the given 2D matrix (edgeRelationArray) in a data structure (let\'s assume a map data structure).\n\n**Step 6:-** Again iterate the 2D matrix (edgeRelationArray) to check which parentNode value is not present in the map dataStructure formed in step 5).\n\n# Complexity\n- Time complexity:O(N) where N is the number of rows present in the 2D matrix\n\n- Space complexity: O(M) where M is the number of nodes present in the Tree (We are storing the nodes values along with its address in the map). \n\n# Code\n```\nclass Solution {\npublic:\n TreeNode* createBinaryTree(vector<vector<int>>& descriptions) {\n map<int, TreeNode*> mp;\n for (auto it : descriptions) {\n TreeNode* parentNode, * childNode;\n\n // Finding the parent Node\n if (mp.find(it[0]) != mp.end()) {\n parentNode = mp[it[0]];\n }\n else {\n parentNode = new TreeNode(it[0]);\n mp[it[0]] = parentNode;\n }\n\n // Finding the child Node\n if (mp.find(it[1]) != mp.end()) {\n childNode = mp[it[1]];\n }\n else {\n childNode = new TreeNode(it[1]);\n mp[it[1]] = childNode;\n }\n\n // Making the Edge Between parent and child Node\n if (it[2] == 1) {\n parentNode->left = childNode;\n }\n else {\n parentNode->right = childNode;\n }\n }\n\n // Store the childNode \n map<int, int> storeChild;\n for (auto it : descriptions) {\n storeChild[it[1]] = 1;\n }\n // Find the root of the Tree\n TreeNode* root;\n for (auto it : descriptions) {\n if (storeChild.find(it[0]) == storeChild.end()) {\n root = mp[it[0]];\n }\n }\n return root;\n }\n};\n``` | 108,134 |
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 531 | 13 | Please pull this [commit]() for solutions of weekly 283.\n\n```\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n mp = {}\n seen = set()\n for p, c, left in descriptions: \n if p not in mp: mp[p] = TreeNode(p)\n if c not in mp: mp[c] = TreeNode(c)\n if left: mp[p].left = mp[c]\n else: mp[p].right = mp[c]\n seen.add(c)\n for p, _, _ in descriptions: \n if p not in seen: return mp[p]\n``` | 108,135 |
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 516 | 5 | Here we use a HashMap to keep track of node values and their references along with the fact if that node has a parent or not. We develop the Binary Tree as we go along. Finally we check which node has no parent as that node is the root node.\n1. Maintain a hash map with the keys being node values and value being a list of its `REFERENCE` and a `HAS_PARENT` property which tells weather or not it has a parent or not (Represented by True if it has False if not)\n2. Traverse through the descriptions list.\n3. For every new node value found, add a new TreeNode into the list with its `HAS_PARENT` property being False.\n4. Now make the child node parents left/right child and update the `HAS_PARENT` property of child value in map to True.\n5. Now once the Binary Tree is made we traverse through the hash map to check which node still has no parent. This node is out root node.\n6. Return the root node.\n```\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n root = None\n table = {}\n for arr in descriptions:\n parent = arr[0]\n child = arr[1]\n isleft = arr[2]\n if table.get(parent, None) is None: # If key parent does not exist in table\n table[parent] = [TreeNode(parent), False]\n if table.get(child, None) is None: If key child does not exist in table\n table[child] = [TreeNode(child), False]\n table[child][1] = True # Since child is going to have a parent in the current iteration, set its has parent property to True\n if isleft == 1:\n table[parent][0].left = table[child][0]\n else:\n table[parent][0].right = table[child][0]\n\t\t# Now traverse the hashtable and check which node still has no parent\n for k, v in table.items():\n if not v[1]: # Has parent is False, so root is found.\n root = k\n\t\t\t\tbreak\n return table[root][0]\n``` | 108,138 |
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 572 | 10 | ```\nclass Solution {\n public TreeNode createBinaryTree(int[][] descriptions) {\n HashMap<Integer,TreeNode> map=new HashMap<>();\n HashSet<Integer> children=new HashSet<>();\n for(int[] info:descriptions)\n {\n int parent=info[0],child=info[1];\n boolean isLeft=info[2]==1?true:false;\n TreeNode parentNode=null;\n TreeNode childNode=null;\n if(map.containsKey(parent))\n parentNode=map.get(parent);\n else\n parentNode=new TreeNode(parent);\n if(map.containsKey(child))\n childNode=map.get(child);\n else\n childNode=new TreeNode(child);\n if(isLeft)\n parentNode.left=childNode;\n else\n parentNode.right=childNode;\n map.put(parent,parentNode);\n map.put(child,childNode);\n children.add(child);\n \n }\n TreeNode root=null;\n for(int info[]:descriptions)\n {\n if(!children.contains(info[0]))\n {\n root=map.get(info[0]);\n break;\n }\n }\n return root;\n }\n \n \n} | 108,141 |
Create Binary Tree From Descriptions | create-binary-tree-from-descriptions | You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid. | Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node. | 383 | 8 | ```\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n \n tree = dict()\n children = set()\n for parent, child, isLeft in descriptions:\n if parent not in tree : tree[parent] = TreeNode(parent)\n if child not in tree : tree[child] = TreeNode(child)\n \n if isLeft : tree[parent].left = tree[child]\n else : tree[parent].right = tree[child]\n \n children.add(child)\n \n for parent in tree:\n if parent not in children:\n return tree[parent]\n \n``` | 108,152 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 4,636 | 84 | ## Observations\n\nThis hint made the question very easy.\n\n```\nIt can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result.\n```\nIt could have been transformed to a trick question if this fact was not stated.\n\nNow, since the order doesn\'t matter we have the following observations.\n\n### Observation 1\n\nIf we start processing from the first element one by one, we only care about the last two elements so we can simply check if they have a `gcd > 1` in `O(log(n))` time (using built in functions or Eucledian algorithm). If they are co-prime we can replace them with their LCM, more on that in `Observation 2`. Once replaced by the LCM we have reduced the previous two elements by one and thus we can check the LCM element with the 3rd last element. Eg: `[x,y,z]` -> `[x, LCM(y,z)]` -> `[LCM(x,(LCM(y,z)))]`. \n\nThis setting is similar to many stack related questions like:\n\n[1047. Remove All Adjacent Duplicates In String]()\n[1209. Remove All Adjacent Duplicates in String II]()\n[1717. Maximum Score From Removing Substrings]()\n\nThus using a stack we can keep repeating this process until the stack is empty or the last two numbers are co-prime and then move on to the next iteration/element of the input and repeat.\n\n### Observation 2\n\nHow do we get `LCM` of two numbers? Well there is a mathematical formula to do that for two numbers `a` and `b`.\n`LCM(a,b) * GCD(a,b) = a * b` therefore `LCM(a,b) = (a * b) / GCD(a,b)`.\n\nWe can use these two observations to formulate our solution.\n\n## Solution\n**C++**\n\n```c++\nclass Solution {\npublic:\n vector<int> replaceNonCoprimes(vector<int>& nums) {\n vector<int> result;\n for(int &i:nums) {\n result.push_back(i); // Push the new element in stack.\n while(result.size()>1&&__gcd(result.back(),result[result.size()-2])>1) { // While we have two elements and they are not co-prime.\n long long a=result.back(),b=result[result.size()-2],g=__gcd(a,b); // Get the last two numbers in the stack and their GCD.\n \n // Remove the two elements.\n result.pop_back(); \n result.pop_back();\n result.push_back(a*b/g); // Push the LCM of the two numbers, replacing them.\n }\n }\n return result;\n }\n};\n```\n\n**Python**\n\nCredits to [@tojuna]() for the python solution, please upvote his comment!\n```python\ndef replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n\tstk = []\n\tfor num in nums:\n\t\tstk.append(num)\n\t\twhile len(stk) > 1 and gcd(stk[-1], stk[-2]) > 1:\n\t\t\tstk.append(lcm(stk.pop(), stk.pop()))\n\treturn stk\n```\n\n## Complexity\nSpace: `O(1)`. If you don\'t consider the output space.\nTime: `O(nlog(m))`. GCD of two numbers takes `O(log(min(a,b))`.\n | 108,160 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 4,453 | 69 | # **Explanation**\nFor each number `a` in input array `A`,\ncheck if it is coprime with the last number `b` in `res`.\nIf it\'s not coprime, then we can merge them by calculate `a * b / gcd(a, b)`.\nand check we can continue to do this process.\n\nUntil it\'s coprime with the last element in `res`,\nwe append `a` at the end of `res`.\n\nWe do this for all elements `a` in `A`, and return the final result.\n<br>\n\n# **Complexity**\nTime `O(nlogn)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public List<Integer> replaceNonCoprimes(int[] A) {\n LinkedList<Integer> res = new LinkedList();\n for (int a : A) {\n while (true) {\n int last = res.isEmpty() ? 1 : res.getLast();\n int x = gcd(last, a);\n if (x == 1) break; // co-prime\n a *= res.removeLast() / x;\n }\n res.add(a);\n }\n return res;\n }\n\n private int gcd(int a, int b) {\n return b > 0 ? gcd(b, a % b) : a;\n }\n```\n\n**C++**\n```cpp\n vector<int> replaceNonCoprimes(vector<int>& A) {\n vector<int> res;\n for (int a: A) { \n while (true) { \n int x = gcd(res.empty() ? 1 : res.back(), a);\n if (x == 1) break; // co-prime\n a *= res.back() / x;\n res.pop_back();\n }\n res.push_back(a);\n }\n return res;\n }\n```\n\n**Python3**\n```py\n def replaceNonCoprimes(self, A):\n res = []\n for a in A:\n while True:\n x = math.gcd(res[-1] if res else 1, a)\n if x == 1: break # co-prime\n a *= res.pop() // x\n res.append(a)\n return res\n```\n | 108,161 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 992 | 18 | No need to overcomplicate. This is just a brute-force. Using the list just for fun; I feel it\'s a bit easier to get right than a stack or two-pointer.\n\n**C++**\n```cpp\nvector<int> replaceNonCoprimes(vector<int>& nums) {\n list<int> l(begin(nums), end(nums));\n for (auto it = begin(l); it != end(l); ++it)\n if (it != begin(l)) {\n int n1 = *prev(it), n2 = *it;\n int it_gcd = gcd(n1, n2);\n if (it_gcd > 1) {\n l.erase(prev(it));\n *it = (long long)n1 * n2 / it_gcd;\n --it;\n }\n }\n return vector<int>(begin(l), end(l));\n}\n``` | 108,162 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 1,561 | 13 | \nSee my latest update in repo [LeetCode]()\n\n## Solution 1. Simulation + Two Pointers\n\n**Intuition**: From left to right, replace two adjacent non-coprime numbers with their LCM. When a merge happens, try keep merging leftwards.\n\n**Algorithm**: `i` is a read pointer scaning `A` from left to right. `j` is a write pointer. After reading a new number `A[j] = A[i]`, we keep trying to merge `A[j]` with `A[j-1]` if they are non-coprime. The new `A[j-1]` after merge is `LCM(A[j], A[j-1])`.\n\n**Time Complexity**:\n\nSince `gcd(a, b)`\'s time complexity is `log(min(a, b))`, the time complexity is `O(NlogM)` overall where `M` is the maximum number in `A`.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1) extra space\nclass Solution {\npublic:\n vector<int> replaceNonCoprimes(vector<int>& A) {\n int j = 0, N = A.size();\n for (int i = 0; i < N; ++i, ++j) {\n A[j] = A[i];\n for (; j - 1 >= 0 && gcd(A[j], A[j - 1]) > 1; --j) { // When we can merge leftwards from `A[j]`, keep merging\n A[j - 1] = (long)A[j] * A[j - 1] / gcd(A[j], A[j - 1]); // replace `A[j-1]` with LCM of `A[j-1]` and `A[j]`.\n }\n }\n A.resize(j);\n return A;\n }\n};\n``` | 108,164 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 1,139 | 9 | **Approach** - \n\n0) As in questions says we have to choose adjacent , then I thought **stack** can be used .\n1) we have to check whether the top value in the stack and the current val in array is non-coprime or not.\n2) If the **gcd>1** then it means they are non-coprime , so just take the lcm of top value from stack(pop it also) and the current value and push it back to stack.\n\nImpo-\n\n3)Now first I think this will be valid let\'s take an example - \n\n```\nA = [4 2 3 5]\nA = [4,3,5] , 4 and 2 are non-coprime so replace with LCM(4)\nA = [4,3,5] , 4 and 3 are coprime nothing happens\nA = [4,3,5] , 3 and 5 are coprime nothing happens\n```\n\nBut wait , take another example where this is wrong-\n\n```\nA = [5,2,3,6]\nA = [5,2,3,6] , 5 and 2 are coprime nothing happens\nA = [5,2,3,6] , 2 and 3 are coprime nothing happens\nA = [5,2,6] , 3 and 6 are non-coprime so replace with LCM(6)\n\nin last my stack contains [5,2 6], I returned , this is wrong.\n```\n\n**we have to do step 2 , untill we have non-coprime value from the current element and the top element , and then return it.**\n\n\n\n\n```\nclass Solution\n{\n public:\n vector<int> replaceNonCoprimes(vector<int> &a)\n {\n stack<int> st;\n int n = a.size();\n for (int i = 0; i < n; i++)\n {\n int cr = a[i];\n int gcd, LCM, tp;\n while (!st.empty())\n {\n\n int gcd = __gcd(cr, st.top());\n if (gcd > 1)\n {\n tp = st.top();\n st.pop();\n LCM = (cr / gcd) * tp;\n cr = LCM;\n }\n else\n break;\n }\n st.push(cr);\n }\n\n vector<int> ans;\n\n while (!st.empty())\n {\n ans.push_back(st.top());\n st.pop();\n }\n\n reverse(ans.begin(), ans.end());\n\n return ans;\n }\n};\n```\nTime complexity : **NlogD** , where D is **maxA** , correct me if I am wrong.\n\n | 108,165 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 771 | 6 | \tclass Solution {\n\t\tpublic List<Integer> replaceNonCoprimes(int[] nums) \n\t\t{\n\t\t\tList<Integer> al=new ArrayList<>();\n\t\t\tlong n1=nums[0];\n\t\t\tint idx=1;\n\n\t\t\twhile(idx<nums.length)\n\t\t\t{\n\t\t\t\tif((int)gcd(n1,nums[idx])==1)\n\t\t\t\t{\n\t\t\t\t\twhile(al.size()!=0)\n\t\t\t\t\t{\n\t\t\t\t\t\tint t=al.get(al.size()-1);\n\t\t\t\t\t\tif(gcd(n1,t)==1)\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tal.remove(al.size()-1);\n\t\t\t\t\t\t\tn1=lcm(t,n1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tal.add((int)n1);\n\t\t\t\t\tn1=nums[idx];\n\t\t\t\t\tidx++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tn1=lcm(n1,nums[idx]);\n\t\t\t\t\tidx++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile(al.size()!=0)\n\t\t\t{\n\t\t\t\tint t=al.get(al.size()-1);\n\t\t\t\tif(gcd(n1,t)==1)\n\t\t\t\t\tbreak;\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tal.remove(al.size()-1);\n\t\t\t\t\tn1=lcm(t,n1);\n\t\t\t\t}\n\t\t\t} \n\t\t\tal.add((int)n1);\n\n\t\t\treturn al;\n\t\t}\n\n\t\tpublic long gcd(long a,long b)\n\t\t{\n\t\t\tif (b == 0) \n\t\t\t\treturn a; \n\n\t\t\treturn gcd(b, a % b); \n\t\t}\n\n\t\tpublic long lcm(long a,long b)\n\t\t{\n\t\t\tlong hcf=gcd(a,b);\n\t\t\treturn (a*b)/hcf;\n\t\t}\n\t} | 108,167 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 776 | 10 | ## idea\n- we process the numbers from left to right, when processing a number, merge it to the left (with the already processed elements) until we can\'t.\n- maintain the processed elements by a stack.\n## code\n- C++\n```\nclass Solution {\npublic:\n vector<int> replaceNonCoprimes(vector<int>& nums) {\n vector<int> res;\n for (auto num : nums) {\n while (!res.empty() && gcd(res.back(), num) > 1) {\n num = lcm(res.back(), num);\n res.pop_back();\n }\n res.push_back(num);\n }\n return res;\n }\n};\n```\n- Python3\n```\nclass Solution:\n def replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n res = []\n for num in nums:\n while res and gcd(res[-1], num) > 1:\n num = lcm(res[-1], num)\n res.pop()\n res.append(num)\n return res\n```\n- JavaScript (is there any built-in `gcd` or `lcm` in js?)\n```\nfunction gcd(a, b) {\n while (b > 0) {\n a %= b;\n [a, b] = [b, a];\n }\n return a;\n}\nfunction lcm(a, b) {\n return a / gcd(a, b) * b;\n}\n\nvar replaceNonCoprimes = function(nums) {\n let res = new Array();\n for (let num of nums) {\n while (res.length > 0 && gcd(res.at(-1), num) > 1) {\n num = lcm(res.at(-1), num);\n res.pop();\n }\n res.push(num);\n }\n return res;\n};\n```\n- Time Complexity\n\t- `O(n * log(1e8))` as we process each element once, and the complexity of both `gcd(a, b)` and `lcm(a, b)` are known to be `O(log(max(a, b)))`\n- Space Complexity\n\t- `O(n)` used by `res`.\n## Similar Problems\n- Although the concepts are not exactly the same, the code of this problem looks like those related to **monotonic stacks**\n- [LC 496 - Next Greater Element I]() (solve it in linear time)\n- [LC 503 - Next Greater Element II]()\n- [LC 739 - Daily Temperatures]()\n- [LC 402 - Remove K Digits]()\n- [LC 1944 - Number of Visible People in a Queue]()\n- [LC 84 - Largest Rectangle in Histogram]()\n- [LC 85 - Maximum Rectangle]()\n- [LC 1340 - Jump Game V]() | 108,168 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 592 | 7 | ```\nclass Solution {\npublic:\n int gcd(int a, int b) {\n if (b == 0)\n return a;\n return gcd(b, a % b);\n }\n\n int lcm(int a, int b) {\n return (a / gcd(a, b)) * b;\n }\n vector<int> replaceNonCoprimes(vector<int>& nums) {\n vector<int> modified;\n for (int i : nums) {\n int pre = 0, cur = i;\n while (modified.size() && gcd(modified.back(), cur) > 1) {\n pre = modified.back();\n cur = lcm(cur, pre);\n modified.pop_back();\n }\n modified.push_back(cur);\n }\n \n return modified;\n }\n};\n``` | 108,171 |
Replace Non-Coprime Numbers in Array | replace-non-coprime-numbers-in-array | You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y. | Array,Math,Stack,Number Theory | Hard | Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left). | 551 | 5 | **C++ solution with Time Complexity = O(nlog m) and space complexity O(n)**,\nwhere the length of the array and the maximum number present in the array is m.\n## Approach\nLet the final array be ans. \n1. For each number ```curr``` in array ```nums```, check whether it is Coprime with the last number ```top``` of ```ans``` array. Now, we have two possibilities:\n\t\t\ta. If they are Coprime, then insert ```curr``` to ```ans```.\n\t\t\tb. If they are not Coprime, replace ```curr``` with ```LCM (top, curr)``` and pop the last element of ```ans```. Repeat 1 until ```top``` and ```curr``` are not Coprime.\n\n\n```cpp\nclass Solution\n{\n private:\n bool isCoprime(int x, int y)\t// O(logM) where M is max(x, y)\n {\n return gcd(x, y) == 1;\t\t\n }\n int gcd(int x, int y)\t\t\t// O(logM) where M is max(x, y)\n {\n return __gcd(x, y);\t\t\n }\n int lcm(int x, int y)\t\t\t// O(logM) where M is max(x, y)\n {\n long long LCM = x;\n LCM *= y;\n LCM /= gcd(x, y);\n return LCM;\n }\n public:\n vector<int> replaceNonCoprimes(vector<int> &nums)\n {\n\n vector<int> ans;\n int n = nums.size();\n ans.push_back(nums[0]);\n for (int i = 1; i < n; i++)\n {\n int curr = nums[i];\n while (ans.size() && !isCoprime(ans.back(), curr))\n {\n int top = ans.back();\n ans.pop_back();\n curr = lcm(curr, top);\n }\n ans.push_back(curr);\n }\n return ans;\n }\n};\n```\n*If you find this helpful, please consider giving an upvote!!* | 108,185 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 5,339 | 41 | **Method 1: Count and check parity**\n\n```java\n public boolean divideArray(int[] nums) {\n int[] cnt = new int[501];\n for (int n : nums)\n ++cnt[n];\n return IntStream.of(cnt).allMatch(n -> n % 2 == 0);\n }\n```\n\n```python\n def divideArray(self, nums: List[int]) -> bool:\n return all(v % 2 == 0 for v in Counter(nums).values())\n```\n\n---\n\n**Method 2: check parity by boolean array**\n\n```java\n public boolean divideArray(int[] nums) {\n boolean[] odd = new boolean[501];\n for (int n : nums)\n odd[n] = !odd[n];\n return Arrays.equals(odd, new boolean[501]);\n }\n```\n```python\n def divideArray(self, nums: List[int]) -> bool:\n odd = [False] * 501\n for n in nums:\n odd[n] = not odd[n]\n return not any(odd)\n```\n\n---\n\n**Method 3: HashSet** - credit to **@SunnyvaleCA**.\n\n```java\n public boolean divideArray(int[] nums) {\n Set<Integer> seen = new HashSet<>();\n for (int num : nums) {\n if (!seen.add(num)) {\n seen.remove(num);\n }\n }\n return seen.isEmpty();\n }\n```\n```python\n def divideArray(self, nums: List[int]) -> bool:\n seen = set()\n for num in nums:\n if num in seen:\n seen.discard(num)\n else:\n seen.add(num)\n return not seen\n```\nor simplify it to follows: - credit to **@stefan4trivia**\n\n```python\nclass stefan4trivia:\n def divideArray(self, nums: List[int], test_case_number = [0]) -> bool:\n seen = set()\n for n in nums:\n seen ^= {n}\n return not seen\n```\n\n**Analysis:**\n\nTime & space: `O(n)`. | 108,216 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 198 | 5 | # 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:0(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean divideArray(int[] nums) {\n int temp[] = new int[1000];\n for(int i : nums) temp[i]++;\n for(int i=0; i<temp.length; i++){\n if(temp[i]%2!=0) return false;\n }\n return true;\n\n// USING HASHMAP\n\n // Map<Integer,Integer> temp = new HashMap<>();\n // for(int i : nums) temp.put(i,temp.getOrDefault(i,0)+1);\n \n // for(int i : temp.keySet()){\n // if(temp.get(i)%2!=0) return false; \n // }\n // return true;\n }\n}\n``` | 108,217 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 3,538 | 39 | **Please upvote if you find this solution helpful :)**\n**Approach-1 :**\n*Time Complexity - O(Nlog(N))\nSpace Complexity - O(1)*\n**Code:**\n```\nclass Solution {\npublic:\n bool divideArray(vector<int>& nums) \n {\n int n =nums.size();\n sort(nums.begin(), nums.end());\n int i=1;\n while(i<n)\n {\n if(nums[i-1] != nums[i])\n return false;\n i = i+2;\n }\n return true;\n \n }\n};\n```\n**Code:**\n**Approach-2 :**\n*Time Complexity - O(N)\nSpace Complexity - O(N)*\n\n```\nclass Solution {\npublic:\n bool divideArray(vector<int>& nums) {\n int n = nums.size();\n unordered_map<int, int> mpp;\n \n for(int i=0; i<n; i++){\n mpp[nums[i]]++; \n }\n \n //count total pairs\n int totalPairs = 0;\n for(auto it: mpp){\n totalPairs += it.second/2;\n }\n \n return (totalPairs == n/2);\n }\n};\n```\n\n**Please upvote if you find this solution helpful :)** | 108,221 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 1,683 | 12 | Just check that the count of all characters is even.\n\n**C++**\n```cpp\nbool divideArray(vector<int>& nums) {\n int cnt[501] = {};\n for (int n : nums)\n ++cnt[n];\n return all_of(begin(cnt), end(cnt), [](int cnt){ return cnt % 2 == 0; });\n}\n``` | 108,225 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 1,502 | 17 | as even occurence of a number does not affect the XOR, the result should be zero\nbut this approach is not working. What\'s wrong? any idea?\n```\nint xorr=0;\nfor(int i=0; i<nums.size(); i++){\n\txorr^=nums[i];\n}\n\nreturn xorr==0 ;\n``` | 108,228 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 1,128 | 10 | ```\nPls Upvote \n\nclass Solution {\npublic:\n bool divideArray(vector<int>& nums) {\n \n unordered_map<int,int> hello ;\n \n for (int i=0;i<nums.size();i++)\n hello[nums[i]]++ ;\n \n \n for (auto& c:hello)\n if (c.second%2==1)\n return false ;\n \n return true ;\n \n }\n};\n``` | 108,231 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 789 | 16 | Let me know if you have any doubts. I try to answer/help.\n\nPlease upvote if you liked the solution.\n\n```\nvar divideArray = function(nums) {\n const numMap = new Map();\n for (const num of nums) {\n numMap.has(num) ? numMap.delete(num) : numMap.set(num, true);\n }\n return numMap.size === 0;\n};\n``` | 108,233 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 546 | 5 | # 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 public boolean divideArray(int[] nums) {\n Set<Integer>set=new HashSet<>();\n for(int i:nums){\n if(set.contains(i)){\n set.remove(i);\n }else{\n set.add(i);\n }\n }\n return set.size()==0;\n \n }\n}\n``` | 108,236 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 1,779 | 15 | ```\n\n/*\nThing here is that each number\'s frequency must be even,\nSo that they can be in pair that satisfy given condition \n*/\nclass Solution {\n public boolean divideArray(int[] nums) {\n int freq[] = new int[501];\n \n //count freuency\n //O(N)\n for (int i = 0; i < nums.length; i++) {\n freq[nums[i]]++;\n }\n \n //check if frequency is even or not\n //O(500) - O(1)\n for (int f : freq) {\n if (f % 2 != 0) {\n return false;\n }\n }\n \n return true;\n }\n}\n\n```\n\nTC - O(N)\nSC - O(501) or O(1)\n\nFeel free to upvote :) | 108,237 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 588 | 8 | ```\nclass Solution {\n public boolean divideArray(int[] nums) {\n Arrays.sort(nums);\n // int count = 0;\n for( int i = 0; i< nums.length ; i+=2){\n if(nums[i] != nums[i+1]){\n return false;\n }\n }\n return true;\n }\n} | 108,243 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 849 | 5 | # 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 public boolean divideArray(int[] nums) {\n Arrays.sort(nums);\n for(int i=0;i<nums.length-1;i++)\n {\n if(nums[i]==nums[i+1])\n {\n i++;\n continue;\n }\n else \n return false;\n }\n return true;\n }\n}\n``` | 108,248 |
Divide Array Into Equal Pairs | divide-array-into-equal-pairs | You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false. | Array,Hash Table,Bit Manipulation,Counting | Easy | For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even. | 1,075 | 5 | ```\nplease upvote, if you find it useful\n```\n\n\n# Java\n```\nclass Solution {\n public boolean divideArray(int[] nums) {\n int[] n = new int[501];\n for(int i=0;i<nums.length;i++){\n n[nums[i]]++;\n }\n for(int i=0;i<501;i++){\n if(n[i]%2==1) return false;\n }\n return true;\n }\n}\n```\n# C++\n\n```\nclass Solution {\npublic:\n bool divideArray(vector<int>& nums) {\n int n[501]={};\n int size =nums.size();\n for(int i=0;i<size;i++){\n n[nums[i]]++;\n }\n for(int i=0;i<501;i++){\n if(n[i]%2==1) return false;\n }\n return true;\n }\n};\n``` | 108,251 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 6,391 | 177 | # **Intuition**\nIf we add `pattern[0]`, the best option is to add at the begin.\nIf we add `pattern[1]`, the best option is to add at the end.\n<br>\n\n# **Explanation**\nFirstly we\'ll try to find the number of subquence `pattern` in the current string `text`\nIterate every character `c` from input string `text`,\n`cnt1` means the count of character `pattern[0]`,\n`cnt2` means the count of character `pattern[1]`.\n\nIf `c == pattern[1]`, \nit can build up string pattern with every `pattern[0]` before it,\nso we update `res += cnt1` as well as `cnt2++`\n\nIf `c == pattern[0]`, \nwe simply increment `cnt1++`.\n\nThen we consider of adding one more character:\n\nIf we add `pattern[0]`,\nthe best option is to add at the begin,\n`res += cnt2`\n\nIf we add `pattern[1]`,\nthe best option is to add at the end,\n`res += cnt1`\n<br>\n\n# **Tip**\nUse two `if` in my solution,\nto handle the corner case where `pattern[0] == pattern[1]`.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public long maximumSubsequenceCount(String s, String pattern) {\n long res = 0, cnt1 = 0, cnt2 = 0;\n for (int i = 0; i < s.length(); ++i) { \n if (s.charAt(i) == pattern.charAt(1)) { \n res += cnt1; \n cnt2++;\n }\n if (s.charAt(i) == pattern.charAt(0)) { \n cnt1++;\n }\n }\n return res + Math.max(cnt1, cnt2);\n }\n```\n**C++**\n```cpp\n long long maximumSubsequenceCount(string text, string pattern) {\n long long res = 0, cnt1 = 0, cnt2 = 0;\n for (char& c: text) { \n if (c == pattern[1])\n res += cnt1, cnt2++;\n if (c == pattern[0])\n cnt1++;\n }\n return res + max(cnt1, cnt2);\n }\n```\n**Python**\n```py\n def maximumSubsequenceCount(self, text, pattern):\n res = cnt1 = cnt2 = 0\n for c in text:\n if c == pattern[1]:\n res += cnt1\n cnt2 += 1\n if c == pattern[0]:\n cnt1 += 1\n return res + max(cnt1, cnt2)\n```\n<br>\n\n**Follow-up**\nYou can add either character anywhere in text exactly **`K`** times. \nReturn the result.\n | 108,259 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 1,889 | 30 | **Intuition:** the best strategy is to add `pat[0]` as the first letter, or `pat[1]` as the last.\n\nWe go left-to-right, counting `pat[0]` using `cnt0`. Note that `cnt0` starts from `1` - since we added `pat[0]` as the very first character. Every time we find `pat[1]`, we have `cnt0` subsequences\n\nThe same logic is applied when we add `pat[1]` as the last character - we just need to go right-to-left.\n\n**C++**\n```cpp\nlong long maximumSubsequenceCount(string t, string pat) {\n long long cnt0 = 1, cnt1 = 1, res0 = 0, res1 = 0;\n for (int i = 0, j = t.size() - 1; j >= 0; ++i, --j) {\n if (t[i] == pat[1])\n res0 += cnt0;\n if (t[j] == pat[0])\n res1 += cnt1;\n cnt0 += t[i] == pat[0];\n cnt1 += t[j] == pat[1];\n }\n return max(res0, res1);\n}\n``` | 108,261 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 1,750 | 23 | ```\nclass Solution {\n\n public long maximumSubsequenceCount(String s, String p) {\n long ans = 0, max = 0;\n int cnt = 1;\n //Assume adding 0th character of pattern at starting\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == p.charAt(1)) ans += cnt;\n if (s.charAt(i) == p.charAt(0)) cnt++;\n }\n max = Math.max(max, ans);\n ans = 0; cnt = 1;\n //Assume adding second character of pattern at end\n for (int i = s.length() - 1; i >= 0; i--) {\n if (s.charAt(i) == p.charAt(0)) ans += cnt;\n if (s.charAt(i) == p.charAt(1)) cnt++;\n }\n max = Math.max(max, ans);\n return max;\n }\n}\n```\n | 108,262 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 751 | 17 | **The things we need to observe at the start:**\n\n* Only way to maximise the number of subsequence is to either add `pattern[0]` at the start of the given string or to add `pattern[1]` at end of the given string. \n* If we can calculate the number of subsequence in the given string, we can easily calculate the final ans. It would be `ans = num_of_subsequence + max(count(pattern[0]), count(pattern[1]))`. If you wonder why we are adding the count of two character, it is indeed what we discussed in the first point. Either adding pattern[0] at the start or pattern[1] at the end. \n\n**How to calculate the number_of_subsequence?**\n\nWe iterate through every character in the given string and keep track of `count(pattern[0])` and` count(pattern[1])`, Whenever we encounter` pattern[1]`, we know that the `count(pattern[0])` before that character is` number_of_subsequence` possible, so we add that to the total.\n\n**Example:** text = "aabb", pattern = "ab"\n\n**a**abb -> count_a = 1, count_b = 0, total = 0\na**a**bb -> count_a = 2, count_b = 0, total = 0\naa**b**b -> count_a = 2, count_b = 1, total = 2\naab**b** -> count_a = 2, count_b = 2, total = 4\n\n**Talking is cheap:**\n```\nclass Solution:\n def maximumSubsequenceCount(self, text: str, pattern: str) -> int:\n total = count_a = count_b = 0\n for c in text:\n if c == pattern[1]:\n total += count_a\n count_b += 1\n if c == pattern[0]:\n count_a += 1\n \n return total + max(count_a, count_b)\n```\n**Note:** \n\tWe must handle` c == pattern[1]` before` c == pattern[0]`, to overcome cases where `pattern[0] == pattern[1]` | 108,263 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 1,394 | 18 | ```\nclass Solution {\npublic:\n long long cal(string s , string t){\n long long ans = 0;\n unordered_map<char , long long> m;\n for(auto x : s){\n if(x == t[1]){\n ans += m[t[0]];\n }\n m[x]++;\n }\n return ans;\n }\n long long maximumSubsequenceCount(string text, string pattern) {\n long long op1 = cal(pattern[0] + text , pattern);\n long long op2 = cal(text + pattern[1] , pattern);\n return max(op1,op2);\n \n }\n};\n``` | 108,264 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 925 | 8 | ```\nclass Solution\n{\n public:\n long long findAns(string s, string pattern)\n {\n long long int secondChar = 0;\n int n = s.size();\n long long int total = 0;\n for (int i = n - 1; i >= 0; i--)\n {\n int flag = 0;\n if (s[i] == pattern[1])\n {\n flag = 1;\n secondChar++;\n }\n if (s[i] == pattern[0])\n {\n total += secondChar;\n }\n \t// for the case like hh\n if (flag and pattern[0] == pattern[1])\n total--;\n }\n return total;\n }\n long long maximumSubsequenceCount(string text, string pattern)\n {\n \t// add first char to start add last char to last\n return max(findAns(pattern[0] + text, pattern), findAns(text + pattern[1], pattern));\n }\n};\n``` | 108,265 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 657 | 6 | ## Maximize Number of Subsequences in a String\n\nIf have 2 cases\n1. **When pattern[0]==pattern[1]**\n\t* we can calculate the number of occurances of pattern[0] in text which we can say `occ`\n\t* our already existing subquence will be `occ*(occ-1)/2` [sum of n numbers were n=occ-1]\n\t* we can add one pattern[0] to existing text to now the answer will be `(occ+1)*occ/2`\n2. **When pattern[0]!=pattern[1]**\n\t* we can take to pointer `first` which keeps track of occurences of pattern[0] and `second` which keeps track of occurences of pattern[1]\n\t* when ever we find `text[i] == pattern[1]` we can add no of new subsquence found i.e. `occ+=first`\n\t* for e.g. text="abdcadabc" and pattern="ac"\n\t\t* initialy first=0, second=0, and occ=0\n\t\t* at i=0 first=1 and second=0\n\t\t* at i=3 first=1 and second=1 and so we found 1 subsequence occ=1\n\t\t* at i=4 first=2 and at i=6 first=3\n\t\t* at i=8 first=3 and second=2 so we found 3 new subsequences occ+=first = occ+=3 occ=4\n\t* now we are suppoed to add one among pattern[0] and pattern[1] we will **choose the one with least occurance**\n\t* for eg first=3 and second=2\n\t\t* if we add pattern[0], occ+=second occ+=2, occ=6\n\t\t* if we add pattern[1], occ+=first, occ+=3, occ=7\n\n\n### C++ Code\n\n```\nclass Solution {\npublic:\n long long maximumSubsequenceCount(string text, string p) {\n \n int n=text.length();\n if(p[0]==p[1])\n {\n long long ans=0;\n for(int i=0; i<n; i++)\n if(text[i]==p[0])\n ans++;\n \n return ans*(ans+1)/2;\n \n }\n \n int f=0,s=0;\n long long ans=0;\n for(int i=0; i<n; i++)\n {\n if(text[i]==p[0])\n f++;\n if(text[i]==p[1])\n {\n s++;\n ans+=f;\n } \n }\n \n return max(ans+f, ans+s);\n }\n};\n```\n\nIf it helped do upvote :)\n\n | 108,267 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 710 | 5 | See my latest update in repo [LeetCode]()\n\n## Solution 1. Prefix Sum and Suffix Sum\n\nStep 1: count the number of subsequences in `s` without insertion as `sum`.\n\nStep 2: At each index `i`, let `a` be the count of `p[0]` in prefix, and `b` be the count of `p[1]` in the suffix. \n\nIf we append `p[0]`, we get `sum + b` subsequences. IF we append `p[1]`, we get `sum + a` subsequences.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n long long maximumSubsequenceCount(string s, string p) {\n long a = 0, b = 0, sum = 0;\n for (char c : s) b += c == p[1];\n long tmp = b;\n for (char c : s) {\n tmp -= c == p[1]; \n if (c == p[0]) sum += tmp;\n }\n long ans = b;\n for (char c : s) {\n a += c == p[0];\n b -= c == p[1];\n ans = max({ ans, b, a });\n }\n return sum + ans;\n }\n};\n```\n\nIn fact, we can see that, we just need the global maximum of all `a` and `b` values. This leads to solution 2.\n\n\n## Solution 2. Prefix Sum and Suffix Sum\n\nIf we add `p[0]`, the best option is to prepend it at the beginning.\n\nIf we add `p[1]`, the best option is to append it at the end.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n long long maximumSubsequenceCount(string s, string p) {\n long a = 0, b = 0, sum = 0;\n for (char c : s) {\n if (c == p[1]) sum += a;\n a += c == p[0];\n b += c == p[1];\n }\n return sum + max(a, b);\n }\n};\n``` | 108,269 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 540 | 5 | \n1.calculate ans in two ways\n2.first put patter[0] in the beginning of the text and then calculate the answer.\n3.second put pattern[1] in the end of the text and calculate the total pattern.\n4.Return the maximum ans between both of them.\n5.\n```\nclass Solution {\npublic:\n long long maximumSubsequenceCount(string text, string pat) {\n long long ans1=0,ans2=0;\n\n \n// loop for calculate the answer if pattern[0] is in the begingging\n int m=1;\n for(int i=0;i<text.size();i++){\n if(pat[1]==text[i]){\n long long tp=m*1;\n ans1+=tp;\n }\n if(pat[0]==text[i]){\n m++;\n }\n }\n// loof for calculate teh answer if pattern[1] if in the end\n int p=1;\n for(int i=text.size()-1;i>=0;i--){\n if(pat[0]==text[i]){\n long long tp=p*1;\n ans2+=tp;\n }\n if(pat[1]==text[i]){\n p++;\n }\n }\n return max(ans1,ans2);\n \n }\n};\n``` | 108,270 |
Maximize Number of Subsequences in a String | maximize-number-of-subsequences-in-a-string | You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. | String,Greedy,Prefix Sum | Medium | Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer. | 284 | 5 | **Intuition:**\n\nFirst thing we can observe is that our choices are limited-\n- we can add **only 1 character** to given string.\n- we only have **2 characters** from which we can choose.\n- subsequence to form is of **length 2.**\n\nNow, the only thing that is not limited is that we can place a character before or after any character of given string.\nbut, if we give it a thought, we can maximize subsequences by placing the character either at the **start of string or end of the string.**\n\n**Why placing the character at start or at the end of the string will maximize subsequences?**\nLet\'s say `p0` and `p1` are characters at `index 0` and `index 1` respectively in `pattern`.\n\n***Observation** - character `p0` should be before character `p1` to form subsequence in string and vice versa.*\n\nTherefore, to maximize subsequence we have two choices-\n\n**choice 1:** pick character `p0` and place it before all the occurences of `p1` so that `p0` can pair with every `p1` \n**choice 2:** pick character `p1` and place it after all the occurences of `p0` so that `p1` can pair with every `p0` \n\nWe can satisfy *choice 1* by placing `p0` at the start of the string thus making it before every character of string including `p1`.\nSimilarly, by placing `p1` at the end of string ensures *choice 2* as it is after every character of string including `p0`.\n\nNow, our result would be the `max(choice1, choice2)`.\n\n**Code:**\n\n```java\nclass Solution {\n public long maximumSubsequenceCount(String s, String p) {\n \n // choice1: place p0 at the start\n long choice1 = 0;\n int countOfP0 = 1;\n for (int i = 0; i < s.length(); i++)\n {\n // if p1 found, it can be paired with all the p0\'s found till now\n if (s.charAt(i) == p.charAt(1)) choice1 += countOfP0;\n if (s.charAt(i) == p.charAt(0)) countOfP0++;\n }\n \n // choice2: place p1 at the end\n long choice2 = 0;\n int countOfP1 = 1;\n for (int i = s.length() - 1; i >= 0; i--) \n {\n // if p0 found, it can be paired with all the p1\'s found till now \n if (s.charAt(i) == p.charAt(0)) choice2 += countOfP1;\n if (s.charAt(i) == p.charAt(1)) countOfP1++;\n }\n \n return Math.max(choice1, choice2);\n }\n}\n``` | 108,273 |
Minimum Operations to Halve Array Sum | minimum-operations-to-halve-array-sum | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. | Array,Greedy,Heap (Priority Queue) | Medium | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. | 2,324 | 17 | I was thinking that a straightforward solution will get TLE, and we need some clever way to halve large numbers.\n\nThen I realized that large numbers would also reduce `sum` quite a lot, so I went for the straightforward one.\n\n**C++**\n```cpp\nint halveArray(vector<int>& nums) {\n double sum = accumulate(begin(nums), end(nums), 0.0), orig = sum, cnt = 0;\n priority_queue<double> pq(begin(nums), end(nums));\n for (; sum * 2 > orig; ++cnt) {\n double n = pq.top(); pq.pop();\n sum -= n / 2; \n pq.push(n / 2); \n }\n return cnt;\n}\n``` | 108,316 |
Minimum Operations to Halve Array Sum | minimum-operations-to-halve-array-sum | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. | Array,Greedy,Heap (Priority Queue) | Medium | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. | 4,089 | 32 | * First find sum of array\n* Put all the elements in a Max heap or a priority queue such that popping the queue gives you the max element\n* `k` is current sum of halved elements\n* While sum of array - `k` > sum of array / 2, pop an element out of the `pq`, half it, add it to `k` and `pq`\n<iframe src="" frameBorder="0" width="620" height="310"></iframe> | 108,318 |
Minimum Operations to Halve Array Sum | minimum-operations-to-halve-array-sum | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. | Array,Greedy,Heap (Priority Queue) | Medium | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. | 1,520 | 18 | **Q & A**\n*Q1:* Why in `PriorityQueue<Double> pq=new PriorityQueue<>((a,b)->b-a);` the lambda expression does not work with `double`?\n*A1:* Not very sure, but I guess it is because that in Java `Comparator` interface there is only one `int compare(T o1, T o2)` method, of which the return type is `int`. Please refer to [Java 8 Comparator]().\n\nYou can use `Math.signum` to convert `double` to `int` as follows:\n```java\n PriorityQueue<Double> pq = new PriorityQueue<Double>((a, b) -> (int)Math.signum(b - a));\n```\n\n\n*Q2:* `Math.signum()` returns only 3 values(double) i.e `1.0, -1.0, 0.0`. Then how exactly sorting is happening in above lambda expression `(a, b) -> (int)Math.signum(b - a)`?\n*A2:* The returning 3 values are enough for comparing `2` elements in the array.\n\n`Arrays.sort(Object[])` uses Tim sort. The sorting algorithms like Tim Sort, Merge Sort, Quick Sort, and Heap Sort, etc., are comparison (of `2` elements) based. Therefore, we only need to know the result of each comparison between `2` elements: `<`, `=`, `>`, which we can get conclusion from the returning values `-1.0`, `0.0`, `1.0`.\n\n\n*Q3:* How does this work?\n```java\nPriorityQueue pq = new PriorityQueue((a, b) -> b.compareTo(a));\n```\n*A3:* `compareTo` is the method in `Comparable` interface and you can refer to [Java 8 Comparable Interface]().\n\n`int compareTo(T o)`\n\n"Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.\n\n..."\n\n\n*Q4:* And when to use `(b-a)` and when to use `b.compareTo(a)` in lambda expressions?\n*A4:* I would choose `b.compareTo(a)` if `(b - a)` could cause overflow. e.g, `a` and `b` are both `int` or `long` and `a = Integer.MIN_VALUE or Long.MIN_VALUE`.\n\nHowever, in case of no overflow, either is good to use.\n\n**Correct me if I am wrong.**\n\n\n**End of Q & A**\n\n----\n\nAlways reduce current max value by half.\n\n1. Compute the `half` of the sum of the input `nums`;\n2. Put all `nums` into a PriorityQueue/heap by reverse order;\n3. Poll out and cut the current max value by half and add it back to PriorityQueue/ heap, deduct the `half` of the sum accordingly and increase the counter `ops` by 1;\n4. Repeat 3 till `half <= 0`, then return `ops`.\n```java\n public int halveArray(int[] nums) {\n PriorityQueue<Double> pq = new PriorityQueue<>(Comparator.reverseOrder()); \n double half = IntStream.of(nums).mapToLong(i -> i).sum() / 2d;\n for (int n : nums) {\n pq.offer((double)n);\n }\n int ops = 0;\n while (half > 0) {\n double d = pq.poll();\n d /= 2;\n half -= d;\n pq.offer(d);\n ++ops;\n }\n return ops;\n }\n```\n\n```python\n def halveArray(self, nums: List[int]) -> int:\n half, ops = sum(nums) / 2, 0\n heap = [-num for num in nums]\n heapify(heap)\n while half > 0:\n num = -heappop(heap)\n num /= 2.0\n half -= num\n heappush(heap, -num)\n ops += 1\n return ops\n```\n\n**Analysis:**\n\nTime: `O(nlogn)`, space: `O(n)`, where `n = nums.length`. | 108,320 |
Minimum Operations to Halve Array Sum | minimum-operations-to-halve-array-sum | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. | Array,Greedy,Heap (Priority Queue) | Medium | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. | 1,233 | 12 | **Intuition**\n* On observing example cases first idea is to use greedy approach use the maximum value to subtract, because that will help us to attin the goal faster.\n* for example, [5,19,8,1]\n* maximum is 19, so subtract its half, 19-19/2 = 9.5\n* Now array is [5, 9.5, 8, 1]\n* Now maximum is 9.5 so subtract its half, 9.5 - 9.5/2 = 4.75\n* Now array is [5, 4.5, 8, 1], maximum is 8, so now choose 8 and subtract its half\n* Now array is [5, 4, 4, 1]\n* Now as the sum of array becomes at least half of the initial sum so return number of steps\n\n **C++**\n```\nclass Solution {\npublic:\n int halveArray(vector<int>& nums) {\n\t\tpriority_queue<double> pq;\n double totalSum = 0;\n double requiredSum = 0;\n for(auto x: nums){\n totalSum += x;\n pq.push(x);\n }\n \n requiredSum = totalSum/2;\n int minOps = 0;\n while(totalSum > requiredSum){\n double currtop = pq.top();\n pq.pop();\n currtop = currtop/2;\n totalSum -= currtop;\n pq.push(currtop);\n minOps++;\n }\n return minOps;\n\t}\n}\n\t\t\n```\n\n**Python**\n```\nclass Solution:\n def halveArray(self, nums: List[int]) -> int:\n # Creating empty heap\n maxHeap = []\n heapify(maxHeap) # Creates minHeap \n \n totalSum = 0\n for i in nums:\n # Adding items to the heap using heappush\n # for maxHeap, function by multiplying them with -1\n heappush(maxHeap, -1*i) \n totalSum += i\n \n requiredSum = totalSum / 2\n minOps = 0\n \n while totalSum > requiredSum:\n x = -1*heappop(maxHeap) # Got negative value make it positive\n x /= 2\n totalSum -= x\n heappush(maxHeap, -1*x) \n minOps += 1\n \n return minOps\n```\n\n**Upvote if you like and comment if you have doubt** | 108,321 |
Minimum Operations to Halve Array Sum | minimum-operations-to-halve-array-sum | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. | Array,Greedy,Heap (Priority Queue) | Medium | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. | 799 | 7 | At each iteration, we should perform the operation on the maximum element. Because if the element is maximum, it\'s half will also be maximum among all halves. Thus reducing the sum by maximum possible.\n\n- Insert all values in the priotiy queue\n- In each iteration, Pop the maximum element, removed it\'s half from sum. Add back the halved value to PQ if it\'s not zero.\n- Keep repeating untill the half of initial sum becomes zero.\n\n```\nclass Solution {\npublic:\n int halveArray(vector<int>& nums) {\n priority_queue<double> pq;\n long long sum = 0;\n for (int x : nums) {\n sum += x;\n pq.push(x);\n }\n \n double half = (double)sum / 2.0;\n int answer = 0;\n \n while (half > 0) {\n double max = pq.top();\n pq.pop();\n \n max /= 2.0;\n half -= max;\n \n if (max > 0) {\n pq.push(max);\n }\n \n answer++;\n }\n \n return answer;\n }\n};\n``` | 108,323 |
Minimum Operations to Halve Array Sum | minimum-operations-to-halve-array-sum | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. | Array,Greedy,Heap (Priority Queue) | Medium | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. | 648 | 9 | ```\nclass Solution {\npublic:\n int halveArray(vector<int>& nums) {\n double sum = 0;\n\t priority_queue<double> p;\n for(auto x : nums) {\n\t\t sum += x;\n p.push(x);\n\t\t}\n double ans = sum;\n int cnt = 0;\n while(sum > ans/2.0){\n cnt++;\n double top = p.top();\n p.pop();\n sum -= top/2.0;\n top = top/2.0;\n p.push(top);\n }\n return cnt;\n }\n};\n``` | 108,326 |
Minimum Operations to Halve Array Sum | minimum-operations-to-halve-array-sum | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. | Array,Greedy,Heap (Priority Queue) | Medium | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. | 332 | 5 | **Intuition :**\n\n* In order to reduce sum to half in minimum operations, we need to reduce **largest elements first**.\n\n* So that sum can be reduced significantly, in less number of operations.\n* And to get largest elements first, we can use **Max Heap / Priority Queue**.\n\n# Code : \n\n\n```\nclass Solution {\npublic:\n int halveArray(vector<int>& nums) {\n \n double sum = accumulate(nums.begin(), nums.end(), 0.00);\n double halfSum = sum / 2;\n \n priority_queue<double> pq;\n \n for(auto& num : nums) pq.push((double)num);\n \n int operations = 0;\n \n while(pq.size() and sum > halfSum) {\n double item = pq.top(); pq.pop();\n \n sum -= item/2.00;\n \n item /= 2.00;\n \n operations++;\n \n if(item>0) pq.push(item);\n }\n return operations;\n }\n};\n```\n\n**Complexity :**\n\n* Time : `O(NlogN)`\n* Space : `O(N)`\n\n***If you find this helpful, do give it a like :)*** | 108,329 |
Minimum Operations to Halve Array Sum | minimum-operations-to-halve-array-sum | You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half. | Array,Greedy,Heap (Priority Queue) | Medium | It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements. | 407 | 8 | ```\n public static int halveArray(int[] nums) {\n Queue<Double> pq = new PriorityQueue<>(Collections.reverseOrder());\n double sum = 0, cur = 0;\n for(int val : nums){\n sum += val;\n pq.add((double)val);\n }\n int count = 0;\n while(cur < sum/2) {\n double val = pq.poll()/2;\n cur += val;\n pq.add(val);\n count++;\n }\n return count;\n \n \n \n \n }\n``` | 108,332 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 6,135 | 109 | # **Explanation**\n`dp[i][k]` means that,\nusing `k` tiles to cover the first `i` tiles\nthe minimum number of white tiles still visible.\n\n\nFor each tile `s[i]`, we heve two options,\nOne option is doing nothing, `jump` this tile,\n`jump = dp[i - 1][k] + int(s[i - 1])`\nThe other option is covering this tile\n`cover = dp[i - l][k - 1]`\n\nThen we take the minimum result of two options:\n`dp[i][k] = min(jump, cover)`\n\nFinally after explore all combination of `(i,k)`,\nwe return `dp[n][nc]`.\n<br>\n\n# **Complexity**\nTime `O(NC)`\nSpace `O(NC)`\nwhere `N = floor.length` and `C = numCarpets`.\nSpace can be optimized to `O(N)`.\n<br>\n\n**Java**\n```java\n public int minimumWhiteTiles(String s, int nc, int l) {\n int n = s.length(), dp[][] = new int[n + 1][nc + 1];\n for (int i = 1; i <= n; ++i) {\n for (int k = 0; k <= nc; ++k) {\n int jump = dp[i - 1][k] + s.charAt(i - 1) - \'0\';\n int cover = k > 0 ? dp[Math.max(i - l, 0)][k - 1] : 1000;\n dp[i][k] = Math.min(cover, jump);\n }\n }\n return dp[n][nc];\n }\n```\n\n**C++**\n```cpp\n int minimumWhiteTiles(string s, int nc, int l) {\n int n = s.size();\n vector<vector<int>> dp(n + 1, vector<int>(nc + 1));\n for (int i = 1; i <= n; ++i) {\n for (int k = 0; k <= nc; ++k) {\n int jump = dp[i - 1][k] + s[i - 1] - \'0\';\n int cover = k > 0 ? dp[max(i - l, 0)][k - 1] : 1000;\n dp[i][k] = min(cover, jump);\n }\n }\n return dp[n][nc];\n }\n```\n\n**Python3**\n```py\n def minimumWhiteTiles(self, A, k, l):\n\n @lru_cache(None)\n def dp(i, k):\n if i <= 0: return 0\n return min(int(A[i - 1]) + dp(i - 1, k), dp(i - l, k - 1) if k else 1000)\n \n return dp(len(A), k) \n```\n | 108,359 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 2,826 | 55 | Iterate over string `floor`:\n\n- At each index `pos` in the string `floor` we have two options:\n\n - Use a carpet, that starts from the index `pos` and ends at `pos + carpetLength - 1`. All tiles in this part will change to black, hence move to index `pos + carpetLength`\n - Skip the index and move to next index `pos + 1`. This time the tile at index `pos` will be unchanged, thus add `1` to the answer if it\'s a white tile.\n\n- After either of the options, recursively move to the next index. Return the minimum of the above two options.\n\nBase Case:\n\n- If we have traversed the whole string `floor`, then no white tiles present. Hence return `0`.\n- If we have used all the available carpets, then the remaining string will not change. Hence return the number of `1`\'s in the remaining string. (Store the number of `1`s for the suffix `[i, N]` in the array `suffix` beforehand, instead of finding it again and again).\n\nThere will be repeated subproblems corresponding to index (`pos`) and the number of carpet used (`used`). Hence store the result in the table `dp` and use it to answer repeated problems insetad of going into recursion.\n\n```\nclass Solution {\npublic:\n int dp[1001][1001];\n int suffix[1001];\n\n void findSuffixSum(string& floor) {\n int n = floor.size();\n \n suffix[n - 1] = (floor[n - 1] == \'1\');\n for (int i = n - 2; i >= 0; i--) {\n suffix[i] = suffix[i + 1] + (floor[i] == \'1\');\n }\n }\n \n int solve(string& floor, int numCarpets, int carpetLen, int pos, int used) {\n if (pos >= floor.size()) {\n return 0;\n } else if (used == numCarpets) {\n return suffix[pos];\n }\n \n if (dp[pos][used] != -1) {\n return dp[pos][used];\n }\n\n return dp[pos][used] = min(solve(floor, numCarpets, carpetLen, pos + carpetLen, used + 1),\n (floor[pos] == \'1\') + solve(floor, numCarpets, carpetLen, pos + 1, used));\n }\n \n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n memset(dp, -1, sizeof(dp));\n findSuffixSum(floor);\n \n return solve(floor, numCarpets, carpetLen, 0, 0);\n }\n};\n``` | 108,360 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 1,373 | 25 | Problem constraints will help you to understand that this problem can be solved with `dp`. Let the state `dp(i, t)` be minimum number of white tiles when we allowed to use `t` number of carpets such that their right (and hence all carpets) lies in `[0, i]`. Then each moment of time we have option to take carpet or do not take it:\n1. If we take, previous state is `dp(i - L, t - 1)`.\n2. If we do not take it, previous state is `dp(i - 1, t) + `int(floor[i] == "1")`.\n\n#### Complexity\nIt is `O(n^2)` for time and space.\n\n#### Code\n```python\nclass Solution:\n def minimumWhiteTiles(self, floor, k, L):\n @lru_cache(None)\n def dp(i, t):\n if t < 0: return float("inf")\n if i < 0: return 0\n return min(dp(i - L, t - 1), dp(i - 1, t) + int(floor[i] == "1"))\n \n return dp(len(floor) - 1, k)\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 108,361 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 1,151 | 14 | Hello, while it may seem like a difficult one, the fourth question can be done with an almost bruteforce approach with some optimizations.\n\nLet dp[i][j] denote the maximum number of ones we can cover with i carpets till index j(**with current carpet ending exactly at index j**). Assuming that the current carpet ends at exactly j *greatly simplifies* the problem\n\nNow, dp[i][j]= number of ones in string[j:j-len]+ max(dp[i-1][j-len], dp[i-1][j-len-1],....dp[i-1][0])\n\nOptimizations:\nWe store this max part of previous iteration of i till j-len in a helper variable. (prevmax)\nWe use prefix sum array to calculate number of white blocks in a range in O(1) time\nWe only need the ith and i-1th rows of the dp array, so space can be reduced (didn\'t do it due to time constraints during contest)\n\n```\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {\n int dp[1001][1001]={0};\n int pre[1000]={0};\n if(floor[0]==\'1\')pre[0]=1;\n for(int i=1;i<floor.size();i++){\n pre[i]+=pre[i-1];\n if(floor[i]==\'1\')pre[i]++;\n }\n for(int i=1;i<=numCarpets;i++){\n int prevmax=0;\n for(int j=0;j<floor.size();j++){\n if(j<carpetLen) dp[i][j]=pre[j];\n else{\n prevmax=max(prevmax,dp[i-1][j-carpetLen]);\n dp[i][j]=pre[j]-pre[j-carpetLen]+prevmax;\n }\n }\n }\n int ans=0;\n for(int i=0;i<floor.size();i++)ans=max(ans,dp[numCarpets][i]);\n return pre[floor.size()-1]-ans;\n }\n};\n```\n | 108,362 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 1,194 | 9 | See my latest update in repo [LeetCode]()\n\n## Solution 1. Fixed-length Sliding Window + DP\n\n**Intuition**:\n\n1. Use a sliding window of length `carpetLen` to compute a `cover` array where `cover[i]` is the number of white tiles covered by a carpet placed ending at `floor[i]`.\n2. Use DP to calculate the maximum coverable white tiles using `numCarpets` carpets.\n\n**Algorithm**:\n\n**Fixed-length Sliding Window**:\n\nKeep a rolling sum `white` as the number of white tiles within the sliding window.\n\nFor each `i` in range `[0, N)`, we:\n* increment `white` if `s[i] == \'1\'`\n* decrement `white` if `s[i - len] == \'1\'`\n* Set `cover[i] = white`.\n\n**DP**:\n\nLet `dp[i][j + 1]` be the maximum number of coverable white tiles where `1 <= i <= numCarpet` is number of carpets used and `0 <= j < N` is the last index where we can place carpet.\n\nAll `dp` values are initialized as `0`s.\n\nFor each `dp[i][j + 1]`, we have two options:\n1. Don\'t place carpet at index `j`. `dp[i][j+1] = dp[i][j]`\n2. Place carpet ending at index `j` covering `cover[j]` white tiles. And we can place `i-1` carpets at or before `j-carpetLen`. So, `dp[i][j+1] = dp[i-1][j-carpetLen+1] + cover[j]`.\n\n```\ndp[i][j + 1] = max(\n dp[i][j], // don\'t place carpet at index `j`\n (j - carpetLen + 1 >= 0 ? dp[i - 1][j - carpetLen + 1] : 0) + cover[j] // place carpet at index `j`\n )\n```\n\n`dp[numCarpet][N]` is the maximum number of white titles coverable. The answer is the number of total white tiles minus `dp[numCarpet][N]`. \n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N * numCarpet)\n// Space: O(N * numCarpet)\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpet, int carpetLen) {\n int N = floor.size(), sum = 0;\n vector<int> cover(N);\n for (int i = 0, white = 0; i < N; ++i) {\n sum += floor[i] - \'0\';\n white += floor[i] - \'0\';\n if (i - carpetLen >= 0) white -= floor[i - carpetLen] - \'0\'; \n cover[i] = white;\n }\n vector<vector<int>> dp(numCarpet + 1, vector<int>(N + 1));\n for (int i = 1; i <= numCarpet; ++i) {\n for (int j = 0; j < N; ++j) {\n dp[i][j + 1] = max(dp[i][j], (j - carpetLen + 1 >= 0 ? dp[i - 1][j - carpetLen + 1] : 0) + cover[j]);\n }\n }\n return sum - dp[numCarpet][N];\n }\n};\n```\n\nWe can reduce the space complexity to `O(N)` by using rolling arrays.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N * numCarpet)\n// Space: O(N)\nclass Solution {\npublic:\n int minimumWhiteTiles(string floor, int numCarpet, int carpetLen) {\n int N = floor.size(), sum = 0;\n vector<int> cover(N);\n for (int i = 0, white = 0; i < N; ++i) {\n sum += floor[i] - \'0\';\n white += floor[i] - \'0\';\n if (i - carpetLen >= 0) white -= floor[i - carpetLen] - \'0\'; \n cover[i] = white;\n }\n vector<int> dp(N + 1);\n for (int i = 1; i <= numCarpet; ++i) {\n vector<int> next(N + 1);\n for (int j = 0; j < N; ++j) {\n next[j + 1] = max(next[j], (j - carpetLen + 1 >= 0 ? dp[j - carpetLen + 1] : 0) + cover[j]);\n }\n swap(dp, next);\n }\n return sum - dp[N];\n }\n};\n``` | 108,363 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 1,000 | 24 | Imagine we are covering the floor with carpets from left to right. At any point in this exercise, we will be at some point i and have carpetsRemaining carpets remaining. At this point we are only concerned with covering the floor from i to n - 1. \nIn other words i can say that the state at any point is fully defined by (current position, carpets remaining)\n\nWhen we are standing at index i, we have 2 choices\n\t* either skip this tile and leave it uncovered\n\t* use one carpet starting from here.\n\nFirst off, If we are currently on a black tile, it makes no sense to start a new carpet here, so we just move one step to the right. (whatever white tiles we cover by starting here, we can cover from i + 1 and possibly more)\nNow that we are on a white tile, \n\t* If we apply option 1 and skip this tile, we would expose 1 white tile and continue the exercise from tile i + 1 with the same number of carpets remaining\n\t* If we apply option 2 and start a new carpet here, we would use one carpet and continue the exercise from tile i + carpetLen.\n\twe would obviously want to take the option which would expose the minumum number of white tiles. \n\nIf f( i , carpetsRemaining ) represents the minimum number if white tiles exposed for the floor from i to n - 1 with carpetsRemaining carpets remaining, \n//base cases\n* if( i >= n) then ans = 0. ( we have fully covered the floor and are standing to the right of it)\n* if( carpetsRemaining == 0 ) then ans = number of zeroes from i to n - 1. (We dont have any more carpets and will expose everything here on out)\n```\n\tif(i >= a.length) {\n\t\treturn 0;\n\t}\n\tif(carpets_left == 0) {\n\t\treturn suffix[i]; //suffix[i] = number of white tiles from index i to n (can be calculated using a simple for loop)\n\t}\n```\n//recursive cases\n* if( floor[i] == BLACK ) then ans = f ( i + 1, carpetsRemaining). (Just ignore this tile, continue from next index)\n* if( floor[i] == WHITE ) then ans = Max of\n\t\t\t\t\t\t\t\t\t* 1 + f( i + 1, carpetsRemaining) (expose this tile, hence + 1, and continue with same number of carpets)\n\t\t\t\t\t\t\t\t\t* f( i + carpetLen, carpetsRemaining - 1 ) (start a new carpet here, skip carpetLen tiles, but have 1 less carpet)\n\n```\n\t // first check if this state has already been visited, if so return the answer already computed\n\tif(dp[i][carpets_left] != UNVISITED) { \n\t\treturn dp[i][carpets_left];\n\t}\n\tif(a[i] == BLACK) {\n\t\t//this tile is black, skip it\n\t\tdp[i][carpets_left] = f(i + 1, carpets_left, a, dp, suffix, carpetLen);\n\t}\n\telse {\n\t\t//start carpet here\n\t\tint start_carpet_here = f(i + carpetLen, carpets_left - 1, a, dp, suffix, carpetLen);\n\t\t//dont start carpet here\n\t\tint dont_start_carpet_here = 1 + f(i + 1, carpets_left, a, dp, suffix, carpetLen);\n\t\tdp[i][carpets_left] = Math.min(start_carpet_here, dont_start_carpet_here);\n\t}\n\n\treturn dp[i][carpets_left];\n```\n\nThere are (n * numCarpets) states, we momoize the result for each state in a 2D array.\nTime Complexity: O(n * numCarpets)\nSpace Complexity: O(n * numCarpets)\n\nFull Code:\n```\nclass Solution {\n private static final int UNVISITED = -1;\n private static final char BLACK = \'0\';\n private static final char WHITE = \'1\';\n\n private int f(int i, int carpets_left, char[] a, int[][] dp, int[] suffix, int carpetLen) {\n if(i >= a.length) {\n return 0;\n }\n if(carpets_left == 0) {\n return suffix[i];\n }\n if(dp[i][carpets_left] != UNVISITED) {\n return dp[i][carpets_left];\n }\n if(a[i] == BLACK) {\n dp[i][carpets_left] = f(i + 1, carpets_left, a, dp, suffix, carpetLen);\n }\n else {\n //start carpet here\n int start = f(i + carpetLen, carpets_left - 1, a, dp, suffix, carpetLen);\n //dont start carpet here\n int dont = 1 + f(i + 1, carpets_left, a, dp, suffix, carpetLen);\n\n dp[i][carpets_left] = Math.min(start, dont);\n }\n\n return dp[i][carpets_left];\n }\n\n public int minimumWhiteTiles(String floor, int numCarpets, int carpetLen) {\n \n int n = floor.length();\n char[] a = floor.toCharArray();\n \n //calculating the suffix array\n int[] suffix = new int[n + 1];\n for(int i = n - 1; i >= 0; i--) {\n suffix[i] = suffix[i + 1];\n if(a[i] == WHITE) {\n suffix[i] ++;\n }\n }\n \n int[][] dp = new int[n + 1][numCarpets + 1];\n for(int[] row : dp) {\n Arrays.fill(row, UNVISITED);\n }\n\n return f(0, numCarpets, a, dp, suffix, carpetLen);\n }\n}\n```\n | 108,364 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 651 | 8 | ```\nclass Solution {\n int n;\n vector<int> suffix;\n vector<vector<int>> memo;\npublic:\n \n int doit(string& floor, int carp, int len, int ind) {\n if (ind >= n) return 0;\n if (carp == 0) return suffix[ind]; // if no carpets are left then all the white tiles from current index to the last will be visible\n if (memo[carp][ind] != -1) return memo[carp][ind];\n int a = doit(floor, carp-1, len, ind+len); // carpet is used\n int b = doit(floor, carp, len, ind+1) + (floor[ind] == \'1\'); // carpet is not used\n return memo[carp][ind] = min(a, b);\n }\n \n int minimumWhiteTiles(string floor, int carp, int len) {\n \n n = size(floor);\n suffix.resize(n+1, 0);\n memo.resize(carp+1, vector<int>(n+1, -1));\n suffix[n-1] = (floor[n-1] == \'1\');\n for (int i=n-2; ~i; i--)\n suffix[i] = suffix[i+1] + (floor[i] == \'1\');\n \n return doit(floor, carp, len, 0);\n }\n};\n``` | 108,365 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 1,490 | 20 | It feels like there could be some clever way to lay carpets, but there isn\'t. We need to search for an optimal solution.\n\n> Note: problem constrains give it away.\n\nWe start with the top-down approach, and then convert it to the bottom-up one. By analyzing the tabulation, we can reduce the memory usage to O(n). The runtime for the final, memory-optimized bottom-up approach is 120 ms.\n\n#### Top-Down\nFor the search, we can skip positions with black tiles.\n**C++**\n```cpp\nint dp[1001][1001] = {};\nint dfs(string &floor, int i, int n, int len) {\n if (n < 0)\n return floor.size();\n if (floor.size() - i <= n * len)\n return 0;\n if (floor[i] == \'0\')\n return dfs(floor, i + 1, n, len);\n if (dp[i][n] == 0)\n dp[i][n] = 1 + min(1 + dfs(floor, i + 1, n, len), dfs(floor, i + len, n - 1, len)); \n return dp[i][n] - 1;\n}\nint minimumWhiteTiles(string floor, int numCarpets, int len) {\n return dfs(floor, 0, numCarpets, len);\n} \n```\n\n#### Bottom-Up\n**C++**\n```cpp\nint dp[1001][1001] = {};\nint minimumWhiteTiles(string floor, int numCarpets, int len) {\n for (int i = floor.size() - 1; i >= 0; --i) {\n dp[i][0] = dp[i + 1][0] + (floor[i] == \'1\');\n for (int c = 1; c <= numCarpets; ++c)\n dp[i][c] = min(dp[i + 1][c] + (floor[i] == \'1\'), dp[min(1000, i + len)][c - 1]);\n }\n return dp[0][numCarpets];\n} \n```\n\n#### Memory-Optimized Bottom-Up DP\nWe can rearrange loops from the solution above so that the first loop iterates through carpets. That way, we only need to store tabulation values for the current and previous step. \n\n**C++**\n```cpp\nint minimumWhiteTiles(string floor, int numCarpets, int len) {\n int sz = floor.size(), dp[2][1001] = {};\n for (int i = 0; i < sz; ++i)\n dp[0][i + 1] += dp[0][i] + (floor[i] == \'1\'); \n for (int c = 1; c <= numCarpets; ++c)\n for (int i = 0; i < sz; ++i)\n dp[c % 2][i + 1] = min(dp[c % 2][i] + (floor[i] == \'1\'),\n dp[(c + 1) % 2][max(0, i + 1 - len)]);\n return dp[numCarpets % 2][sz];\n} \n``` | 108,366 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 646 | 11 | ```\nclass Solution {\n int pref[];\n\n public int minimumWhiteTiles(String floor, int tot, int len) {\n char a[] = floor.toCharArray();\n this.pref = new int[a.length];\n int c = 0;\n this.dp = new int[a.length + 1][tot + 1];\n for (int d[] : dp) Arrays.fill(d, -1);\n for (int i = 0; i < a.length; i++) {\n if (a[i] == \'1\') c++;\n pref[i] = c;\n }\n return pref[a.length - 1] - solve(0, a, tot, len); // total ones - max removed\n }\n\n int dp[][];\n\n private int solve(int index, char a[], int tot, int len) {\n if (index >= a.length || tot == 0) {\n return 0;\n }\n if (dp[index][tot] != -1) return dp[index][tot];\n int ones = pref[Math.min(index + len - 1, a.length - 1)] - (index == 0 ? 0 : pref[index - 1]);\n int take = ones + solve(index + len, a, tot - 1, len); // either take it and add one\'s count in that subsegment\n int dont = solve(index + 1, a, tot, len); // or dont \n return dp[index][tot] = Math.max(take, dont); // return max of both\n }\n}\n``` | 108,368 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 413 | 7 | ```\nclass Solution\n{\n public:\n int recur(string &s, int numCarpets, int len, int i, vector<vector < int>> &dp, vector< int > &sufOnes)\n {\n if (i >= s.size())\n return 0;\n if (numCarpets == 0)\n return sufOnes[i];\n\n if (dp[i][numCarpets] != -1)\n {\n return dp[i][numCarpets];\n }\n if (s[i] == \'0\')\n {\n dp[i][numCarpets] = recur(s, numCarpets, len, i + 1, dp, sufOnes);\n }\n else\n {\n \t//start carpet here\n int start = recur(s, numCarpets - 1, len, i + len, dp, sufOnes);\n \t//dont start carpet here\n int dont = 1 + recur(s, numCarpets, len, i + 1, dp, sufOnes);\n\n dp[i][numCarpets] = min(start, dont);\n }\n\n return dp[i][numCarpets];\n }\n int minimumWhiteTiles(string s, int n, int len)\n {\n int nn = s.size() + 1, mm = n + 1;\n vector<int> sufOnes(s.size() + 1, 0);\n for (int i = s.size() - 1; i >= 0; i--)\n {\n sufOnes[i] = sufOnes[i + 1];\n if (s[i] == \'1\')\n {\n sufOnes[i]++;\n }\n }\n vector<vector < int>> dp(nn, vector<int> (mm, -1));\n return recur(s, n, len, 0, dp, sufOnes);\n }\n};\n``` | 108,369 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 238 | 5 | ```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n n = len(floor)\n if carpetLen*numCarpets >= n:\n return 0\n floorlist = []\n for i in floor:\n if i == \'1\':\n floorlist.append(1)\n else:\n floorlist.append(0)\n dp=[[0] * n for i in range(numCarpets)]\n \n for i in range(carpetLen, n):\n dp[0][i] = min(floorlist[i] + dp[0][i-1], sum(floorlist[:i - carpetLen + 1]))\n for j in range(1, numCarpets):\n for i in range(carpetLen * j, n):\n dp[j][i] = min(floorlist[i] + dp[j][i - 1], dp[j - 1][i - carpetLen])\n return dp[-1][-1]\n``` | 108,371 |
Minimum White Tiles After Covering With Carpets | minimum-white-tiles-after-covering-with-carpets | You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible. | String,Dynamic Programming,Prefix Sum | Hard | Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not. | 586 | 6 | ```\n\tvector<vector<int>> dp;\n int func(int i,string& s,int car,int len){\n if(i>=s.size()) return 0;\n if(dp[i][car]!=-1) return dp[i][car];\n if(s[i]==\'0\') return dp[i][car]=func(i+1,s,car,len);\n else{ \n int ans=INT_MAX;\n ans=1+func(i+1,s,car,len);\n if(car>0) ans=min(ans,func(i+len,s,car-1,len));\n return dp[i][car]=ans;\n }\n }\n int minimumWhiteTiles(string s, int car, int len) {\n dp=vector<vector<int>>(s.size(),vector<int>(car+1,-1));\n return func(0,s,car,len);\n } | 108,372 |
Most Frequent Number Following Key In an Array | most-frequent-number-following-key-in-an-array | You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. | Array,Hash Table,Counting | Easy | Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it. | 2,278 | 45 | **C++**\n```cpp\nint mostFrequent(vector<int>& nums, int key) {\n int cnt[1001] = {}, res = 0;\n for (int i = 1; i < nums.size(); ++i)\n if (nums[i - 1] == key && ++cnt[nums[i]] > cnt[res])\n res = nums[i];\n return res;\n}\n``` | 108,414 |
Most Frequent Number Following Key In an Array | most-frequent-number-following-key-in-an-array | You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. | Array,Hash Table,Counting | Easy | Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it. | 2,909 | 26 | **Java**\n```java\n public int mostFrequent(int[] nums, int key) {\n Map<Integer, Integer> freq = new HashMap<>();\n int mostFreq = -1;\n for (int i = 0, n = nums.length, max = 0; i + 1 < n; ++i) {\n if (nums[i] == key) {\n int candidate = nums[i + 1];\n freq.put(candidate, 1 + freq.getOrDefault(candidate, 0));\n if (freq.get(candidate) > max) {\n max = freq.get(candidate);\n mostFreq = candidate;\n }\n }\n }\n return mostFreq;\n }\n```\nOr make the above simpler as follows:\n\n```java\n public int mostFrequent(int[] nums, int key) {\n Map<Integer, Integer> freq = new HashMap<>();\n int mostFreq = nums[0];\n for (int i = 0, n = nums.length; i + 1 < n; ++i) {\n if (nums[i] == key && \n freq.merge(nums[i + 1], 1, Integer::sum) > \n freq.get(mostFreq)) {\n mostFreq = nums[i + 1];\n }\n }\n return mostFreq;\n }\n```\n\n----\n\n**Python 3**\n\n```python\n def mostFrequent(self, nums: List[int], key: int) -> int:\n c = Counter()\n for i, n in enumerate(nums):\n if n == key and i + 1 < len(nums):\n c[nums[i + 1]] += 1\n return c.most_common(1)[0][0]\n```\n\nOne liner for fun: - credit to **@stefan4trivia**.\n\n```python\n def mostFrequent(self, nums: List[int], key: int) -> int:\n return statistics.mode(b for a, b in itertools.pairwise(nums) if a == key)\n``` | 108,415 |
Most Frequent Number Following Key In an Array | most-frequent-number-following-key-in-an-array | You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. | Array,Hash Table,Counting | Easy | Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it. | 961 | 6 | class Solution {\npublic:\n int mostFrequent(vector<int>& nums, int key) {\n unordered_map<int, int> mp;\n \n for(int i=0; i<nums.size()-1; i++){\n if(nums[i]==key)\n mp[nums[i+1]]++; //increase target frequency\n }\n \n int mx = INT_MIN;\n int target = -1;\n for(auto &it: mp){\n if(it.second > mx){ //highest target count\n mx = it.second;\n target = it.first; //store target(element)\n }\n }\n \n return target;\n }\n};\n\n\n//please upvote if u like the solution:) | 108,417 |
Most Frequent Number Following Key In an Array | most-frequent-number-following-key-in-an-array | You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. | Array,Hash Table,Counting | Easy | Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it. | 841 | 6 | ```\nclass Solution {\n public int mostFrequent(int[] nums, int key) {\n HashMap<Integer, Integer> map = new HashMap<>();\n int ans=-1;\n int max=Integer.MIN_VALUE;\n for(int i = 0; i<nums.length-1; i++){\n if(nums[i]==key){\n \n if(!map.containsKey(nums[i+1])){\n map.put(nums[i+1], 1);\n }\n else{\n int x = map.get(nums[i+1]);\n map.put(nums[i+1], ++x);\n }\n if(map.get(nums[i+1])>max){\n max=map.get(nums[i+1]);\n ans=nums[i+1];\n }\n }\n }\n return ans;\n }\n}\n``` | 108,420 |
Most Frequent Number Following Key In an Array | most-frequent-number-following-key-in-an-array | You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. | Array,Hash Table,Counting | Easy | Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it. | 1,241 | 10 | ```\nclass Solution {\npublic:\n int mostFrequent(vector<int>& nums, int key) {\n unordered_map<int,int> umap;\n int count=0;\n int ans=nums[0];\n for(int i=0;i<nums.size()-1;i++)\n {\n if(nums[i]==key)\n {\n umap[nums[i+1]]++;\n if(umap[nums[i+1]]>count)\n {\n count=umap[nums[i+1]];\n ans=nums[i+1];\n }\n }\n \n }\n return ans;\n }\n};\n```\n**Like it? Please Upvote :-)** | 108,425 |
Most Frequent Number Following Key In an Array | most-frequent-number-following-key-in-an-array | You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. | Array,Hash Table,Counting | Easy | Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it. | 773 | 8 | **Solution - Count by hand**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n counts = {}\n \n for i in range(1,len(nums)):\n if nums[i-1]==key:\n if nums[i] not in counts: counts[nums[i]] = 1\n else: counts[nums[i]] += 1\n \n return max(counts, key=counts.get)\n```\n\n**Solution - Counter**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n arr = [nums[i] for i in range(1,len(nums)) if nums[i-1]==key]\n c = Counter(arr)\n return max(c, key=c.get)\n```\n\n**One-Liner - Counter**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n return max(c := Counter([nums[i] for i in range(1,len(nums)) if nums[i-1]==key]), key=c.get)\n```\n\n**One-Liner - Mode**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n return mode(nums[i] for i in range(1,len(nums)) if nums[i-1]==key)\n```\n\n**One-Liner - Mode with Pairwise** (Credit: [stefan4trivia]()):\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n return mode(b for a, b in pairwise(nums) if a == key)\n``` | 108,431 |
Most Frequent Number Following Key In an Array | most-frequent-number-following-key-in-an-array | You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique. | Array,Hash Table,Counting | Easy | Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it. | 489 | 5 | ## Core Strategy\n\nIt\'s another counting problem. What we need to do is:\n- counting the frequency for every `target`\n- find out the number with the max frequency\n\nIt\'s easy to think about using a 2 times traversal - 1 time for counting and another time for finding the max.\nBut, actually, we could finish it in just 1-time traversal by maintaining a variable of the max frequency.\n\n## Count with map\n\nWe just follow the strategy, use a map to save the frequency, nothing more.\n\nHere\'s a sample code from me:\n\n```js\nconst mostFrequent = (nums, key) => {\n const freq = {};\n let ret = 0;\n for (let i = 0, max = 0; i < nums.length - 1; ++i) {\n if (nums[i] !== key) continue;\n const target = nums[i + 1];\n freq[target] = (freq[target] || 0) + 1;\n if (freq[target] > max) {\n max = freq[target];\n ret = target;\n }\n }\n return ret;\n};\n```\n\n## Count with array\n\nWe use a fixed-length array to save the frequency, and I try to make the code shorter.\n\nHere\'s a sample code from me:\n\n```js\nconst mostFrequent = (nums, key) => {\n const freq = new Uint16Array(1001);\n let ret = 0;\n for (let i = 0, max = 0; i < nums.length - 1; ++i) {\n const target = nums[i + 1];\n nums[i] === key && ++freq[target] > max && ((max = freq[target]), (ret = target));\n }\n return ret;\n};\n``` | 108,434 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 4,113 | 80 | Duplicates could be tricky to handle. For that, we use a second pointer (`j`), which we update only when we detect a hill or a valley.\n\n**C++**\n```cpp\nint countHillValley(vector<int>& nums) {\n int res = 0;\n for (int i = 1, j = 0; i < nums.size() - 1; ++i)\n if ((nums[j] < nums[i] && nums[i] > nums [i + 1]) || \n (nums[j] > nums[i] && nums[i] < nums [i + 1])) {\n ++res;\n j = i;\n } \n return res;\n}\n``` | 108,462 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 5,300 | 48 | ```\nclass Solution {\npublic:\n int countHillValley(vector<int>& nums) {\n\t// taking a new vector\n vector<int>v;\n v.push_back(nums[0]);\n\t\t//pushing unique elements into new vector\n for(int i=1;i<nums.size();i++){\n if(nums[i]!=nums[i-1]){\n v.push_back(nums[i]);\n }\n }\n int c=0;\n\t\t//checking for valley or hill\n for(int i=1;i<v.size()-1;i++){\n if(v[i]>v[i-1] and v[i]>v[i+1] or v[i]<v[i-1] and v[i]<v[i+1]){\n c++;\n }\n }\n return c;\n }\n};\n``` | 108,463 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 4,930 | 54 | ```java\n public int countHillValley(int[] a){\n int r = 0, left = a[0];\n for(int i = 1; i < a.length - 1; i++)\n if(left < a[i] && a[i] > a[i + 1] || left > a[i] && a[i] < a[i + 1]){\n r++;\n left = a[i];\n }\n return r;\n } | 108,464 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 2,979 | 56 | We start by taking a for loop which goes from 1 to length of array -1.\nSince we cannot take 2 adjacent values such that nums[i] == nums[j]. \nSo, we update the current value to previous value which will help us in counting the next hill or valley. \n\nTime complexity = O(n)\nSpace complexity = O(1)\n\n```class Solution:\n def countHillValley(self, nums: List[int]) -> int:\n hillValley = 0\n for i in range(1, len(nums)-1):\n if nums[i] == nums[i+1]:\n nums[i] = nums[i-1]\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]: #hill check\n hillValley += 1\n if nums[i] < nums[i-1] and nums[i] < nums[i+1]: #valley check\n hillValley += 1\n return hillValley\n``` | 108,465 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 1,761 | 12 | ```\nclass Solution {\npublic:\n int countHillValley(vector<int>& nums) {\n int ans = 0, n = nums.size();\n for(int i = 1; i < n; i++){\n if(nums[i] == nums[i-1]) continue; // same hill or valley\n \n int idx = i - 1, jdx = i + 1;\n while(idx >= 0 && nums[idx] == nums[i]) idx--;\n if(idx < 0) continue; // no left neighbour found\n\t\t\t\n while(jdx < n && nums[jdx] == nums[i]) jdx++;\n if(jdx == n) continue; // no right neighbour found\n \n if(nums[idx] < nums[i] && nums[jdx] < nums[i]) ans++;\n else if(nums[idx] > nums[i] && nums[jdx] > nums[i]) ans++;\n }\n return ans;\n }\n};\n``` | 108,470 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 1,017 | 10 | ```\nclass Solution:\n def countHillValley(self, nums: List[int]) -> int:\n res = 0\n candidate = last_num = None\n \n for i in range(1, len(nums)):\n if nums[i] != nums[i-1]:\n if candidate and ((candidate > last_num and candidate > nums[i]) or (candidate < last_num and candidate < nums[i])):\n res += 1\n candidate = nums[i]\n last_num = nums[i-1]\n \n return res\n``` | 108,471 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 1,654 | 11 | Problem: Finding the non-equal nearest neighbours on both the sides of an array element and comparing those values to decide a peak or valley. It is simple if we there are no duplicate values next to each.\n\nFor the adjacent duplicates we have to keep track of the closest neighbour on left and not update it till duplicates are crossed. \n\nOnce the adjacent duplicates are done, we can update it for the newer values .\n\n```\npublic int countHillValley(int[] nums) {\n int ans = 0;\n int prev = nums[0];\n for(int i = 1; i < nums.length-1; i++){\n if((nums[i] > nums[i+1] && nums[i] > prev || (nums[i] < nums[i+1] && nums[i] < prev)))\n ans++;\n if(nums[i] != nums[i+1]){\n prev = nums[i];\n }\n }\n return ans;\n }\n\t``` | 108,473 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 2,076 | 18 | \n class Solution {\n public int countHillValley(int[] nums) {\n int result = 0;\n \n\t\t\t// Get head start. Find first index for which nums[index] != nums[index-1]\n\t\t\tint start = 1;\n\t\t\twhile(start < nums.length && nums[start] == nums[start-1])\n\t\t\t\tstart++;\n\n\t\t\tint prev = start-1; //index of prev different value num\n\t\t\tfor(int i=start; i<nums.length-1; i++) {\n\t\t\t\tif(nums[i] == nums[i+1]) //If numbers are same, simply ignore them\n\t\t\t\t\tcontinue;\n\t\t\t\telse {\n\t\t\t\t\tif(nums[i] > nums[prev] && nums[i] > nums[i+1]) //compare current num with prev number and next number\n\t\t\t\t\t\tresult++;\n\t\t\t\t\tif(nums[i] < nums[prev] && nums[i] < nums[i+1])\n\t\t\t\t\t\tresult++;\n\t\t\t\t\tprev = i; // Now your current number will become prev number.\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t} | 108,475 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 290 | 5 | ```cpp\nint countHillValley(vector<int>& nums) {\n\tnums.erase(unique(nums.begin(), nums.end()), nums.end()); // this removes equal adjacent numbers\n\tint n = 0;\n\tfor(int i = 1; i < nums.size() -1; ++i)\n\t\tn += (nums[i-1] < nums[i] && nums[i] > nums[i+1]) // hill\n\t\t || (nums[i-1] > nums[i] && nums[i] < nums[i+1]); // valley\n\treturn n;\n}\n```\n\nAs suggested by @izackwu, detection of hill or valley can be reduced :\n```cpp\nint countHillValley(vector<int>& nums) {\n\tnums.erase(unique(nums.begin(), nums.end()), nums.end()); // this removes equal adjacent numbers\n\tint n = 0;\n\tfor(int i = 1; i < nums.size() -1; ++i)\n\t\tn += (nums[i - 1] > nums[i]) == (nums[i] < nums[i + 1]); // hill or valley\n return n;\n}\n```\n\nJust for the fun of ccode golfing, we can even drop it to 2 lines using (or abusing) `std::count_if` :\n\n```cpp\nint countHillValley(vector<int>& nums) {\n\tnums.erase(unique(nums.begin(), nums.end()), nums.end()); \n\treturn nums.size()>2?count_if(next(nums.begin()), prev(nums.end()),[](const int& a) {return (*(&a-1) > a) == (a < *(&a+1));}):0;\n}\n``` | 108,478 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 968 | 7 | The idea of this problem is pretty simple, we wish to count the number of Valleys and Hills in the array.\nThe solution used in this problem is focused on simplicity and being easy to understand.\nThis is O(n) time complexity, and O(n) memory complexity.\n\n**Strategy:**\n\nSo, to find if a number is a hill or a valley, we need to see if the neighboring values that aren\'t the same are both an increase or decrease relative to this number.\n\nStep 1:\n\nMake sure that there are no neighboring nodes of the same values, so turning something like ``[6,7,7,7,8,8,9,2] -> [6,7,8,9,2]``.\n\nStep 2:\n\nLoop through the array starting at the 2nd index and up to the 2nd last index, and increase the return value if a nodes neighbors are both greater than or less than the node.\n\n**Solution:**\n\n**C++**\n\n```\nint countHillValley(vector<int>& ns) {\n //Step 1\n std::vector<int> nums;\n int l = ns[0];\n nums.push_back(l);\n for (int n : ns) {\n if (n != l) {\n nums.push_back(n);\n l = n;\n }\n }\n \n //Step 2.\n int ret = 0;\n for (int i = 1; i < nums.size() - 1; i++) {\n if (nums[i-1] < nums[i] == nums[i+1] < nums[i]) ret++;\n }\n return ret;\n}\n```\n\n**Python**\n\n```\ndef countHillValley(self, ns: List[int]) -> int:\n #Step 1\n nums = []\n l = ns[0]\n nums.append(l)\n for n in ns:\n if n != l:\n nums.append(n)\n l = n\n \n #Step 2\n ret = 0\n for i in range (1, len(nums) - 1):\n if ((nums[i-1] < nums[i]) == (nums[i+1] < nums[i])):\n ret += 1\n \n return ret\n```\n\n**Javascript**\n\n```\nvar countHillValley = function(ns) {\n //Step 1\n nums = [];\n let l = ns[0];\n nums.push(l);\n for (let i = 0; i < ns.length; i++) {\n n = ns[i];\n if (n != l) {\n l = n;\n nums.push(n);\n }\n }\n\n \n //Step 2\n let ret = 0;\n for (let i = 1; i < nums.length - 1; i++) {\n if (nums[i-1] < nums[i] == nums[i+1] < nums[i]) ret++;\n }\n \n return ret; \n};\n```\n | 108,481 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 450 | 7 | By removing side-by-side duplicates, we can shorten the array and remove the need for code that would tell us if a number was part of a previous valley or hill. We then have our loop ignore the edges of the array, as our code tests each number against the one before & after it.\n\n```\nvar countHillValley = function(nums) {\n let answer = 0;\n nums = nums.filter((a, i, b) => a !== b[i + 1]); // Remove Flatlands\n for (let i = 1; i < nums.length - 1; i++) {\n if (nums[i - 1] > nums [i] && nums[i] < nums[i + 1]) answer++; // Valley\n if (nums[i - 1] < nums [i] && nums[i] > nums[i + 1]) answer++; // Hill\n }\n return answer;\n};\n``` | 108,486 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 455 | 6 | Only move the previous pointer when we have a hill or valley.\nElse keep that pointer, never move it.\n\n```\nclass Solution {\n public int countHillValley(int[] nums) {\n int length = nums.length;\n int countHillValley = 0;\n int previous = nums[0];\n for (int i = 1; i < length - 1; i++) {\n if (previous < nums[i] && nums[i] > nums[i + 1] || previous > nums[i] && nums[i] < nums[i + 1]) {\n previous = nums[i];\n countHillValley++;\n }\n }\n return countHillValley;\n }\n}\n``` | 108,490 |
Count Hills and Valleys in an Array | count-hills-and-valleys-in-an-array | You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums. | Array | Easy | For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted. | 407 | 6 | ```\npublic int countHillValley(int[] nums) {\n int left = nums[0];\n int result = 0;\n\n for (int i = 1; i < nums.length - 1; i++) {\n if (isHill(left, nums[i], nums[i + 1]) || isValley(left, nums[i], nums[i + 1])) {\n result++;\n left = nums[i];\n }\n }\n return result;\n }\n\n private boolean isHill(int left, int value, int right) {\n return value > left && value > right;\n }\n\n private boolean isValley(int left, int value, int right) {\n return value < left && value < right;\n } | 108,497 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 5,695 | 279 | ```\n/*\ncars on left side which are moving in left direction are never going to collide,\nSimilarly, cars on right side which are moving right side are never going to collide.\n\nIn between them every car is going to collide.\n*/\n\nclass Solution {\n public int countCollisions(String directions) {\n int left = 0, right = directions.length() - 1;\n \n while (left < directions.length() && directions.charAt(left) == \'L\') {\n left++;\n }\n \n while (right >= 0 && directions.charAt(right) == \'R\') {\n right--;\n }\n \n int count = 0;\n for (int i = left; i <= right; i++) {\n if (directions.charAt(i) != \'S\') {\n count++;\n }\n }\n\t\t//combining these three loops - TC : O(N).\n \n return count;\n }\n}\n```\n\nTC : O(N)\nSC : O(1)\n\nFeel free to upvote : ) | 108,511 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 6,300 | 124 | **Similar Question :-** [ ]\n**C++ Solution**\n\n```\nclass Solution {\npublic:\n int countCollisions(string dir) {\n \n int res(0), n(size(dir)), i(0), carsFromRight(0);\n \n while (i < n and dir[i] == \'L\') i++; // skipping all the cars going to left from beginning as they will never collide\n \n for ( ; i<n; i++) {\n if (dir[i] == \'R\') carsFromRight++;\n else {\n // if dir[i] == \'S\' then there will be carsFromRight number of collission\n // if dir[i] == \'L\' then there will be carsFromRight+1 number of collision (one collision for the rightmost cars and carsFromRight collision for the cars coming from left)\n res += (dir[i] == \'S\') ? carsFromRight : carsFromRight+1;\n carsFromRight = 0;\n }\n }\n return res;\n }\n};\n```\n\n**Java Solution**\n\n```\nclass Solution {\n public int countCollisions(String dir) {\n \n int res = 0, n = dir.length(), i = 0, carsFromRight = 0;\n \n while (i < n && dir.charAt(i) == \'L\') i++;\n \n for ( ; i<n; i++) {\n if (dir.charAt(i) == \'R\') carsFromRight++;\n else {\n res += (dir.charAt(i) == \'S\') ? carsFromRight : carsFromRight+1;\n carsFromRight = 0;\n }\n }\n return res;\n }\n}\n```\n**Python Solution**\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n \n res, n, i, carsFromRight = 0, len(directions), 0, 0\n \n while i < n and directions[i] == \'L\':\n i+=1\n \n while i<n:\n if directions[i] == \'R\':\n carsFromRight+=1\n else:\n res += carsFromRight if directions[i] == \'S\' else carsFromRight+1;\n carsFromRight = 0\n i+=1\n \n return res\n```\n**Upvote if it helps :)** | 108,513 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 5,054 | 75 | What a Stupid problem! There are so many unclear cases need to be decribed better: should we consider the collision before/after the each pair or so???\n\n**If you are trying to practice the algorithm and sharpen your interview skills, I will do you a favor to tell you to SKIP this STUPID question with no doubt!!**\n\n```\npublic int countCollisions(String directions) {\n char[] s = directions.toCharArray();\n int n = s.length;\n int ans = 0;\n for(int i = 0;i < n;i++){\n if(s[i] == \'S\'){\n for(int j = i-1;j >= 0;j--){\n if(s[j] == \'R\'){\n ans++;\n }else{\n break;\n }\n }\n for(int j = i+1;j < n;j++){\n if(s[j] == \'L\'){\n ans++;\n }else{\n break;\n }\n }\n }\n }\n for(int i = 0;i < n-1;i++){\n if(s[i] == \'R\' && s[i+1] == \'L\'){\n ans += 2;\n for(int j = i-1;j >= 0;j--){\n if(s[j] == \'R\'){\n ans++;\n }else{\n break;\n }\n }\n for(int j = i+2;j < n;j++){\n if(s[j] == \'L\'){\n ans++;\n }else{\n break;\n }\n }\n }\n }\n \n return ans;\n }\n``` | 108,514 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 2,040 | 74 | All the cars that move to the middle will eventually collide.... \n\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n return sum(d!=\'S\' for d in directions.lstrip(\'L\').rstrip(\'R\'))\n``` | 108,515 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 2,241 | 37 | ```\n\n\n/*\nIn the case LLRR : there will be no collisions since two cars are moving towards Left and two cars moving towards right\n<- <- -> ->\n L L R R \n\nIn the case RRRRLL : \n-> -> -> -> <- <- \nR R R R L L \n0 1 2 3 4 5\n\n Cars 3 and 4 collide and become stationary (S), since cars 0, 1, 2 are moving towards this stationary car so they will all \n collide and cars 4 and 5 are moving towards the same stationary card from the left direction so even they will collide and \n become stationary (S). We will store cars 0,1,2, 3 in stack and when current car is driving towards left we pop 3 and change \n the current car\u2019s state to stationary and pop rest of the cars driving towards it from the right direction and calculate the \n collision value. \n\nIn the case RSLRL: \n\n-> | <- -> <-\nR S L R L \n0 1 2 3 4\n\nCar 0 collides with the stationary car 1, car 2 collides with the stationary car 1 and cars 3 and 4 collide with each other. \n\n*/\n public int countCollisions(String directions) {\n \n int collisions = 0;\n Stack<Character> stack = new Stack();\n stack.push(directions.charAt(0));\n for(int i = 1;i<directions.length();i++){\n char curr = directions.charAt(i);\n \n if((stack.peek()== \'R\' && curr == \'L\') ){\n \n collisions+=2;\n stack.pop();\n curr = \'S\';\n \n\n }else if((stack.peek() == \'S\' && curr == \'L\')){\n curr = \'S\';\n collisions+=1;\n }\n \n while(!stack.isEmpty() && ((stack.peek() == \'R\' && curr == \'S\') )){\n collisions+=1;\n stack.pop();\n }\n \n stack.push(curr);\n }\n \n return collisions;\n } | 108,518 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 1,527 | 23 | I originally solved this problem using simulation (see below). But later I realized that all cars, except cars on the left moving left and cars on the right moving right, will collide.\n\n#### Counting\n**C++**\n```cpp\nint countCollisions(string d) {\n int l = d.find_first_not_of("L"), r = d.find_last_not_of("R");\n return l == string::npos || r == string::npos ? 0 : \n count_if(begin(d) + l, begin(d) + r + 1, [](char ch){ return ch != \'S\';});\n}\n```\n\n#### Simulation\n**C++**\n```cpp\nint countCollisions(string directions) {\n int right = 0, res = 0, obstacle = false;\n for (char d : directions)\n if (d == \'R\')\n ++right;\n else if (d == \'S\') {\n res += right;\n right = 0;\n obstacle = true;\n }\n else {\n if (right > 0) {\n res += right + 1;\n right = 0;\n obstacle = true;\n }\n else if (obstacle)\n ++res;\n }\n return res;\n}\n``` | 108,520 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 397 | 8 | x|x|x|x|x|x|x|x|x|x|x|x|\n\nimage all the x are moveing left, every point can be potentially blocked (that is, if there is a S, and R before those x, they all being blocked), and vice versa\n\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n \n ans = 0\n L_block = 0\n R_block = 0\n \n \n for ch in directions:\n if ch == "L":\n ans += L_block\n else:\n L_block = 1\n \n for ch in directions[::-1]:\n if ch == "R":\n ans += R_block \n else:\n R_block = 1\n \n return ans\n \n # time---N, space---1\n``` | 108,521 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 1,378 | 16 | **Code:**\n```\nint countCollisions(string dir) {\n int n = dir.size();\n stack<char> s;\n int ans = 0;\n for(int i=0; i<n; i++)\n {\n if(s.empty()) s.push(dir[i]);\n else if( (s.top() == \'S\') && (dir[i] == \'L\')) ans++;\n else if(s.top() == \'R\' && (dir[i] == \'L\')) {\n s.pop();\n dir[i] = \'S\';\n i--;\n ans += 2;\n }\n else if( (s.top() == \'R\') && (dir[i] == \'S\')){\n s.pop();\n dir[i] = \'S\';\n i--;\n ans++;\n }\n else{\n s.push(dir[i]);\n }\n }\n return ans;\n}\n``` | 108,522 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 540 | 5 | ## **Solution**\n\n#### **Logic**\n- For all ```R``` look for next index, Whenever you get collison change current index and next index to ```S```\n- For all ```L``` look previous index, Whenever you get collison change current index and previous index to ```S```\n- For all ```S```, skip it\n- Whenever you change current index to ```S```, look backward for all continous occuring ```R```\n\n#### **Code**\n\n```cpp\nclass Solution {\npublic:\n int countCollisions(string directions) {\n int sol = 0;\n \n for (int j = 0; j < directions.size(); j++) {\n if (directions[j] == \'S\') {\n continue;\n }\n if (j + 1 < directions.size() && directions[j] == \'R\' && directions[j + 1] != \'R\') {\n if (directions[j + 1] == \'L\') {\n directions[j + 1] = \'S\';\n sol += 1;\n }\n directions[j] = \'S\';\n sol += 1;\n\n }\n if (j - 1 >= 0 && directions[j] == \'L\' && directions[j - 1] != \'L\') {\n if (directions[j - 1] == \'R\'){\n directions[j - 1] = \'S\';\n sol += 1;\n }\n directions[j] = \'S\';\n sol += 1;\n } \n if (directions[j] == \'S\') {\n int i = j - 1;\n while (i >= 0 && directions[i] == \'R\') {\n sol++;\n i--;\n } \n }\n }\n \n return sol;\n }\n};\n```\n\n## **Complexity**\n\n#### Time Complexity: **O(size_of_directions * size_of_directions)**, outer ```for``` loop will run (size_of_directions) times, but inner ```while``` loop can run for (size_of_directions - 1) times, for the worst case like ```RRRRRRRRL```.\n\n#### Space Complexity: **O(1)**, \n<br>\n<br>\n\n __Check out all [my]() recent solutions [here]()__\n\n \n __Feel Free to Ask Doubts\nAnd Please Share Some Suggestions\nHAPPY CODING :)__\n\n\n | 108,523 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 377 | 5 | ```\nclass Solution {\n public int countCollisions(String directions) {\n int start = 0, end = directions.length()-1;\n int count = 0;\n while(start<directions.length() && directions.charAt(start)==\'L\')\n start++;\n while(end>=0 && directions.charAt(end)==\'R\')\n end--;\n \n Stack<Character> stack = new Stack<>();\n for(int i = start; i<=end;i++){\n char c = directions.charAt(i);\n if(stack.size()==0)\n stack.push(c);\n else{\n char prev = stack.peek();\n if(c == \'L\'){\n if(prev==\'S\')\n {\n count++;\n }else{// prev ==\'R\'\n stack.pop();\n stack.push(\'S\');\n count+=2;\n }\n }else{\n stack.push(c);\n }\n \n }\n }\n while(stack.size()>0)\n {\n char c = stack.pop();\n if(c==\'R\')\n count++;//R\'s will eventually crash into \'S\'es\n }\n return count;\n }\n} | 108,524 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 1,099 | 13 | We can transform this problem into whether go right or go left cars will stop and count the sum of stops. After transformation, we just need to check the situation of each go left and go right car individually.\n\nStarting from left->right,\n\nIf there is no car at the beginning go right or stop, then go left car after them will never stop.\nExample\nLLLLL -> No one car will stop\nIf there one car stop or go right at the beginning, then go left car after them is bound to stop\nExample\nLR | LLL -> After R, three L will stop there are **three** left car stop\nLS | LLL -> After S, three L will stop\n\n\nStarting from right->left,\nIf there is no car at the beginning go left or stop, then go right car after them will never stop.\nExample\nRRRRR -> No one car will stop\n\nIf there is one car stop or go left at the beginning, then go right car after them is bound to stop\nExample\nRRR | LR -> After L, three RRR will stop \nRRR | SR -> After S, three R will stop\n\nThen we check wether left car will stop by (left->right) and then check wether right car will stop by (right->left). The answer is the sum\n\n\n\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n ans = 0\n # At the beginning, leftest car can go without collide\n # At the beginning, rightest car can go without collide\n \n leftc = rightc = 0\n \n for c in directions:\n # if left side, no car stop or right answer + 0\n # if left side start to have car go right or stop\n # then cars after that are bound to be stopped so answer + 1\n if c == "L":\n ans += leftc\n else:\n leftc = 1\n \n for c in directions[::-1]:\n # if right side, no car stop or left answer + 0\n # if right side start to have car go left or stop\n # then cars after that are bound to be stopped so answer + 1\n if c == "R":\n ans += rightc\n else:\n rightc = 1\n \n return ans\n``` | 108,526 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 474 | 9 | ### **INTUTION**\n\nTo understand the problem first we need to know how any kind of the collision will happen?\n\n**Case1:** \n\nSo if the current direction let suppose be **L**. So how car moving in the left direction will collide?\nAnswer would be - \n\n**Way1:** \n![image]()\nAs we see car from the right (**R**) can collide with car with left (**L**) direction\n\n**Way2:**\n![image]()\nAnother way is that we collide to the stationay car or **previous accident**\n\n**Case2:**\n\nSo if the current condition of car is stationary **"S"** so what are ways we can encounter the collision?\n\n**Way1:**\n![image]()\nAs we can see car coming from the right **"R"** will colide to the stationary (**"S"**) car\n\n**Case3:**\n\nIf current car direction is right **"R"** how collision will happen?\n\nAnswer would be none way as in first two case we encounter how car from the right (**"R"**) will collide to stationary (**"S"**) and car moving to the left (**"L"**) . So we don\'t need to consider any case here for the collision.\n\n**Now we know how all ways to the collision that can happen!!**\n\n#### **Special Case**\n![image]()![image]()\n\nNow if we have multiple car in the right (**"R"**) direction we need to check all the right cars to the stationary (**"S"**) or accident location car\n\n### **Conclusion**\nNumber of ways cars can collide we will use them as if condition for given direction of the current car and we use the special case as while loop when the current car direction is stationary (**"S"**). If accident occur we will denote that location with stationary (**"S"**).\nTo solve the problem we will use the **stack** data structure\n\n### **Code**\n\n```\nclass Solution {\npublic:\n int countCollisions(string directions) {\n stack<char> s;\n int res = 0;\n for(char dir : directions) {\n if(s.empty()) s.push(dir);\n else {\n if(dir==\'L\'){\n if(s.top()==\'R\'){\n res+=2;\n s.pop();\n s.push(\'S\');\n }else if(s.top()==\'S\') res++;\n else s.push(dir);\n }else if(dir==\'R\') s.push(dir);\n else {\n if(s.top()==\'R\'){\n res++;\n s.pop();\n }\n s.push(dir);\n }\n }\n }\n int cnt = 0;\n while(!s.empty()){\n char dir = s.top();\n s.pop();\n if(dir==\'R\') res+=cnt;\n else if(dir==\'S\') cnt = 1;\n }\n return res;\n }\n};\n```\n**If my intutuion and code help you with the understanding of the problem please upvote.** | 108,527 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 1,084 | 10 | My solution :\n```\nclass Solution {\npublic:\n int countCollisions(string D) {//D is Direction string\n int n = D.size(), ans = 0;\n\t\tint i = 0 , j = n-1;\n while(i<=j and D[i] == \'L\') i++; // Cars on left going left => no colision\n\t\twhile(i<=j and D[j] == \'R\') j--; // Cars on right going right => no colision\n for( ; i<=j ; i++) ans += (D[i] != \'S\'); // Whether S collides or not it doesn\'t change answer , all other collide and change score\n return ans;\n }\n \n \n};\n```\nExplanation:\ni. The Ones on left going left and on right going right will not collide .\n hence the first two while loops \nii. All others will collide but a stopped vehicles collision doesn\'t count so we count the rest.\n\nEdit : \nReason for S not contribiting to score is, collision can occur in 3 ways only\ncolliding pair | score increase ...\n R-L | 2\n R-S | 1\n S-L | 1\nSo we can say that if S is involved in collision it has 0 contribution to score while R or L would contribute 1 in collision. Thus whether S takes part in a collision or not is immaterial .\n\n\n\n\n | 108,531 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 1,177 | 12 | The problem was a good simulation problem. Here we have three cases of collision and one hidden case.\n* First case, if the car is moving **R** and the car next to it is moving **L**\n* Second, if the car is moving **R** and the very next car is stationary *i.e.* **S**\n* Third, one is if the first car is stationary **S** and the next car is moving in left direction **L**\n* and the hidden case which i found it later was, what if ***two or more*** cars is moving in right direction and later on some collision take place and the car become stationary\n\t\n# \tExplanation with examples and proof\n\t Example and explanation of the 4th hidden case\n\t Eg: RRRRRRL\n\t Here we can see that R and L will become stationary (After collision of R and L)\n\t -> RRRRRS (after collision or after first traverse)\n\t but, we have just missed the couple of R\'s before S\n\t \n\t To handle this, we will remove the leading R\'s from the stack.\n\t and after removing leading R\'s count remaing R\'s and add to the answer\n\t **Proof**\n\t Let a string S S R S S R L L R S L L R S R S S R L R R R R L L R R L S S R R\n\t after performing first traverse( handling only first 3 cases ) the stack will look like \n\t R R S S S R S R R R S S S S S S S S S S the string is in reverse order\n\t\t\t \n\t After reversing it S S S S S S S S S S R R R S R S S S R R\n\t \n\t Now, we can see that there are couple of collision are left i.e R R R S R S S S R R\n\t last two R R cant collide in any way so remove them from the stack \n\t current stack R R R S R S S S\n\t \n\t Resulting we are only remain with some R\'s that are surely going to collide because even if we\n\t have single \'S\' it is sure that after collide if any car it will become stationary and number of\n\t stationary will increment.\n\t \n\t So, count the remaining R\'s and add to the answer\n\t \n\t Please do dry run on this case, for better understand\n\t S S R S S R L L R S L L R S R S S R L R R R R L L R R L S S R R\n\t \n**read the comment in the code for better understand**\n**CODE**\n\n```\nclass Solution {\npublic:\n int countCollisions(string s) {\n stack<char> st; // creating a stack\n int n = s.size();\n if(n == 1)return 0; // edge case !\n st.push(s[0]); // Push the very first element in stack \n int ans = 0;\n for(int i=1; i<n; i++)\n {\n if(!st.empty() && st.top() == \'R\' && s[i] == \'L\') // First case \n {\n ans += 2;\n st.pop(); // remove the last element from the stack because they have collide \n st.push(\'S\'); // after collide the car become stationary so, push "S"\n }\n else if(!st.empty() && st.top() == \'R\' && s[i] == \'S\') // second case\n {\n ans += 1;\n st.pop(); // same here \n st.push(\'S\');\n }\n else if(!st.empty() && st.top() == \'S\' && s[i] == \'L\') // third case \n ans += 1; \n else\n st.push(s[i]); // if no condition is matched push the current element;\n } \n // handling 4th case \n while(!st.empty() && st.top() == \'R\') // remove the leading R\'s\n st.pop();\n while(!st.empty()) // count the remaing R\'s\n {\n if(st.top() == \'R\')ans++;\n st.pop();\n }\n // please dry run this case of your own for better understand\n // S S R S S R L L R S L L R S R S S R L R R R R L L R R L S S R R\n \n \n return ans;\n }\n};\n``` | 108,532 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 300 | 5 | ```\n return len(directions.lstrip(\'L\').rstrip(\'R\').replace(\'S\',\'\'))\n ```\n\n**Update:**\nExcept for the Left Most cars going in left and Rightmost Cars going towards Right\nEvery Car will collide So Counting these by taking length after removing stay | 108,539 |
Count Collisions on a Road | count-collisions-on-a-road | There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road. | String,Stack | Medium | In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer? | 577 | 5 | This question is similar to the [Asteroid Collision]() question.\n\nWe need a few variables:\n- has_stationary - determines if there stationary objects which will result in collisions\n- number of cars moving towards the right - when they hit a left/stationary car, they will result in collisions\n\n```py\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n has_stationary, right, collisions = False, 0, 0\n for direction in directions:\n if direction == \'R\':\n\t\t\t # Just record number of right-moving cars. We will resolve them when we encounter a left-moving/stationary car.\n right += 1\n elif direction == \'L\' and (has_stationary or right > 0): \n\t\t\t # Left-moving cars which don\'t have any existing right-moving/stationary cars to their left can be ignored. They won\'t hit anything.\n\t\t\t\t# But if there are right-moving/stationary cars, it will result in collisions and we can resolve them.\n\t\t\t\t# We reset right to 0 because they have collided and will become stationary cars.\n collisions += 1 + right\n right = 0\n has_stationary = True\n elif direction == \'S\':\n\t\t\t # Resolve any right-moving cars and reset right to 0 because they are now stationary.\n collisions += right\n right = 0\n has_stationary = True\n return collisions\n```\n\nShorter solution (but less readable IMO)\n\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n has_stationary, right, collisions = False, 0, 0\n for direction in directions:\n if direction == \'R\':\n right += 1\n elif (direction == \'L\' and (has_stationary or right > 0)) or direction == \'S\':\n collisions += (1 if direction == \'L\' else 0) + right\n right = 0\n has_stationary = True\n return collisions\n``` | 108,553 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 6,506 | 89 | **\u2714\uFE0F Solution 1: Top down DP with Backtrack**\n- Step 1: We can DP to find the maximum score Bob can get.\n\t- Let `dp(k, numArrows)` is the maximum score Bob can get if we compute sections from `[k...11]` and `numArrows` arrows.\n\t- We choose the maximum score between 2 following cases:\n\t\t- If Bob **LOSE** then `dp[k][numArrows] = dp[k+1][numArrows]`. It means no score earn, we use no arrows.\n\t\t- If Bob **WIN** only if `numArrows` is greater than `aliceArrows[k]` then `dp[k][numArrows] = dp[k+1][numArrows-aliceArrows[k]-1] + k`. It means we earn `k` score and use `aliceArrows[k] + 1` arrows.\n- Step 2: Backtracking to see in section `k`, Bob win or lose.\n\n<iframe src="" frameBorder="0" width="100%" height="650"></iframe>\n\n**Complexity**\n- Time: `O(2 * 12 * numArrows)`, where `numArrows <= 10^5`.\n- Space: `O(12 * numArrows)`\n- Explain: There are total `12 * numArrows` states, each state need at most `2` case (Lose or Win) to compute.\n\n---\n**\u2714\uFE0F Solution 2: Backtracking**\n- For each section `[0..11]`, we have 2 choices: Bob wins or loses, so there are up to `2^12` options.\n- Therefore we can do normal backtracking to check all possible options, and update the best option if we found.\n```python\nclass Solution:\n def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n self.bestScore = 0\n self.bestBobArrows = None\n \n def backtracking(k, remainArrows, score, bobArrows):\n if k == 12:\n if score > self.bestScore:\n self.bestScore = score\n self.bestBobArrows = bobArrows[::]\n return\n \n backtracking(k+1, remainArrows, score, bobArrows) # Bob loses\n \n # Bob wins\n arrowsNeeded = aliceArrows[k] + 1\n if remainArrows >= arrowsNeeded:\n old = bobArrows[k]\n bobArrows[k] = arrowsNeeded # set new\n backtracking(k+1, remainArrows - arrowsNeeded, score + k, bobArrows)\n bobArrows[k] = old # backtrack\n \n backtracking(0, numArrows, 0, [0] * 12)\n\t\t# In case of having remain arrows then it means in all sections Bob always win \n # then we can distribute the remain to any section, here we simple choose first section.\n self.bestBobArrows[0] += numArrows - sum(self.bestBobArrows)\n return self.bestBobArrows\n```\n**Complexity**\n- Time: `O(2 ^ 12)` in avg. But in the worst case it always update the `bestScore`, so it does copy the whole `bobArrows`, so it takes `O(12 * 2^12)` in time complexity.\n- Space: `O(1)`\n\n---\n**\u2714\uFE0F Solution 3: Bit Masking**\n- Instead of using backtracking, we can generate all possible options by using bit masking.\n- Let `mask` represent the option, Bob wins in section `k` only if `k_th` bit of `mask` is `1`.\n```python\nclass Solution:\n def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n def test(mask, remainArrows):\n score = 0\n bobArrows = [0] * 12\n for k in range(12):\n if (mask >> k) & 1:\n arrowsNeeded = aliceArrows[k] + 1\n if remainArrows < arrowsNeeded: return 0, []\n score += k\n bobArrows[k] = arrowsNeeded\n remainArrows -= arrowsNeeded\n \n\t\t\t# In case of having remain arrows then it means in all sections Bob always win \n\t\t\t# then we can distribute the remain to any section, here we simple choose first section.\n bobArrows[0] += remainArrows\n return score, bobArrows\n \n bestScore = 0\n bestBobArrows = None\n for mask in range(1 << 12):\n score, bobArrows = test(mask, numArrows)\n if score > bestScore:\n bestScore = score\n bestBobArrows = bobArrows\n return bestBobArrows\n```\n**Complexity**\n- Time: `O(12 * 2 ^ 12)`\n- Space: `O(1)` | 108,561 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 4,291 | 60 | ```\nclass Solution\n{\n public:\n vector<int> ans;\n int target = 0;\n vector<int> maximumBobPoints(int numArrows, vector<int> &aliceArrows)\n {\n vector<int> res(12, 0);\n rec(11, numArrows, aliceArrows, 0, res);\n return ans;\n }\n void rec(int n, int numArrows, vector<int> &aliceArrow, int sum, vector<int> res)\n {\n if (n == -1 || numArrows <= 0)\n {\n if (sum > target)\n {\n target = sum;\n if (numArrows > 0)\n {\n res[0] += numArrows;\n }\n ans = res;\n }\n return;\n }\n int req = aliceArrow[n] + 1;\n if (req <= numArrows)\n {\n res[n] = req;\n rec(n - 1, numArrows - req, aliceArrow, sum + n, res);\n res[n] = 0;\n }\n rec(n - 1, numArrows, aliceArrow, sum, res);\n return;\n }\n};\n```\n\nList of similar problems - \n**Decreasing order of frequency (asked in interviews)**\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n | 108,562 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 1,551 | 19 | This problem can be simplified to knapsack, where\n```\nwt[i] = aliceArrows[i]+1 and profit[i]=i\n```\nand so,\n```\ndp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-(aliceArrows[i-1]+1)]+(i-1))\n```\nTo trace back in knapsack, \n```\n(dp[i][j] == dp[i-1][j]) = > coming from pervious, not selected\nelse the item is selected and so ans[i] = aliceArrows[i]+1\n```\n\nComplexity - O(NW) `W => numArraows, N=>aliceArrows.length(constant 12 in this case)`\n```\nclass Solution {\n public int[] maximumBobPoints(int numArrows, int[] aliceArrows) {\n int[][] dp = new int[13][numArrows+1];\n \n for(int i=0; i<=12; i++){\n for(int j=0; j<=numArrows; j++){\n if(i==0 || j==0){\n dp[i][j] = 0;\n } else if(j>=(aliceArrows[i-1]+1)){\n dp[i][j] = Math.max(dp[i-1][j], dp[i-1][j-(aliceArrows[i-1]+1)]+(i-1));\n } else {\n dp[i][j] = dp[i-1][j];\n }\n }\n }\n \n int[] ans = new int[12];\n int result = dp[12][numArrows];\n int total = 0; // to count total arrows used by bob\n for (int i=12, j=numArrows; i > 0 && result > 0; i--) {\n if (result == dp[i-1][j])\n continue;\n else {\n // This item is included.\n ans[i-1] = aliceArrows[i-1]+1;\n result -= (i-1); // subtracting profit\n j -= (aliceArrows[i-1]+1); // subtracting weight\n total += aliceArrows[i-1]+1; \n }\n }\n \n\t\t// as bob has to fire numArrows, remaining can be of 0 value\n if(total<numArrows){\n ans[0] = numArrows-total;\n }\n return ans;\n }\n}\n``` | 108,563 |
Maximum Points in an Archery Competition | maximum-points-in-an-archery-competition | Alice and Bob are opponents in an archery competition. The competition has set the following rules: For example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points. You are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain. Return the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows. If there are multiple ways for Bob to earn the maximum total points, return any one of them. | Array,Bit Manipulation,Recursion,Enumeration | Medium | To obtain points for some certain section x, what is the minimum number of arrows Bob must shoot? Given the small number of sections, can we brute force which sections Bob wants to win? For every set of sections Bob wants to win, check if we have the required amount of arrows. If we do, it is a valid selection. | 2,287 | 44 | Your goal is to get the maximum points.\nSo, at each point, you have 2 choices\n1. Fire more arrow than Alice. 1 arrow more than Alice\'s arrows is enough. OR\n2. Don\'t use any arrow on this point so, we can later utilize it for better points.\n\n**While this problem can have multiple solutions, the maximum points Bob can get is always unique.**\n\ne.g. \nYou have 2 arrows.\nAlice fired 1 arrow on point 1 and 1 arrow on point 11. Total point: 12.\nNow, you can fire 2 arrows on point 11 to gain 11 points and win the game because it will make Alice\'s point to 1 and Bob\'s point to 11. But **remember Your goal is not to reduce Alice\'s point but to maximize your points.**\n\nSo, instead of using your 2 arrows on point 11, you should have used it for point 10 and 9, total points = 19.\n\n**Solution:**\nLet\'s start with the max point = 11, and apply the above two conditions. Move to the next point with the remaining arrow and use the same process untill either you reached to the end or you don\'t have any more arrows left. If you have reached to the end and still have arrows left, they are useless because you couldn\'t gain more points. You can add those arrows to any point. I\'m adding them to 0 point.\n\n\n\t class Solution {\n\t\t\tint bobPoint = 0;\n\t\t\tint[] maxbob = new int[12];\n\t\t\tpublic int[] maximumBobPoints(int numArrows, int[] aliceArrows) {\n\t\t\t\tint[] bob = new int[12];\n\t\t\t\tcalculate(aliceArrows, bob, 11, numArrows, 0); //Start with max point that is 11\n\t\t\t\treturn maxbob;\n\t\t\t}\n\t\t\tpublic void calculate(int[] alice, int[] bob, int index, int remainArr, int point) {\n\t\t\t\tif(index < 0 || remainArr <= 0) {\n\t\t\t\t\tif(remainArr > 0)\n\t\t\t\t\t\tbob[0] += remainArr;\n\t\t\t\t\tif(point > bobPoint) { // Update the max points and result output\n\t\t\t\t\t\tbobPoint = point;\n\t\t\t\t\t\tmaxbob = bob.clone();\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t//part 1: assign 1 more arrow than alice\n\t\t\t\tif(remainArr >= alice[index]+1) {\n\t\t\t\t\tbob[index] = alice[index] + 1;\n\t\t\t\t\tcalculate(alice, bob, index-1, remainArr-(alice[index]+1), point + index);\n\t\t\t\t\tbob[index] = 0;\n\t\t\t\t}\n\t\t\t\t//part 2: assign no arrow and move to next point\n\t\t\t\tcalculate(alice, bob, index-1, remainArr, point);\n\t\t\t\tbob[index] = 0;\n\t\t\t}\n\t\t}\n\n\nSince we have 12 states and at each state we make 2 decisions. So, total Time complexity will be **O(2^12)**. | 108,564 |