title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
---|---|---|---|---|---|---|---|
Solution | divide-nodes-into-the-maximum-number-of-groups | 0 | 1 | \n# Code\n```\nfrom collections import deque \n\nclass Solution:\n def magnificentSets(self, n: int, edges: List[List[int]]) -> int:\n res = 0\n E = build_edges(edges)\n max_distances = {}\n for i in range(1, n+1):\n max_distance = bfs(i, E, n)\n if max_distance:\n max_distances[i] = max_distance\n else:\n return -1\n visited_node = set()\n for i in range(1, n+1):\n if i not in visited_node:\n res += dfs(i, E, visited_node, max_distances)\n\n return res\n\ndef dfs(i, E, visited_node, max_distances):\n visited_node.add(i)\n res = max_distances[i]\n for v in E.get(i, []):\n if v not in visited_node:\n res = max(res, dfs(v, E, visited_node, max_distances))\n return res\n\n\ndef build_edges(edges):\n E = {}\n for e in edges:\n E.setdefault(e[0], []).append(e[1])\n E.setdefault(e[1], []).append(e[0])\n return E\n\ndef bfs(r, E, n):\n my_q = deque()\n my_q.append((r, 0))\n DIST = {r: 0}\n\n while my_q:\n curr_node, cur_dist = my_q.popleft()\n for v in E.setdefault(curr_node, []):\n if v in DIST:\n if (DIST[v] - (cur_dist + 1)) % 2 != 0:\n return None\n else:\n DIST[v] = cur_dist + 1\n my_q.append((v, cur_dist+1))\n return cur_dist + 1\n\n\n``` | 0 | You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`.
You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is a **bidirectional** edge between nodes `ai` and `bi`. **Notice** that the given graph may be disconnected.
Divide the nodes of the graph into `m` groups (**1-indexed**) such that:
* Each node in the graph belongs to exactly one group.
* For every pair of nodes in the graph that are connected by an edge `[ai, bi]`, if `ai` belongs to the group with index `x`, and `bi` belongs to the group with index `y`, then `|y - x| = 1`.
Return _the maximum number of groups (i.e., maximum_ `m`_) into which you can divide the nodes_. Return `-1` _if it is impossible to group the nodes with the given conditions_.
**Example 1:**
**Input:** n = 6, edges = \[\[1,2\],\[1,4\],\[1,5\],\[2,6\],\[2,3\],\[4,6\]\]
**Output:** 4
**Explanation:** As shown in the image we:
- Add node 5 to the first group.
- Add node 1 to the second group.
- Add nodes 2 and 4 to the third group.
- Add nodes 3 and 6 to the fourth group.
We can see that every edge is satisfied.
It can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied.
**Example 2:**
**Input:** n = 3, edges = \[\[1,2\],\[2,3\],\[3,1\]\]
**Output:** -1
**Explanation:** If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied.
It can be shown that no grouping is possible.
**Constraints:**
* `1 <= n <= 500`
* `1 <= edges.length <= 104`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `ai != bi`
* There is at most one edge between any pair of vertices. | null |
Beats 100% C++, Java, Python | maximum-value-of-a-string-in-an-array | 1 | 1 | # Intuition\nIterate through the collection of words and check if they satisfy the given conditions.\n\n# Approach\nEvery word we iterate through in the vector/ array/ list, we check:\nIf that word has a letter in it. If it does:\n We check if its length is greater than the maximum length we have come through so far. If it does, we set the maximum to the length of this word, and move on to the next word.\n\nIf that word has no letter in it:\nWe check if the length of the word is greater than the maximum length we have come so far. If it is:\nWe set the maximum to the length of the current word.\n\nAfter we have been through every word, we return the maximum length.\n\n# Complexity\n- Time complexity:\nO($n^2$)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# C++ Code:\n```\nclass Solution {\npublic:\n int maximumValue(vector<string>& strs) {\n int maximum = 0;\n for(int i = 0; i < strs.size(); i++)\n {\n bool value = false;\n int j = 0;\n string word = strs[i];\n while (j < word.length())\n {\n int letter = word[j];\n if (letter > 96 && letter < 123)\n {\n value = true;\n break;\n }\n j += 1;\n }\n if (value == true)\n {\n if (word.length() > maximum)\n {\n maximum = word.length();\n }\n }\n else\n {\n int number = std::stoi(word);\n if (number > maximum)\n {\n maximum = number;\n }\n }\n }\n return maximum; \n }\n};\n```\n# Java Code:\n```\nclass Solution {\n public int maximumValue(String[] strs) {\n int maximum = 0;\n for(int i = 0; i < strs.length; i++)\n {\n boolean value = false;\n int j = 0;\n String word = strs[i];\n while (j < word.length())\n {\n int letter = word.charAt(j);\n if (letter > 96 && letter < 123)\n {\n value = true;\n break;\n }\n j += 1;\n }\n if (value == true)\n {\n if (word.length() > maximum)\n {\n maximum = word.length();\n }\n }\n else\n {\n int number = Integer.parseInt(word);\n if (number > maximum)\n {\n maximum = number;\n }\n }\n }\n return maximum;\n }\n}\n```\n\n# Python Code:\n```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int:\n maximum = 0\n for word in strs:\n if any(ord(letter) in range(97, 123) for letter in word):\n if len(word) > maximum:\n maximum = len(word)\n else:\n if int(word) > maximum:\n maximum = int(word)\n return maximum\n``` | 1 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
Python3 solution using try and except block unique approach O(N),O(1) | maximum-value-of-a-string-in-an-array | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nwe have a variable m which stores the required ans,\nwe iterate through strts and try if given i can be converted to integer if it is not possible then a valueerror will show up and except block is entered here we will compare m with length of i and previous max stored in m\nif a number is found then else block is enetered and we have m being max m and `int(i)` returning m does it\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n0(1)\n\n# Code\n```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int:\n m=0\n for i in strs:\n try:\n b=int(i)\n except ValueError:\n m=max(len(i),m)\n else:\n m=max(m,int(i))\n return m\n``` | 3 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
[Python3] Beginner friendly solutions with explanation (re) | maximum-value-of-a-string-in-an-array | 0 | 1 | Using **regular expressions** you can check if a string **contains a digit** ```re.search(r\'\\d\', word)```, you can also check if a string **contains letters** ```re.search(r\'[a-z]\', word)```.\nFurther combining the conditions, we look for the value of an alphanumeric according to the task description.\n```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int:\n \n max_val, cur_val = -1, 0\n \n def hasDigits(word):\n return bool(re.search(r\'\\d\', word))\n \n def hasChars(word):\n return bool(re.search(r\'[a-z]\', word))\n \n for word in strs:\n if hasDigits(word) and hasChars(word):\n cur_val = len(word)\n elif hasDigits(word) and not hasChars(word):\n cur_val = int(word)\n else:\n cur_val = len(word)\n \n max_val = max(max_val, cur_val)\n \n return max_val\n```\n\nString validation functions with regular expressions can be replaced by character-by-character validation:\n```\n def hasDigits(word):\n return any(char.isdigit() for char in word)\n\n def hasChars(word):\n return any(char.isalpha() for char in word)\n``` | 2 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
O(n) Easy solution in Python (100% Faster) | maximum-value-of-a-string-in-an-array | 0 | 1 | # Code\n```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int: \n max = 0 \n for i in strs:\n # check if we can convert string into integer\n try:\n if int(i)>max:\n max = int(i)\n # other wise take the length of string\n except:\n if len(i) > max:\n max = len(i) \n return max\n \n \n \n \n``` | 1 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
Python simple and clear solution | maximum-value-of-a-string-in-an-array | 0 | 1 | # Approach\nSimply go through the array,\nThere are two cases: if the current string is a digit so we\'ll calculate the max between this digit and the current max, otherwise take the length of the string and calculate the max.\n\n# Complexity\n- Time complexity:\nO(n) - looping the array\n- Space complexity:\nO(1) - no extra space\n# Code\n```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int:\n maxVal = 0\n\n for s in strs:\n if s.isdigit():\n maxVal = max(int(s), maxVal)\n\n else:\n maxVal = max(len(s), maxVal)\n\n return maxVal\n```\n\nLike it ? Please upvote! | 4 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
Maximum Value of an String in an array | maximum-value-of-a-string-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int:\n max_s=0\n for i in strs:\n if i.isdigit():\n max_s=max(max_s,int(i))\n else:\n max_s=max(len(i),max_s)\n \n return max_s\n``` | 1 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
Easy Python Solution | maximum-value-of-a-string-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n Iterative\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumValue(self, s: List[str]) -> int:\n n=len(s)\n for i in range(n):\n if s[i].isnumeric():\n s[i]=int(s[i])\n else:\n s[i]=len(s[i])\n return max(s)\n``` | 1 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
Python 3 || 5 lines, w/ example || T/M: 90% / 61% | maximum-value-of-a-string-in-an-array | 0 | 1 | ```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int:\n # Example: strs = [\'alic3\', \'bob\', \'3\', \'7\', \'00000\']\n mx = 0\n # s s.isdigit() int(s) len(s) mx \n for s in strs: # \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\n if s.isdigit(): mx = max(mx,int(s)) # \'alic3\' False 5 5\n else : mx = max(mx,len(s)) # \'bob\' False 3 5\n # \'3\' True 3 5\n return mx # \'7\' True 7 7\n # \'00000\' False 0 7 <\u2013\u2013 return\n```\n[https://leetcode.com/problems/maximum-value-of-a-string-in-an-array/submissions/858819022/](http://)\n\n\n\nI could be wrong, but I think that time is *O*(*N*) and space is *O*(1). | 4 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
Recursive and Iterative | Python | maximum-value-of-a-string-in-an-array | 0 | 1 | \n# Iterative Code\n```\nclass Solution(object):\n def maximumValue(self, strs):\n max_ = 0\n for ch in strs:\n if ch.isdigit(): max_ = max(max_, int(ch))\n else: max_ = max(max_, len(ch))\n return max_\n```\n# Recursive Code\n```\nclass Solution(object):\n def maximumValue(self, strs):\n def sol(strs, index, max_):\n if index >= len(strs): return max_\n if strs[index].isdigit():\n return sol(strs, index + 1, max(max_, int(strs[index])))\n return sol(strs, index + 1, max(max_, len(strs[index])))\n return sol(strs, 0, 0)\n```\n**UpVote**, if you like it **:)** | 11 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1:**
**Input:** strs = \[ "alic3 ", "bob ", "3 ", "4 ", "00000 "\]
**Output:** 5
**Explanation:**
- "alic3 " consists of both letters and digits, so its value is its length, i.e. 5.
- "bob " consists only of letters, so its value is also its length, i.e. 3.
- "3 " consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4 " also consists only of digits, so its value is 4.
- "00000 " consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3 ".
**Example 2:**
**Input:** strs = \[ "1 ", "01 ", "001 ", "0001 "\]
**Output:** 1
**Explanation:**
Each string in the array has value 1. Hence, we return 1.
**Constraints:**
* `1 <= strs.length <= 100`
* `1 <= strs[i].length <= 9`
* `strs[i]` consists of only lowercase English letters and digits. | null |
Python3, Sort Positive Neighbors | maximum-star-sum-of-a-graph | 0 | 1 | # Approach\nWe are storing all positive neighbors for each node.\n\n# Complexity\n- Time complexity:\nO(N*log(N))\n\n- Space complexity:\nO(N**2)\n\n# Code\n```\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n if k==0: return max(vals) \n n=len(vals)\n answ=max(vals)\n stars=[[] for _ in range(n)]\n for a,b in edges:\n if 0<vals[b]:\n stars[a].append(vals[b])\n if 0<vals[a]:\n stars[b].append(vals[a])\n answ=max(vals)\n for i in range(n):\n answ = max(answ,sum([vals[i]] + sorted(stars[i])[-k:])) \n return answ \n``` | 1 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi.`
A **star graph** is a subgraph of the given graph having a center node containing `0` or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with `3` and `4` neighbors respectively, centered at the blue node.
The **star sum** is the sum of the values of all the nodes present in the star graph.
Given an integer `k`, return _the **maximum star sum** of a star graph containing **at most**_ `k` _edges._
**Example 1:**
**Input:** vals = \[1,2,3,4,10,-10,-20\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\],\[3,5\],\[3,6\]\], k = 2
**Output:** 16
**Explanation:** The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
**Example 2:**
**Input:** vals = \[-5\], edges = \[\], k = 0
**Output:** -5
**Explanation:** There is only one possible star graph, which is node 0 itself.
Hence, we return -5.
**Constraints:**
* `n == vals.length`
* `1 <= n <= 105`
* `-104 <= vals[i] <= 104`
* `0 <= edges.length <= min(n * (n - 1) / 2``, 105)`
* `edges[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* `0 <= k <= n - 1` | null |
[C++|Java|Python3] sorting | maximum-star-sum-of-a-graph | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/661cb4686dc915189ddbf0bc35fa51f408bf42ef) for solutions of biweekly 93. \n\n**Intuition**\nFor each node, we find the (at most) `k` largest adjacent nodes in `vals`. \n\n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n int maxStarSum(vector<int>& vals, vector<vector<int>>& edges, int k) {\n int n = vals.size(); \n vector<vector<int>> graph(n); \n for (auto& e : edges) {\n graph[e[0]].push_back(e[1]); \n graph[e[1]].push_back(e[0]); \n }\n int ans = INT_MIN; \n for (int u = 0; u < n; ++u) {\n int cand = vals[u]; \n if (graph[u].size() > k) \n nth_element(graph[u].begin(), graph[u].begin()+k, graph[u].end(), [&](auto& lhs, auto& rhs) {\n return vals[lhs] > vals[rhs]; \n }); \n for (int i = 0; i < k && i < graph[u].size(); ++i) \n cand += max(0, vals[graph[u][i]]); \n ans = max(ans, cand); \n }\n return ans; \n }\n};\n```\n**Java**\n```\nclass Solution {\n public int maxStarSum(int[] vals, int[][] edges, int k) {\n int n = vals.length; \n List<Integer>[] graph = new ArrayList[n]; \n for (int u = 0; u < n; ++u) graph[u] = new ArrayList(); \n for (int[] e : edges) {\n graph[e[0]].add(e[1]); \n graph[e[1]].add(e[0]); \n }\n int ans = Integer.MIN_VALUE; \n for (int u = 0; u < n; ++u) {\n int cand = vals[u]; \n if (graph[u].size() > k) Collections.sort(graph[u], (a, b) -> vals[b] - vals[a]);\n for (int v = 0; v < k && v < graph[u].size(); ++v)\n cand += Math.max(0, vals[graph[u].get(v)]); \n ans = Math.max(ans, cand); \n }\n return ans; \n }\n}\n```\n**Python3**\n```\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n n = len(vals)\n graph = [[] for _ in range(n)]\n for u, v in edges: \n graph[u].append(v)\n graph[v].append(u)\n ans = -inf \n for i, u in enumerate(graph): \n u.sort(key=vals.__getitem__, reverse=True)\n cand = vals[i] + sum(max(0, vals[x]) for x in u[:k])\n ans = max(ans, cand)\n return ans \n```\n**Complexity**\nTime `O(ElogE)`\nSpace `O(E)` | 1 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi.`
A **star graph** is a subgraph of the given graph having a center node containing `0` or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with `3` and `4` neighbors respectively, centered at the blue node.
The **star sum** is the sum of the values of all the nodes present in the star graph.
Given an integer `k`, return _the **maximum star sum** of a star graph containing **at most**_ `k` _edges._
**Example 1:**
**Input:** vals = \[1,2,3,4,10,-10,-20\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\],\[3,5\],\[3,6\]\], k = 2
**Output:** 16
**Explanation:** The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
**Example 2:**
**Input:** vals = \[-5\], edges = \[\], k = 0
**Output:** -5
**Explanation:** There is only one possible star graph, which is node 0 itself.
Hence, we return -5.
**Constraints:**
* `n == vals.length`
* `1 <= n <= 105`
* `-104 <= vals[i] <= 104`
* `0 <= edges.length <= min(n * (n - 1) / 2``, 105)`
* `edges[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* `0 <= k <= n - 1` | null |
Beats 100% Python Simple Solution | maximum-star-sum-of-a-graph | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n \n graph = defaultdict(list)\n \n for src,dest in edges:\n graph[src].append(dest)\n graph[dest].append(src)\n \n #traverse each node and find value of edges and pick the highest two \n maxi = float(\'-inf\')\n if not edges:\n return max(vals)\n for node in graph:\n temp = []\n for val in graph[node]:\n heapq.heappush(temp, vals[val])\n while len(temp) > k:\n heapq.heappop(temp)\n \n tot = vals[node]\n for i in range(len(temp)):\n tot = max(tot, tot+ temp[i])\n maxi = max(maxi,tot)\n return maxi \n \n \n \n``` | 2 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi.`
A **star graph** is a subgraph of the given graph having a center node containing `0` or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with `3` and `4` neighbors respectively, centered at the blue node.
The **star sum** is the sum of the values of all the nodes present in the star graph.
Given an integer `k`, return _the **maximum star sum** of a star graph containing **at most**_ `k` _edges._
**Example 1:**
**Input:** vals = \[1,2,3,4,10,-10,-20\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\],\[3,5\],\[3,6\]\], k = 2
**Output:** 16
**Explanation:** The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
**Example 2:**
**Input:** vals = \[-5\], edges = \[\], k = 0
**Output:** -5
**Explanation:** There is only one possible star graph, which is node 0 itself.
Hence, we return -5.
**Constraints:**
* `n == vals.length`
* `1 <= n <= 105`
* `-104 <= vals[i] <= 104`
* `0 <= edges.length <= min(n * (n - 1) / 2``, 105)`
* `edges[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* `0 <= k <= n - 1` | null |
[Python] From Brute Force to Optimal. MinHeap O(V + E log(K)) solution. | maximum-star-sum-of-a-graph | 0 | 1 | # 1) Brute Force (using sort)\nBuild an adjacency list for each vertex in the graph. In a final pass, sort each adjacency list and compute the maximum possible star sum using at most K neighbors for each vertex.\n\n```Python\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], K: int) -> int:\n # T: O(E + V * K + V log(V)), S: O(V)\n V, E = len(vals), len(edges)\n adjList = [[] for _ in range(V)]\n for u, v in edges: # T: O(E)\n adjList[u].append(v)\n adjList[v].append(u)\n \n ans = -math.inf\n for u in range(V): # T: O(V * K)\n adjList[u].sort(key=lambda node: vals[node], reverse=True) # T: O(V log(V)) in total\n starSum = vals[u]\n for i in range(min(K, len(adjList[u]))):\n if vals[adjList[u][i]] <= 0: continue\n starSum += vals[adjList[u][i]]\n ans = max(ans, starSum)\n\n return ans\n```\n\n# 2) MinHeap (optimal)\nInstead of adding all the neighbors of a node to the adjacency list, we can only add the K maximum ones with the help of a MinHeap.\n- Neighbors with a value <= 0 contribute nothing to the star and must be skipped.\n- We simply add nodes until the adjacency list has exactly K elements.\n- If we see a better candidate, that is, a new neighbor with a value greater than the current minimum at the top of the MinHeap we swap them.\n\nWe also use a hashtable to keep track of the star sum for each vertex so that we don\'t have to do additional O(K) work.\n\n```Python\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], K: int) -> int:\n # T: O(E log(K) + V), S: O(V)\n V, E = len(vals), len(edges)\n adjList = [[] for _ in range(V)]\n maxSum = [0] * V\n for u, v in edges: # T: O(E)\n for u, v in [(u, v), (v, u)]: # undirected edges are bidirectional\n if vals[v] <= 0: continue\n\n if len(adjList[u]) < K:\n heapq.heappush(adjList[u], vals[v])\n maxSum[u] += vals[v]\n elif vals[v] > adjList[u][0]:\n maxSum[u] -= adjList[u][0]\n maxSum[u] += vals[v]\n heapq.heapreplace(adjList[u], vals[v])\n\n return max(vals[u] + maxSum[u] for u in range(V)) # T: O(V)\n``` | 2 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi.`
A **star graph** is a subgraph of the given graph having a center node containing `0` or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with `3` and `4` neighbors respectively, centered at the blue node.
The **star sum** is the sum of the values of all the nodes present in the star graph.
Given an integer `k`, return _the **maximum star sum** of a star graph containing **at most**_ `k` _edges._
**Example 1:**
**Input:** vals = \[1,2,3,4,10,-10,-20\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\],\[3,5\],\[3,6\]\], k = 2
**Output:** 16
**Explanation:** The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
**Example 2:**
**Input:** vals = \[-5\], edges = \[\], k = 0
**Output:** -5
**Explanation:** There is only one possible star graph, which is node 0 itself.
Hence, we return -5.
**Constraints:**
* `n == vals.length`
* `1 <= n <= 105`
* `-104 <= vals[i] <= 104`
* `0 <= edges.length <= min(n * (n - 1) / 2``, 105)`
* `edges[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* `0 <= k <= n - 1` | null |
Python - MinHeap | maximum-star-sum-of-a-graph | 0 | 1 | ```\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n \n m = defaultdict(list) # For each node, we will have min heap of size k which stores values # of Top-K nodes it is connected to.\n \n for x,y in edges: \n \n if vals[y]>0: # If neighbor value is negative, our star will have more value without it.\n \n heapq.heappush(m[x], vals[y]) # For each node, push this neighbors value to its heap\n if len(m[x])>k: # If the Min-Heap size is more than K. \n heapq.heappop(m[x]) # Pop the smallest Neighbour value as we can\'t use it anyway. \n \n if vals[x]>0:\n heapq.heappush(m[y], vals[x]) # Repeat the same for other neighbor \n if len(m[y])>k:\n heapq.heappop(m[y])\n \n \n res = -math.inf\n for i in range(len(vals)): # We\'ll try to maximize the star with each node being center\n tot = vals[i] # Our total will be value of that node as it has to be included.\n \n for nei_value in m[i]: # We will check each value in the heap for the node. \n tot+=nei_value # We have already excluded neg values when pushing to Min-Heap\n \n res = max(res, tot) # We\'ll maximize our result\n \n return res \n \n \n \n | 6 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi.`
A **star graph** is a subgraph of the given graph having a center node containing `0` or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with `3` and `4` neighbors respectively, centered at the blue node.
The **star sum** is the sum of the values of all the nodes present in the star graph.
Given an integer `k`, return _the **maximum star sum** of a star graph containing **at most**_ `k` _edges._
**Example 1:**
**Input:** vals = \[1,2,3,4,10,-10,-20\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\],\[3,5\],\[3,6\]\], k = 2
**Output:** 16
**Explanation:** The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
**Example 2:**
**Input:** vals = \[-5\], edges = \[\], k = 0
**Output:** -5
**Explanation:** There is only one possible star graph, which is node 0 itself.
Hence, we return -5.
**Constraints:**
* `n == vals.length`
* `1 <= n <= 105`
* `-104 <= vals[i] <= 104`
* `0 <= edges.length <= min(n * (n - 1) / 2``, 105)`
* `edges[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* `0 <= k <= n - 1` | null |
✅ [PYTHON] ✅ SIMPLE SOLUTION | | maximum-star-sum-of-a-graph | 0 | 1 | # Code\n```\nclass Solution:\n def maxStarSum(self, v: List[int], edges: List[List[int]], k: int) -> int:\n n = len(v)\n g = defaultdict(list)\n for s,d in edges:\n g[s].append([v[d],d])\n g[d].append([v[s],s])\n \n ms = -inf\n \n for z in range(n):\n if g[z]:\n g[z].sort(reverse=True)\n\n cs = v[z]\n c = k\n for j in range(len(g[z])):\n\n if g[z][j][0] > 0:\n cs += g[z][j][0]\n c = c-1\n\n if c == 0: break\n\n else: break\n \n ms = max(ms,cs)\n \n \n if ms == -inf:\n return max(v)\n else:\n return ms\n``` | 2 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi.`
A **star graph** is a subgraph of the given graph having a center node containing `0` or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with `3` and `4` neighbors respectively, centered at the blue node.
The **star sum** is the sum of the values of all the nodes present in the star graph.
Given an integer `k`, return _the **maximum star sum** of a star graph containing **at most**_ `k` _edges._
**Example 1:**
**Input:** vals = \[1,2,3,4,10,-10,-20\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\],\[3,5\],\[3,6\]\], k = 2
**Output:** 16
**Explanation:** The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
**Example 2:**
**Input:** vals = \[-5\], edges = \[\], k = 0
**Output:** -5
**Explanation:** There is only one possible star graph, which is node 0 itself.
Hence, we return -5.
**Constraints:**
* `n == vals.length`
* `1 <= n <= 105`
* `-104 <= vals[i] <= 104`
* `0 <= edges.length <= min(n * (n - 1) / 2``, 105)`
* `edges[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* `0 <= k <= n - 1` | null |
✅ Simple Python Solution - Sort reverse | maximum-star-sum-of-a-graph | 0 | 1 | # Intuition\nGet a list of all the neighbours, then sort them in descending order\n\n\n# Code\n```\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n graph = defaultdict(list)\n for start, end in edges:\n if vals[end] > 0:\n graph[start].append(vals[end])\n if vals[start] > 0:\n graph[end].append(vals[start])\n \n max_sum = -float(\'inf\')\n for i in range(len(vals)):\n total = 0\n graph[i].sort(reverse=True)\n max_sum = max(max_sum, vals[i] + sum(graph[i][:min(len(graph[i]), k)]))\n \n return max_sum\n``` | 2 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi.`
A **star graph** is a subgraph of the given graph having a center node containing `0` or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with `3` and `4` neighbors respectively, centered at the blue node.
The **star sum** is the sum of the values of all the nodes present in the star graph.
Given an integer `k`, return _the **maximum star sum** of a star graph containing **at most**_ `k` _edges._
**Example 1:**
**Input:** vals = \[1,2,3,4,10,-10,-20\], edges = \[\[0,1\],\[1,2\],\[1,3\],\[3,4\],\[3,5\],\[3,6\]\], k = 2
**Output:** 16
**Explanation:** The above diagram represents the input graph.
The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.
It can be shown it is not possible to get a star graph with a sum greater than 16.
**Example 2:**
**Input:** vals = \[-5\], edges = \[\], k = 0
**Output:** -5
**Explanation:** There is only one possible star graph, which is node 0 itself.
Hence, we return -5.
**Constraints:**
* `n == vals.length`
* `1 <= n <= 105`
* `-104 <= vals[i] <= 104`
* `0 <= edges.length <= min(n * (n - 1) / 2``, 105)`
* `edges[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* `0 <= k <= n - 1` | null |
beats 90% in python | frog-jump-ii | 0 | 1 | \n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n if len(stones)==2:\n return stones[1]-stones[0]\n jump=stones[0]\n for i in range(len(stones)-2):\n jump=max(jump,stones[i+2]-stones[i])\n return jump\n\n``` | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
[C++|Java|Python3] every other stone | frog-jump-ii | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/661cb4686dc915189ddbf0bc35fa51f408bf42ef) for solutions of biweekly 93. \n\n**Intuition**\nThe maximum distance of every other stone is the answer with an edge of `stones[1]` when there are only two stones. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n int maxJump(vector<int>& stones) {\n int ans = stones[1]; \n for (int i = 2; i < stones.size(); ++i) \n ans = max(ans, stones[i] - stones[i-2]); \n return ans; \n }\n};\n```\n**Java**\n```\nclass Solution {\n public int maxJump(int[] stones) {\n int ans = stones[1]; \n for (int i = 2; i < stones.length; ++i) \n ans = Math.max(ans, stones[i] - stones[i-2]); \n return ans; \n }\n}\n```\n**Python3**\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n ans = stones[1]\n for i in range(2, len(stones)): \n ans = max(ans, stones[i] - stones[i-2])\n return ans \n```\n**Complexity**\nTime `O(N)`\nSpace `O(1)` | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
Python code | frog-jump-ii | 0 | 1 | # Code\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n l = len(stones)\n if l==3: return stones[2]\n answer = stones[1]\n for i in range(2, l, 2):\n if answer<stones[i]-stones[i-2]:answer=stones[i]-stones[i-2]\n for i in range(3, l, 2):\n if answer<stones[i]-stones[i-2]:answer=stones[i]-stones[i-2]\n return answer\n``` | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
Greedy solution with example and proof | frog-jump-ii | 0 | 1 | \n# Keypoint\n1. Use all rocks: the more rock in path, the better. This is because more rocks make each jump shorter.\n2. Jump alternatively is optimal. so we check all (stones[i+2] - stones[i]) and find maximum. \n\n# Proof\nWe use example `[1,2,3,4]` to prove alterntive-jump is optimal when n == 4. \n\nCase1: If frog jumps alternatively, the forward path\'s jump are [1,3], back path\'s jump are [4,2].\nCase2: If frog doesn\'t jump alternatively, forward path\'s jump are [1,2],[2,3],[3,4], back path\'s jump are [4,1]\n\nWe can see Case2\'s back jump [4,1] covers Case1\'s [1,3] and [4,2]. So Case2 must be larger than Case1.\n\nSo we proved it is always optimal to jump alternatively when n == 4.\nThen we can prove the statement always hold through induction.\n\n\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n n = len(stones)\n ans = stones[1] - stones[0]\n for i in range((n-2)):\n ans = max(ans, stones[i+2] - stones[i])\n return ans\n``` | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
Decently explained Python3 code O(n) w/ Image | frog-jump-ii | 1 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nNo matter how you try, the best approach is always going to be skipping the next stone and going to next stone after that (if this step is possible). \n\nAfter drawing all possibilities it can be seen that the biggest steps are always going to be skipping one stone in between of two stones, i.e of length = 2.\nThere may be other steps as well of length = 1 but there will always be another step of length 2 skipping over the stone involved in jump of length 1, hence making the length 1 jump not worth considering.\n\nHere are examples of possible paths for even and odd number of stones.\nSorry for unclear photos.\n\n\n\n\n\nAs, the images can hopefully show, the optimal path will result in jumps of length 2, and so in the code I have just used two pointers i, j to iterate through the graph and check what is the maximum cost in jumping this way. \n\nHope you understood what I am trying to convey here. Anyways, have a great day and Happy Coding.\n\n\n\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n# Code\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n if len(stones) == 2:\n return (stones[-1] - stones[0])\n maxjump = 0\n i, j = 0, 2\n while j < len(stones):\n maxjump = max(maxjump, (stones[j] - stones[i]))\n i+= 1; j+= 1\n return maxjump\n \n``` | 20 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
Python O(n) solution | frog-jump-ii | 0 | 1 | # Approach\n- Finding difference between even position and odd position(from last)\n- Appending them into a list\n- Returning max value of list\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n l=stones\n x=[]\n n=len(l)\n if(n==2):\n return abs(l[0]-l[1])\n else:\n if(n%2==0):\n count=0\n for i in range(n) :\n if(i%2==0 and i<n-2):\n x.append(abs(l[i]-l[i+2]))\n\n\n for i in range(n) :\n if(i%2==1 and i<=n-2):\n x.append(abs(l[i]-l[i+2]))\n\n\n else:\n count=1\n for i in range(n) :\n if(i%2==0 and i<=n-2):\n x.append(abs(l[i]-l[i+2]))\n\n\n for i in range(n) :\n if(i%2==1 and i<n-2):\n x.append(abs(l[i]-l[i+2]))\n return max(x)\n``` | 2 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
Python 3 || 5 lines || T/M: 97% / 68% | frog-jump-ii | 0 | 1 | You can figure it out. I\'m pretty sure.\n\n"The secret of being a bore is to tell everything." \u2014 Voltaire\n\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n\n n = len(stones)\n\n ans = stones[1]\n\n for i in range(n-2):\n ans = max(ans,stones[i+2]-stones[i])\n\n return ans\n```\n[https://leetcode.com/problems/frog-jump-ii/submissions/858955992/]()\n\nI could be wrong, but I think that time is *O*(*N*) and space is *O*(1). | 4 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
Python - Greedy O(n) - Video Solution | frog-jump-ii | 0 | 1 | The complete intuition is explained in this [video](https://www.youtube.com/watch?v=7eqGntQ7-Fs).\n\n# Intuition\nThe intution is, we have 3 stones `0, 10, 30`, \nthen we have to cover atleast `0 -> 30` / `30 -> 0 ` once.\n\nSo this max gap will be our answer.\n\nSo we try to find max distance between alternate stones.\n\n\nIf this is helpful, please upvote, like the video and subscribe to the channel.\n\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n \n n = len(stones)\n \n if n==2: # if 2 stones, we have to jump end-to-end. \n return stones[-1] # So, last stone will be our answer.\n \n diff_alternate_stone = 0 # Otherwise, the answer will be the max dist between alternate stones \n \n for i in range(n-2): # We find all the alternate distances and maximize it.\n diff_alternate_stone = max(diff_alternate_stone, stones[i+2]-stones[i])\n \n return diff_alternate_stone # The max alternate distance is our answer. | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
Python3 | Binary Search Solution | frog-jump-ii | 0 | 1 | \n# Code\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n l = 0;r = stones[-1]\n while l<r:\n m = (l+r)//2\n if valid(m,stones):\n r = m\n else:\n l = m+1\n return r\n\n\n\ndef valid(x,stones):\n i = 0;j = 0;n = len(stones)\n visitedList = [False for x in range(n)]\n visitedList[0] = True\n while j<n:\n if stones[j]-stones[i]>x:\n if j==i+1:\n return False\n else:\n i = j-1\n visitedList[i] = True\n j+=1\n visitedList[j-1] = True\n last = stones[j-1]\n maximum = 0\n flag = True\n for i in range(n-1,-1,-1):\n if visitedList[i]==False:\n maximum = max(last-stones[i],maximum)\n flag = False\n if maximum>x:\n return False\n last = stones[i]\n\n return last-stones[i]<=x\n\n\n``` | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
One-liner - Python greedy solution O(n) | frog-jump-ii | 0 | 1 | # Intuition\nIf we use a stone, we cannot use it on our way back so we will have to jump above it, so we just need to look at the maximum gaps betwteen stones separated by one stone.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n return stones[1] if len(stones)==2 else max(stones[i+2]-stones[i] for i in range (len(stones)-2))\n \n```\nPlease upvote if you liked!\n\nCheers,\nBerthouille | 2 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
* More formally, if the frog is at `stones[i]` and is jumping to `stones[j]`, the length of the jump is `|stones[i] - stones[j]|`.
The **cost** of a path is the **maximum length of a jump** among all jumps in the path.
Return _the **minimum** cost of a path for the frog_.
**Example 1:**
**Input:** stones = \[0,2,5,6,7\]
**Output:** 5
**Explanation:** The above figure represents one of the optimal paths the frog can take.
The cost of this path is 5, which is the maximum length of a jump.
Since it is not possible to achieve a cost of less than 5, we return it.
**Example 2:**
**Input:** stones = \[0,3,9\]
**Output:** 9
**Explanation:**
The frog can jump directly to the last stone and come back to the first stone.
In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.
It can be shown that this is the minimum achievable cost.
**Constraints:**
* `2 <= stones.length <= 105`
* `0 <= stones[i] <= 109`
* `stones[0] == 0`
* `stones` is sorted in a strictly increasing order. | null |
Greedy || Python 3 | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n O(n)\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n n=len(nums1)\n z=Counter(nums1)\n z1=Counter(nums2)\n for i in z:\n if(n-z1[i]<z[i]):\n return -1\n if(z[i]>=n//2+1 and z1[i]>=n//2+1):\n return -1\n for i in z1:\n if(n-z[i]<z1[i]):\n return -1\n if(z[i]>=n//2+1 and z1[i]>=n//2+1):\n return -1\n z=Counter([])\n ans=0\n flag=0\n d=defaultdict(list)\n vis=[0 for i in range(n)]\n for i in range(n):\n if(nums1[i]==nums2[i]):\n z[nums2[i]]+=1\n ans+=i\n flag=1\n d[nums2[i]].append(i)\n t=0\n l=z.most_common(len(z))\n a=0\n for i in range(1,len(l)):\n a+=l[i][1]\n for j in d[l[i][0]]:\n vis[j]=1\n z[l[i][0]]=0\n if(l and a>=l[0][1]):\n return ans\n x=0\n if(l):\n x=l[0][1]-a\n z[l[0][0]]=x\n print(z,ans)\n for j in z:\n if(z[j]):\n for i in range(n):\n if(vis[i]==0 and nums1[i]!=j and nums2[i]!=j and x):\n if(flag):\n ans+=i\n x-=1\n return ans\n``` | 1 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
[Python 3] As Simple as Possible | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Intuition\n* `ans` $\\ge$ sum of bad indices\n* it\'s "efficient" to make pairs of bad indices and swap them with each other whenever possible\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n def is_possible():\n cnt1 = Counter(nums1)\n cnt2 = Counter(nums2)\n for v in cnt1:\n if v in cnt2 and cnt1[v] > n - cnt2[v]:\n return False\n return True\n \n if not is_possible():\n return -1\n val2bad_inds_cnt = defaultdict(int)\n bad_inds = set()\n for i in range(n):\n if nums1[i] == nums2[i]:\n val2bad_inds_cnt[nums1[i]] += 1\n bad_inds.add(i)\n \n bad_inds_cnt = len(bad_inds)\n if bad_inds_cnt == 0:\n return 0\n # swap bad indices with each other first (they form pairs)\n ans = sum(bad_inds) # ans is at least sum of bad indices\n dominant_bad_value = max(val2bad_inds_cnt.keys(), key=lambda v: val2bad_inds_cnt[v])\n pairs = min(bad_inds_cnt // 2, bad_inds_cnt - val2bad_inds_cnt[dominant_bad_value])\n if pairs != bad_inds_cnt - val2bad_inds_cnt[dominant_bad_value]:\n # if bad_inds_cnt is even, bad_inds split into pairs\n # if bad_inds_cnt is odd, we can swap with index 0 twice\n return ans\n swaps_left = bad_inds_cnt - pairs * 2\n can_swap = lambda i: i not in bad_inds and nums1[i] != dominant_bad_value != nums2[i]\n i = 0\n while swaps_left > 0:\n while i < n and not can_swap(i):\n i += 1\n ans += i\n swaps_left -= 1\n i += 1\n return ans\n\n``` | 1 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
[C++||Java||Python] O(1) space complexity with Moore vote algorithm | minimum-total-cost-to-make-arrays-unequal | 1 | 1 | > **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n\n> **Vote welcome if this solution helped.**\n---\n# Intuition\n\n1. Define "internally" as indexes $i$ satisfy $$a[i] = b[i]$$. It seems that swap internally should be done as much as possible, but there is no guarantee that internal swapping is always possible.\n2. Every time an internal pair $i,j$ which $$i \\ne j$$ is found, an internal swap can be completed. So if we can swap internally for whole array, the $$ S = {\\sum_{a[i]=b[i]}^{} i} $$ will be the result.\n3. In which condition we must swap externally? Obviously only if the number of internal swaps is insufficient.\n4. Why not sufficient? An obvious case is that there is a value occurs more than half of the inner. In mathematics, that is, **the majority is more than a half**.\n5. Another case is the internal number is odd, so it must remain one index. Fortunately, **we have the freedom to choose any index as the remainder, the other indexes will always matchable**. \n6. How to choose? Since the chosen index will swap externally, we strongly want it can swap with `0`. Is it guaranteed to find such an index? The answer is "Yes". \n7. Because the majority is less than half, there are **at least 3 different value inside**. So we can always find a $$i$$ which satisfy $$a[i] \\ne a[0]$$ and $$ a[i] \\ne b[0]$$. Choose this $$i$$ as the remainder, we can still maintain the result as $$S$$.\n8. Finally, if we are forced to do external swaps, we should choose the smallest possible indexes.\n\n# Approach\nThrough the above analysis, the problem becomes:\n1. How to find the majority?\n2. If the majority is greater than half, which external indexes can be included for swapping?\n\nSolve these questions sequentially:\n\n1. It\'s a classical problem: [LeetCode 169](https://leetcode.com/problems/majority-element/), can be solved in $O(1)$ space complexity with [Boyer\u2013Moore majority vote algorithm](https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm).\n2. First, the newly included $$j$$ must be external. Secondly, the newly included $$a[j]$$ and $$b[j]$$ can\'t be majority, otherwise there will be an equal situation after the swap. Finally enumerate from small to large until the number is sufficient.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n long long minimumTotalCost(vector<int>& a, vector<int>& b) {\n // repeat is the number of a[i] == b[i]\n int n = a.size(), repeat = 0; \n // s is the sum of i that satisfies a[i] == b[i]\n long long s = 0; \n // val is the only candidate for majority \n int val = -1, x = 0; \n for (int i = 0; i < n; ++i) {\n if (a[i] == b[i]) {\n if (x == 0) val = a[i];\n x += 2 * (val == a[i]) - 1;\n repeat++;\n s += i;\n }\n }\n // cnt is the count of val\n int cnt = 0; \n for (int i = 0; i < n; ++i) {\n cnt += a[i] == b[i] && a[i] == val;\n }\n // less than half, so s is the result\n if (cnt * 2 < repeat) return s;\n // the number which need to be swapped externally\n int m = 2 * cnt - repeat;\n for (int i = 0; i < n && m > 0; ++i) {\n // index satisfying this condition can be used for swap\n if (a[i] != val && b[i] != val && a[i] != b[i]) {\n s += i;\n m--;\n }\n }\n if (m > 0) return -1;\n return s;\n }\n};\n```\n``` Java []\nclass Solution {\n public long minimumTotalCost(int[] a, int[] b) {\n // repeat is the number of a[i] == b[i]\n int n = a.length;\n int repeat = 0; \n // s is the sum of i that satisfies a[i] == b[i]\n long s = 0; \n // val is the only candidate for majority \n int val = -1;\n int x = 0; \n for (int i = 0; i < n; ++i) {\n if (a[i] == b[i]) {\n if (x == 0) val = a[i];\n if (val == a[i]) x--;\n else x++;\n repeat++;\n s += i;\n }\n }\n // cnt is the count of val\n int cnt = 0; \n for (int i = 0; i < n; ++i) {\n if (a[i] == b[i] && a[i] == val)\n cnt++;\n }\n // less than half, so s is the result\n if (cnt * 2 < repeat) return s;\n // the number which need to be swapped externally\n int m = 2 * cnt - repeat;\n for (int i = 0; i < n && m > 0; ++i) {\n // index satisfying this condition can be used for swap\n if (a[i] != val && b[i] != val && a[i] != b[i]) {\n s += i;\n m--;\n }\n }\n if (m > 0) return -1;\n return s;\n }\n}\n```\n``` Python []\nclass Solution:\n def minimumTotalCost(self, a: List[int], b: List[int]) -> int:\n n = len(a)\n # repeat is the number of a[i] == b[i]\n repeat = 0 \n # s is the sum of i that satisfies a[i] == b[i]\n s = 0\n # val is the only candidate for majority \n val, x = -1, 0\n for i in range(n):\n if a[i] == b[i]:\n if x == 0: val = a[i]\n x += 2 * (val == a[i]) - 1\n repeat += 1\n s += i\n # cnt is the count of val\n cnt = sum(a[i] == b[i] and a[i] == val for i in range(n))\n # less than half, so s is the result\n if cnt * 2 < repeat: \n return s\n # the number which need to be swapped externally\n m = 2 * cnt - repeat\n for i in range(n):\n # index satisfying this condition can be used for swap\n if a[i] != val and b[i] != val and a[i] != b[i]:\n s += i\n m -= 1\n if m <= 0:\n return s\n return -1\n```\n | 3 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
[Python] Detailed explanation, readable code | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | This is not my invention. I borrowed this solution from [@bucketpotato](https://leetcode.com/bucketpotato/), analyzed it and made a super detailed version of their code.\n\n```python\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n inputLength = len(nums1)\n maxNumber = inputLength # By the task definition\n\n # Counts how many times each number appears in both arrays\n numFrequences = Counter(nums1 + nums2)\n \n # If a number appears more times than an array length,\n # it\'s impossible to put it into 2 arrays without overlaps:\n # [1,1,1,2,3]\n # [2,3,1,1,1] // too tight for six 1s\n if max(numFrequences.values()) > inputLength:\n return -1\n \n # Will accumulate the answer here\n cost = 0\n\n # Counting how many time each number appears in a match\n # between nums1 and nums2. Also counting total matches.\n # A map can be used instead, arrays are faster in runtime\n matchesByNum = [0] * (maxNumber + 1)\n matchesCount = 0\n for i in range(0, inputLength):\n if nums1[i] == nums2[i]:\n matchesByNum[nums1[i]] += 1\n matchesCount += 1\n\n # This item must be swapped with something, no matter what with for now.\n # We add the cost of the half-swap (raising the i\'th num up and waiting for moving).\n # We will add the cost the counterpart half-swaps later.\n # (cost of a swap is cost of the half-swaps of its elements)\n cost += i\n \n # Looking for the number that appeared in the matches the most often\n mostMatchingNum = 1\n for num in range(2, maxNumber + 1):\n if matchesByNum[num] > matchesByNum[mostMatchingNum]:\n mostMatchingNum = num\n mostMatchingNumFrequency = matchesByNum[mostMatchingNum]\n \n # If the frequency of the most frequent matching number\n # is not greater than the frequencies all the other numbers combined,\n # We can swap the matching numbers with each other.\n # [1,1,1,1,1,2,2,2,3,3] ->\n # [3,3,2,2,2,1,1,1,1,1] // no match any more\n # Since they match with each outher, their half-swaps are combined\n # into full swaps (like atoms of oxygen), so no extra cost is used.\n if mostMatchingNumFrequency * 2 <= matchesCount:\n return cost\n \n # Otherwise we have excess items that haven\'t got a counterpart.\n # [1,1,1,2,2] ->\n # [2,2,1,1,1] // a match, no matter how to reorder\n # We need to find places for them in the nums2 array within\n # the numbers that didn\'t match initialy, because all the matching\n # numbers either have been swapped (see above) or are to be swapped\n # by the loop below.\n # Looking for the leftmost available place to minimize the cost.\n excessCount = mostMatchingNumFrequency * 2 - matchesCount\n for i in range(0, inputLength):\n # Avoiding matching numbers (see the comment above)\n if nums1[i] == nums2[i]:\n continue\n # Swapping would mean putting mostMatchingNum to a spot\n # where it would be a match too\n if nums1[i] == mostMatchingNum:\n continue\n # mostMatchingNum wouldn\'t make a match here, but the nums2[i]\n # item that we put to the mostMatchingNum old spot (as a result of the swap)\n # would be a match there\n if nums2[i] == mostMatchingNum:\n continue\n\n # Found a good spot, performing a swap.\n # The cost of a half-swap of mostMatchingNum have beed added above,\n # so adding only a half-swap cost of nums2[i]\n cost += i\n\n # When all the pairs for the matching elements are found, the problem is solved\n excessCount -= 1\n if excessCount == 0:\n break\n \n return cost\n``` | 4 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
Algorithm specific to this problem | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nClearly, the minimum cost includes the sum of all i for which nums1[i]=nums2[i].\n\nIn certain circumstances, this is the actual answer. However, there are two cases when this may not be true:\n- when the number of such indices is odd\n- when one value is so predominant among nums when nums1[i]=nums2[i] that we need to go outside this set to swap, because there aren\'t enough swap possibilities inside the set.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- When the number of indices with equality is even and one value is not predominant, the sum of i for which nums1[i]=nums2[i] is the answer; we can then swap values in pairs.\nWhen the number is odd, but one value is not predominant, it turns out that the answer is the same, because we can use the index 0 for an extra swap, whether it is in the set or not.\n\n- If one value dominates, meaning that it is the value of nums for more than half the indices with equality, then we have to go outside the set and use\n$$max\\_ct-(total\\_ct-max\\_ct)=2max\\_ct-total\\_ct$$\nplaces for extra swaps, where total\\_ct is the total number of indices with equality and max_ct is the count of the dominant value. There can be at most one dominant value, call it val.\nWe then go outside the set and look for 2max\\_ct-total\\_ct swap candidates. We look at all indices i, in increasing order, such that:\n\\* nums1[i]!= nums2[i] (meaning i is outside the set),\n\\* nums1[i]!=val\n\\* nums2[i]!=val.\nWhen finding a good index, we add it to the sum, until we find 2*max_ct-total_ct good indices or run out of candidates.\nIf we run out of candidates, a swap is not possible. Otherwise, the updated sum is the minimal cost.\n\n# Complexity\n- Time complexity: $O(n)$.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(n)$ on top of initial data.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n l=len(nums1)\n sm=0\n dct=defaultdict(int)\n ct=0\n for i in range(l):\n if nums1[i]==nums2[i]:\n ct+=1\n dct[nums1[i]]+=1\n sm+=i\n if not ct:\n return 0\n max_it=max(dct.items(), key=lambda x:x[1])\n val=max_it[0]\n dif=(max_it[1]<<1)-ct\n i=0\n while dif>0:\n while i<l and (nums1[i]==nums2[i] or nums1[i]==val or nums2[i]==val):\n i+=1\n if i==l:\n break\n sm+=i\n i+=1\n dif-=1\n if dif<=0:\n return sm\n return -1\n \n``` | 7 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
[Python] Find smallest set to permute | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | ### Approach\nBecause swapping to and from index $0$ is free, if $S\'$ is the set of indices that are in at least one swap in the answer, then the optimal cost is `sum(S\')`.\n\nLet $S \\subseteq S\'$ be the set of $i$ with $A[i] = B[i]$. We have to move these, so the answer is at least `sum(S)`. Note that if all $A[i]$ were different, then `sum(S)` is the final answer.\n\nNow accounting for the values of $A[i]$, consider any $\\text{major} = \\text{mode}(\\{\\,A[i] \\mid i \\in S\\,\\})$. A necessary condition is that $\\text{major}$ doesn\'t occur more than $\\frac{|S\'|}{2}$ times. Actually, it\'s also a sufficient one (*).\n\nSo say $\\text{major}$ has frequency larger than $\\frac{|S|}{2}$ (there can be at most one), then we need to add $i$\'s to $S\'$ so that $A[i]$ and $B[i]$ are not equal to $\\text{major}$, until we get the frequency at or below $\\frac{\\|S\'\\|}{2}$.\n\n### Code\n```\nclass Solution:\n def minimumTotalCost(self, A, B):\n N = len(A)\n indexes = {i for i in range(N) if A[i] == B[i]}\n if not indexes:\n return 0\n\n count = Counter(A[i] for i in indexes)\n major = max(count, key=count.__getitem__)\n to_add = max(count[major] * 2 - len(indexes), 0)\n for i in range(N):\n if to_add and A[i] != major != B[i] and i not in indexes:\n to_add -= 1\n indexes.add(i)\n\n return -1 if to_add else sum(indexes)\n```\n\n(* proof : let the largest frequencies be $(f_1, f_2, \\cdots)$, then decrementing $f_1$ and $f_2$ would have $f_2 \\leq \\frac{n}{2} \\Leftrightarrow f_2 - 1 \\leq \\frac{n-2}{2}$ and $f_3 \\leq \\frac{n}{3} \\leq \\frac{n-2}{2}$ showing our induction would hold for $n \\geq 6$, and small $n$ is an exercise.) | 8 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
Frequency Transform | Commented and Explained | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrequency transform of the problem space makes this much easier, since we can consider the costs based around the most frequent value in the arrays and the frequency of matches in the arrays. \n\nOnce we know the frequency of matches, and we know the most frequent of values that undergo the matches, we can determine the suitability of the problem space. \n\nThis is because by knowing the how frequent the most frequent value that matches another value in both arrays at an index is, we can know if we can swap for the total number of matches. \n\nIf the most frequent value of matching has a frequency that is less than twice the amount of the total number of matching occurrences, we can just return the sum of the indices of the matching occurrences. \n\nOtherwise, we will need to now consider the possibility that the most frequent number may occur too many times in the list to make swapping possible. \n\nIf the most frequent value occurs too many times in the list, we would not be able to perform the swaps. To find out, our current remaining needed swaps would need to be twice the maximal frequency less the total number of matching numbers by indices in the current arrays. \n\nThen, while we have a remainder that is positive, we can loop again, and at any point the numbers do not match, and they are both not the most frequent, we have a remainder operation we can use. \n- This would mean we can add the indexing to the result, and lower the remainder by 1.\n- If we ever reach a stopping point, we can return the result. \n- Otherwise, if we have any remainder left over, it actually means we ran out of spots to place the most frequent value before it runs into a problem. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSet a resulting cost to 0, a base frequency of matching num value by indices as a dictionary, a total number of matching values to 0, and a most frequent and max frequency to 0 each \n\nLoop for index in range of len of the nums\n- get num1 in nums1 at index and num2 in nums2 at index (or you could enumerate) \n- if they match \n - increment result by index \n - increment total by 1 \n - increment base frequency at num1 by 1 \n - if this is new max frequency and most frequent num, set as needed \n\nDetermine if 2 * the max frequency is lte the total number of matches \n- if so, return result \n- otherwise, set remainder to 2 * the max frequency less the total \n- while you have a remainder \n - loop over index in range of len of the nums again \n - on points of mismatch where they are not the most frequent value in either case \n - increment result by index and decrement remainder by 1 \n - if remainder is now 0, return result \n - if remainder is now 0, return result, otherwise break \n- return -1 \n\n# Complexity\n- Time complexity : O(N)\n - O(N) twice over to loop over nums \n\n- Space complexity : O(n) \n - we only store the unique nums in base frequency, not all the nums \n\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n # set result to 0. Result tracks the cost of the operations of the movements. \n result = 0 \n # track frequency of numeric matches of nums in nums1 that are in nums2 at same index \n base_frequency = collections.defaultdict(int)\n # track total matches \n total = 0 \n # track most frequent num \n most_frequent = 0 \n # track max frequency of most frequent num \n max_frequency = 0 \n # enumerate nums zipped \n for index, (num1, num2) in enumerate(zip(nums1, nums2)) : \n # on match \n if num1 == num2 : \n # increment result by index, total by 1 and base frequency by 1 at num1 \n result += index \n total += 1 # total is the total number of matches \n base_frequency[num1] += 1 \n # if the base frequency of this value is now greater than max frequency \n if base_frequency[num1] > max_frequency : \n # set the max frequency and most frequent accordingly \n max_frequency = base_frequency[num1]\n most_frequent = num1 \n # if twice the max frequency is less than the total matches, return result of index summation of matches \n # this is the cost as we can always get away with cost by half via interesting swaps \n if 2 * max_frequency <= total : \n return result \n # otherwise, while you have a remainder, loop over nums again \n # remainder in this case is the twice of the max frequency less the number of total matches \n remainder = 2 * max_frequency - total \n # and at the points where these do not match and neither are the most frequent value, increment the result by indexing and reduce remainder\n for index, (num1, num2) in enumerate(zip(nums1, nums2)) : \n if num1 != num2 and num1 != most_frequent and num2 != most_frequent : \n result += index \n remainder -= 1 \n if remainder == 0 : \n # if you ever run out of remainder, you have your result, as this is now the cost through swapping \n return result \n # otherwise too much remaining values of the most frequent number existed and it is not possible \n return -1 \n``` | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
Python 3 | Solution | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n \n matched = defaultdict(int)\n unmatched = defaultdict(list)\n\n res = 0\n for i, (x,y) in enumerate(zip(nums1, nums2)):\n if x == y:\n res += i\n matched[x] += 1\n matched[y] += 1\n\n else:\n unmatched[i].append(x)\n unmatched[i].append(y)\n\n if matched and max(matched.values()) > sum(list(matched.values()))//2:\n max_key = max(matched, key=lambda k: matched[k])\n num = matched[max_key] - sum(list(matched.values()))//2\n\n for i in unmatched.keys():\n \n if max_key not in unmatched[i]:\n \n res += i\n num -= 1\n if num <= 0:\n return res\n\n return -1\n\n return res\n``` | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
Python Solution | minimum-total-cost-to-make-arrays-unequal | 1 | 1 | \tclass Solution:\n\t\tdef minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\td = Counter(nums2)\n\t\t\tn = len(nums1)\n\t\t\th = n//2\n\t\t\tfor i,j in d.items():\n\t\t\t\tif j>h:\n\t\t\t\t\treturn -1\n\t\t\td = defaultdict(int)\n\t\t\tans = 0\n\t\t\tcnt =0\n\t\t\tfor i in range(n):\n\t\t\t\tif nums1[i]==nums2[i]:\n\t\t\t\t\tans+=i\n\t\t\t\t\tcnt+=1\n\t\t\t\t\td[nums1[i]]+=1\n\t\t\tval =0\n\t\t\tmx =0\n\t\t\tfor i,j in d.items():\n\t\t\t\tif j>mx:\n\t\t\t\t\tmx =j\n\t\t\t\t\tval = i\n\t\t\tif mx+mx>cnt:\n\t\t\t\tfor i in range(n):\n\t\t\t\t\tif nums1[i]!=nums2[i] and nums1[i]!=val and nums2[i]!=val and mx+mx>cnt:\n\t\t\t\t\t\tans+=i\n\t\t\t\t\t\tcnt+=1\n\t\t\treturn ans\n\t\t#We are doing mx+mx because lets suppose we have 3 - 3 and 4-5 so total 8 elements which are same so we can take three of 3 and three of 4 to make swap and then we are left with 3 more elements of 4 which we have to swap with any values which is not 4. | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
[Python3] | Greedy | Steps Explained. | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | 1. Store all indexes in arr which have equal element in nums1 and nums2.\n2. If max Freq element in arr is less than or equal to len(arr) then element can interchange among themselves -> return sum(arr)\n3. if max Freq element in arr is greater than len(arr) , then we need to add some indexes , so that freq will become equal to len(arr) / 2 . Greedily we will start adding from left of array because when we swap then we will add minimum value to answer.\n4. condition to add index will be . lets say we are adding index i\n 1. i shouldn\'t be already included in step 1.\n\t2. nums1[i] should not be equal to max Freq element as it will increase it\'s freq, we want to decrease it to len(arr) / 2. \n\t3. nums2[i] should not be equal to max Freq element , because we wont be able to perform swapping of max Freq element to index i\n\t\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n arr = []\n n = len(nums1)\n hmap = defaultdict(int)\n mx = -1\n for i in range(n):\n if nums1[i] == nums2[i]: #creating arr of indexes which has equal element in both array.\n arr.append(i)\n hmap[nums1[i]] += 1\n if hmap[nums1[i]] > mx: #finding max freq element and its freq.\n mxOcc = nums1[i]\n mx = hmap[nums1[i]]\n sz = len(arr)\n if mx <= sz//2: #condition 2\n return sum(arr)\n else:\n req = (2*mx) - len(arr) #count of extra index to add from nums1 array.\n i = 0\n while i < n and req > 0:\n if nums1[i] != nums2[i] and nums1[i] != mxOcc and nums2[i] != mxOcc: #condition explained in step 4\n req -= 1\n arr.append(i)\n i += 1\n return sum(arr) if req == 0 else -1\n \n```\nUpvote if you liked the solution. | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
Python | Clean Code | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | \n# Code\n```\nfrom collections import Counter\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n res = 0\n d = Counter()\n t = 0\n most = 0\n v = None\n for i,(x,y) in enumerate(zip(nums1, nums2)):\n if x == y:\n res += i\n t += 1\n d[x] += 1 \n if d[x] > most:\n most = d[x]\n v = x\n if 2*most <= t:\n return res\n k = 2*most - t\n for i, (x,y) in enumerate(zip(nums1, nums2)):\n if x != y and x != v and y != v:\n res += i\n k -= 1\n if k == 0: return res\n return -1\n\n \n \n \n``` | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
Python Linear time Linear Space Solution | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n sz, ctr = len(nums1), Counter(nums1 + nums2)\n if max(ctr.values()) > sz:\n return -1\n sames, differents, res = [], [], 0\n sames.append(nums1[0])\n sames.append(nums2[0])\n for idx, (num1, num2) in enumerate(zip(nums1[1:], nums2[1:]), start = 1):\n if num1 == num2:\n res += idx\n sames.append(num1)\n sames.append(num2)\n else:\n differents.append(idx)\n threshold, ctr = len(sames) // 2, Counter(sames)\n maxCount = max(ctr.values())\n if maxCount >= threshold:\n res += sum(differents[: maxCount - threshold])\n return res\n``` | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
Python Solution with Explanation - 2 codes where Leetcode testcases running fine but mine Fails | minimum-total-cost-to-make-arrays-unequal | 1 | 1 | \tclass Solution:\n\t\tdef minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\t#this is the which accepted but can fail for some cases if leetcode did something good otherwise always will be ac.\n\t\t\t"""\n\t\t\td = Counter(nums2)\n\t\t\tn = len(nums1)\n\t\t\th = n//2\n\t\t\tfor i,j in d.items():\n\t\t\t\tif j>h:\n\t\t\t\t\treturn -1\n\t\t\tind =[]\n\t\t\tans = 0\n\t\t\tfor i in range(n):\n\t\t\t\tif nums1[i]==nums2[i]:\n\t\t\t\t\tans+=i\n\t\t\t\t\tind.append(nums1[i])\n\t\t\td = Counter(ind)\n\t\t\th = len(ind)//2\n\t\t\tval =0\n\t\t\tmx =0\n\t\t\tflag =True\n\t\t\tfor i,j in d.items():\n\t\t\t\tif j>mx:\n\t\t\t\t\tmx =j\n\t\t\t\t\tval = i\n\t\t\t\tif j>h:\n\t\t\t\t\tflag = False\n\t\t\tif flag:\n\t\t\t\treturn ans\n\t\t\tcnt = mx - h\n\t\t\tfor i in range(n):\n\t\t\t\tif nums1[i]!=nums2[i] and cnt>0 and nums1[i]!=val:\n\t\t\t\t\tans+=i\n\t\t\t\t\tcnt-=1\n\t\t\treturn ans\n\t\t\t"""\n\t\t\t#Now the final code\n\t\t\td = Counter(nums2)\n\t\t\tn = len(nums1)\n\t\t\th = n//2\n\t\t\tfor i,j in d.items():\n\t\t\t\tif j>h:\n\t\t\t\t\treturn -1\n\t\t\td = defaultdict(int)\n\t\t\tans = 0\n\t\t\tcnt =0\n\t\t\tfor i in range(n):\n\t\t\t\tif nums1[i]==nums2[i]:\n\t\t\t\t\tans+=i\n\t\t\t\t\tcnt+=1\n\t\t\t\t\td[nums1[i]]+=1\n\t\t\tval =0\n\t\t\tmx =0\n\t\t\tfor i,j in d.items():\n\t\t\t\tif j>mx:\n\t\t\t\t\tmx =j\n\t\t\t\t\tval = i\n\t\t\tif mx+mx>cnt:\n\t\t\t\tfor i in range(n):\n\t\t\t\t\tif nums1[i]!=nums2[i] and nums1[i]!=val and nums2[i]!=val and mx+mx>cnt:\n\t\t\t\t\t\tans+=i\n\t\t\t\t\t\tcnt+=1\n\t\t\treturn ans | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
Python (Simple Hashmap + Maths) | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1, nums2):\n n = len(nums1)\n\n result, dict1, total, most_freq, val = 0, collections.defaultdict(int), 0, 0, 0\n\n for i,(x,y) in enumerate(zip(nums1,nums2)):\n if x == y:\n result += i\n total += 1\n dict1[x] += 1\n\n if dict1[x] > val:\n val = dict1[x]\n most_freq = x\n\n if 2*val <= total:\n return result\n\n k = 2*val - total \n\n for i,(x,y) in enumerate(zip(nums1,nums2)):\n if x != y and x != most_freq and y != most_freq:\n result += i\n k -= 1\n\n if k == 0: return result \n\n return -1\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n \n``` | 1 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations.
Return _the **minimum total cost** such that_ `nums1` and `nums2` _satisfy the above condition_. In case it is not possible, return `-1`.
**Example 1:**
**Input:** nums1 = \[1,2,3,4,5\], nums2 = \[1,2,3,4,5\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = \[4,2,3,1,5\]
- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = \[4,3,2,1,5\].
- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =\[5,3,2,1,4\].
We can see that for each index i, nums1\[i\] != nums2\[i\]. The cost required here is 10.
Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.
**Example 2:**
**Input:** nums1 = \[2,2,2,1,3\], nums2 = \[1,2,2,3,3\]
**Output:** 10
**Explanation:**
One of the ways we can perform the operations is:
- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = \[2,2,1,2,3\].
- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = \[2,3,1,2,2\].
The total cost needed here is 10, which is the minimum possible.
**Example 3:**
**Input:** nums1 = \[1,2,2\], nums2 = \[1,2,2\]
**Output:** -1
**Explanation:**
It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.
Hence, we return -1.
**Constraints:**
* `n == nums1.length == nums2.length`
* `1 <= n <= 105`
* `1 <= nums1[i], nums2[i] <= n` | null |
✅✅Simple Python Solution 100% Faster || Easy Solution ✅✅ | delete-greatest-value-in-each-row | 0 | 1 | # Code\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n for i in range(0, len(grid)):\n grid[i].sort()\n n = len(grid[0])\n res = 0\n for j in range(0, n):\n ans = 0\n for i in range(0, len(grid)):\n ans = max(ans, grid[i].pop())\n res += ans\n \n return res\n``` | 1 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that the number of columns decreases by one after each operation.
Return _the answer after performing the operations described above_.
**Example 1:**
**Input:** grid = \[\[1,2,4\],\[3,3,1\]\]
**Output:** 8
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.
- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.
- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.
The final answer = 4 + 3 + 1 = 8.
**Example 2:**
**Input:** grid = \[\[10\]\]
**Output:** 10
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 10 from the first row. We add 10 to the answer.
The final answer = 10.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `1 <= grid[i][j] <= 100` | null |
Sort Rows | delete-greatest-value-in-each-row | 0 | 1 | We sort all rows first, then go column by column and pick the largest value.\n\n**Python 3**\n```python\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n return sum(max(c) for c in zip(*[sorted(r) for r in grid]))\n```\n\n**C++**\n```cpp\nint deleteGreatestValue(vector<vector<int>>& g) {\n int res = 0, si = g.size(), sj = g[0].size();\n for (auto &r : g)\n sort(begin(r), end(r));\n for (int j = 0; j < sj; ++j) {\n int max_row = 0;\n for (int i = 0; i < si; ++i) \n max_row = max(max_row, g[i][j]);\n res += max_row;\n }\n return res;\n}\n``` | 39 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that the number of columns decreases by one after each operation.
Return _the answer after performing the operations described above_.
**Example 1:**
**Input:** grid = \[\[1,2,4\],\[3,3,1\]\]
**Output:** 8
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.
- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.
- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.
The final answer = 4 + 3 + 1 = 8.
**Example 2:**
**Input:** grid = \[\[10\]\]
**Output:** 10
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 10 from the first row. We add 10 to the answer.
The final answer = 10.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `1 <= grid[i][j] <= 100` | null |
Python || Beats 79 % || Easy | delete-greatest-value-in-each-row | 0 | 1 | # Code\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n \n res = 0\n \n n = len(grid[0])\n \n for i in range(n):\n maxi = 0\n for j in grid:\n new = max(j)\n maxi = max(maxi,new)\n j.remove(new)\n res+=maxi\n \n \n \n \n \n \n \n return res \n``` | 1 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that the number of columns decreases by one after each operation.
Return _the answer after performing the operations described above_.
**Example 1:**
**Input:** grid = \[\[1,2,4\],\[3,3,1\]\]
**Output:** 8
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.
- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.
- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.
The final answer = 4 + 3 + 1 = 8.
**Example 2:**
**Input:** grid = \[\[10\]\]
**Output:** 10
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 10 from the first row. We add 10 to the answer.
The final answer = 10.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `1 <= grid[i][j] <= 100` | null |
Python | Easy Solution✅ | delete-greatest-value-in-each-row | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n i = 0\n output = 0\n current_max = 0\n while True:\n if len(grid[i]) == 0:\n break\n grid[i] = sorted(grid[i])\n current_max = max(current_max,grid[i][-1])\n grid[i].pop(-1)\n i+=1\n if i == len(grid):\n output += current_max\n current_max = 0\n i = 0\n return output\n \n\n``` | 6 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that the number of columns decreases by one after each operation.
Return _the answer after performing the operations described above_.
**Example 1:**
**Input:** grid = \[\[1,2,4\],\[3,3,1\]\]
**Output:** 8
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.
- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.
- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.
The final answer = 4 + 3 + 1 = 8.
**Example 2:**
**Input:** grid = \[\[10\]\]
**Output:** 10
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 10 from the first row. We add 10 to the answer.
The final answer = 10.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `1 <= grid[i][j] <= 100` | null |
[C++|Java|Python3] sorting | delete-greatest-value-in-each-row | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/8f409c5e220a4a1a1d7fdfbfcc1dcd24eeead232) for solutions of weekly 323. \n\n**Intuition**\nThe problem can be solved by sorting each row and sum the largest of each column. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n int deleteGreatestValue(vector<vector<int>>& grid) {\n for (auto& row : grid) \n sort(row.begin(), row.end()); \n int ans = 0; \n for (int j = 0, n = grid[0].size(); j < n; ++j) {\n int val = 0; \n for (int i = 0, m = grid.size(); i < m; ++i) \n val = max(val, grid[i][j]); \n ans += val; \n }\n return ans; \n }\n};\n```\n**Java**\n```\nclass Solution {\n public int deleteGreatestValue(int[][] grid) {\n int m = grid.length, n = grid[0].length; \n for (int[] row : grid) Arrays.sort(row); \n int ans = 0; \n for (int j = 0; j < n; ++j) {\n int cand = 0; \n for (int i = 0; i < m; ++i) \n cand = Math.max(cand, grid[i][j]); \n ans += cand; \n }\n return ans; \n }\n}\n```\n**Python3**\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n for row in grid: row.sort()\n return sum(max(col) for col in zip(*grid))\n```\n**Complexity**\nTime `O(MNlogN)`\nSpace `O(1)` | 2 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that the number of columns decreases by one after each operation.
Return _the answer after performing the operations described above_.
**Example 1:**
**Input:** grid = \[\[1,2,4\],\[3,3,1\]\]
**Output:** 8
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.
- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.
- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.
The final answer = 4 + 3 + 1 = 8.
**Example 2:**
**Input:** grid = \[\[10\]\]
**Output:** 10
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 10 from the first row. We add 10 to the answer.
The final answer = 10.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `1 <= grid[i][j] <= 100` | null |
Recursive Solution for Python | delete-greatest-value-in-each-row | 0 | 1 | # Code\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n return self.calculate_answer(grid, 0)\n\n def calculate_answer(self, grid: List[List[int]], answer: int) -> int:\n if grid[0] == []:\n return answer\n\n current_max = 0\n for i in grid:\n maximum_int = max(i)\n if maximum_int >= current_max:\n current_max = maximum_int\n\n i.remove(maximum_int)\n\n answer += current_max\n return self.calculate_answer(grid, answer)\n``` | 1 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that the number of columns decreases by one after each operation.
Return _the answer after performing the operations described above_.
**Example 1:**
**Input:** grid = \[\[1,2,4\],\[3,3,1\]\]
**Output:** 8
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.
- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.
- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.
The final answer = 4 + 3 + 1 = 8.
**Example 2:**
**Input:** grid = \[\[10\]\]
**Output:** 10
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 10 from the first row. We add 10 to the answer.
The final answer = 10.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `1 <= grid[i][j] <= 100` | null |
Python 3 || 3 lines, w/ explanation and example || T/M: 102 ms / 14MB | delete-greatest-value-in-each-row | 0 | 1 | ```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n\n for i in range(len(grid)): grid[i].sort() # <-- sort each row\n\n grid = list(zip(*grid)) # <-- transpose grid; rows become\n # cols and cols become rows\n\n return sum(max(row) for row in grid) # <-- sum the maxs from each row\n #_________________________________\n # Example: grid = [[4,1,2]\n # [3,3,1]]\n\n # Sort rows: grid = [[1,2,4]\n # [1,3,3]]\n #\n # Transpose: grid = [[1,1] <-- max: 1\n # [2,3] <-- max: 3\n # [4,3]] <-- max: 4\n # \u2013\u2013\u2013\n # Sum: return \u2013\u2013> 8 \n \n```\n\n\n\nI could be wrong, but I think that time is *O*(*N*log*N*) and space is *O*(*N*), worst case. | 11 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that the number of columns decreases by one after each operation.
Return _the answer after performing the operations described above_.
**Example 1:**
**Input:** grid = \[\[1,2,4\],\[3,3,1\]\]
**Output:** 8
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.
- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.
- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.
The final answer = 4 + 3 + 1 = 8.
**Example 2:**
**Input:** grid = \[\[10\]\]
**Output:** 10
**Explanation:** The diagram above shows the removed values in each step.
- In the first operation, we remove 10 from the first row. We add 10 to the answer.
The final answer = 10.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 50`
* `1 <= grid[i][j] <= 100` | null |
[Python / JS] dont use expensive sqrt() function | longest-square-streak-in-an-array | 0 | 1 | # Python\n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n seen = {}\n ans = -1\n\n for n in nums:\n if n*n in seen:\n seen[n] = seen[n*n]+1\n ans = max(ans, seen[n])\n else:\n seen[n] = 1\n\n return ans\n```\n# JavaScript\n```\nconst longestSquareStreak = nums => {\n nums.sort((a,b) => b-a)\n const seen = new Map()\n let ans = -1\n\n for (let n of nums) {\n if (seen.has(n*n)) {\n seen.set(n, seen.get(n*n) + 1)\n ans = Math.max(ans, seen.get(n))\n } else {\n seen.set(n, 1)\n }\n }\n\n return ans\n}\n``` | 1 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square streak** in_ `nums`_, or return_ `-1` _if there is no **square streak**._
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[4,3,6,16,8,2\]
**Output:** 3
**Explanation:** Choose the subsequence \[4,16,2\]. After sorting it, it becomes \[2,4,16\].
- 4 = 2 \* 2.
- 16 = 4 \* 4.
Therefore, \[4,16,2\] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.
**Example 2:**
**Input:** nums = \[2,3,5,6,7\]
**Output:** -1
**Explanation:** There is no square streak in nums so return -1.
**Constraints:**
* `2 <= nums.length <= 105`
* `2 <= nums[i] <= 105` | null |
Python | Optimal O(n) | easy to understand | longest-square-streak-in-an-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n nums.sort()\n d = {}\n ans = 0\n for i, n in enumerate(nums):\n sqrt = n ** 0.5\n if sqrt in d and sqrt.is_integer():\n d[n] = d[sqrt] + 1\n ans = max(ans, d[n])\n else:\n d[n] = 1\n \n return ans if ans > 0 else -1\n``` | 1 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square streak** in_ `nums`_, or return_ `-1` _if there is no **square streak**._
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[4,3,6,16,8,2\]
**Output:** 3
**Explanation:** Choose the subsequence \[4,16,2\]. After sorting it, it becomes \[2,4,16\].
- 4 = 2 \* 2.
- 16 = 4 \* 4.
Therefore, \[4,16,2\] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.
**Example 2:**
**Input:** nums = \[2,3,5,6,7\]
**Output:** -1
**Explanation:** There is no square streak in nums so return -1.
**Constraints:**
* `2 <= nums.length <= 105`
* `2 <= nums[i] <= 105` | null |
Python 3 || 11 lines, mathematics, w/ brief comments || T/M: 97%/68% | longest-square-streak-in-an-array | 0 | 1 | Pretty much the same solution as others, except the set of potential squares has been pruned back to just those numbers `n` such that `n%4 == 0` or `n%4 == 1`. \n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n\n s = set(nums)\n nums, ans = sorted(s), 0\n s = {n for n in s if n%4 < 2}\n\n for n in nums:\n square, tally = n*n, 1\n\n while square in s:\n s.remove(square)\n tally+= 1\n square*= square\n\n ans = max(ans, tally)\n \n return ans if ans > 1 else -1\n``` | 4 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square streak** in_ `nums`_, or return_ `-1` _if there is no **square streak**._
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[4,3,6,16,8,2\]
**Output:** 3
**Explanation:** Choose the subsequence \[4,16,2\]. After sorting it, it becomes \[2,4,16\].
- 4 = 2 \* 2.
- 16 = 4 \* 4.
Therefore, \[4,16,2\] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.
**Example 2:**
**Input:** nums = \[2,3,5,6,7\]
**Output:** -1
**Explanation:** There is no square streak in nums so return -1.
**Constraints:**
* `2 <= nums.length <= 105`
* `2 <= nums[i] <= 105` | null |
6 lines with hashmap | longest-square-streak-in-an-array | 0 | 1 | reversing nums is better because no need to take care of float\n\n# Code\n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n ans, buf = -1, {}\n for n in reversed(sorted(nums)):\n buf[n] = buf.get(n*n, 0) + 1\n if buf[n] > 1:\n ans = max(ans, buf[n])\n return ans\n``` | 3 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square streak** in_ `nums`_, or return_ `-1` _if there is no **square streak**._
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[4,3,6,16,8,2\]
**Output:** 3
**Explanation:** Choose the subsequence \[4,16,2\]. After sorting it, it becomes \[2,4,16\].
- 4 = 2 \* 2.
- 16 = 4 \* 4.
Therefore, \[4,16,2\] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.
**Example 2:**
**Input:** nums = \[2,3,5,6,7\]
**Output:** -1
**Explanation:** There is no square streak in nums so return -1.
**Constraints:**
* `2 <= nums.length <= 105`
* `2 <= nums[i] <= 105` | null |
[Python 3] Simple | Using set | longest-square-streak-in-an-array | 0 | 1 | ```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n uniq = set(nums)\n res = 0\n \n for i in nums:\n temp = i\n t = 0\n while temp * temp in uniq:\n temp *= temp\n t += 1\n \n res = max(res, t)\n \n return res + 1 if res else -1\n``` | 2 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square streak** in_ `nums`_, or return_ `-1` _if there is no **square streak**._
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[4,3,6,16,8,2\]
**Output:** 3
**Explanation:** Choose the subsequence \[4,16,2\]. After sorting it, it becomes \[2,4,16\].
- 4 = 2 \* 2.
- 16 = 4 \* 4.
Therefore, \[4,16,2\] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.
**Example 2:**
**Input:** nums = \[2,3,5,6,7\]
**Output:** -1
**Explanation:** There is no square streak in nums so return -1.
**Constraints:**
* `2 <= nums.length <= 105`
* `2 <= nums[i] <= 105` | null |
✔ Python3 Solution | DP | Clean & Concise | longest-square-streak-in-an-array | 0 | 1 | # Complexity\n- Time complexity: $$O(nlogn)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def longestSquareStreak(self, A):\n A.sort()\n n = len(A)\n dp = [1] * n\n r = n - 1\n for i in range(n - 1, -1, -1):\n while A[i] * A[i] < A[r]: r -= 1\n if A[i] * A[i] == A[r]: dp[i] = dp[r] + 1\n ans = max(dp)\n return ans if ans > 1 else -1\n``` | 1 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square streak** in_ `nums`_, or return_ `-1` _if there is no **square streak**._
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[4,3,6,16,8,2\]
**Output:** 3
**Explanation:** Choose the subsequence \[4,16,2\]. After sorting it, it becomes \[2,4,16\].
- 4 = 2 \* 2.
- 16 = 4 \* 4.
Therefore, \[4,16,2\] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.
**Example 2:**
**Input:** nums = \[2,3,5,6,7\]
**Output:** -1
**Explanation:** There is no square streak in nums so return -1.
**Constraints:**
* `2 <= nums.length <= 105`
* `2 <= nums[i] <= 105` | null |
[C++|Java|Python3] dp | longest-square-streak-in-an-array | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/8f409c5e220a4a1a1d7fdfbfcc1dcd24eeead232) for solutions of weekly 323. \n\n**Intuition**\nIt is quite strange that sorting is allowed in this problem. However, since sorting is allowed, all that matters is whether a squared number exists. One solution via DP is to check if a number x is a squared number if so its streak is 1+dp[r] where r is the square root of x. \n\n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n int longestSquareStreak(vector<int>& nums) {\n vector<int> dp(100\'001); \n sort(nums.begin(), nums.end()); \n for (auto& x : nums) {\n dp[x] = max(1, dp[x]); \n int v = sqrt(x); \n if (v * v == x) dp[x] = 1 + dp[v]; \n }\n int ans = *max_element(dp.begin(), dp.end()); \n return ans > 1 ? ans : -1; \n }\n};\n```\n**Java**\n```\nclass Solution {\n public int longestSquareStreak(int[] nums) {\n int[] dp = new int[100_001]; \n Arrays.sort(nums); \n int ans = 0; \n for (int x : nums) {\n dp[x] = Math.max(1, dp[x]); \n int v = (int) Math.sqrt(x); \n if (v*v == x) dp[x] = 1 + dp[v]; \n ans = Math.max(ans, dp[x]); \n }\n return ans > 1 ? ans : -1; \n }\n}\n```\n**Python3**\n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n dp = defaultdict(int)\n for x in sorted(nums): \n dp[x] = max(dp[x], 1)\n v = isqrt(x)\n if v**2 == x: dp[x] = 1 + dp[v]\n ans = max(dp.values())\n return ans if ans > 1 else -1\n```\n**Complexity**\nTime `O(NlogN)`\nSpace `O(N)` | 2 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square streak** in_ `nums`_, or return_ `-1` _if there is no **square streak**._
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[4,3,6,16,8,2\]
**Output:** 3
**Explanation:** Choose the subsequence \[4,16,2\]. After sorting it, it becomes \[2,4,16\].
- 4 = 2 \* 2.
- 16 = 4 \* 4.
Therefore, \[4,16,2\] is a square streak.
It can be shown that every subsequence of length 4 is not a square streak.
**Example 2:**
**Input:** nums = \[2,3,5,6,7\]
**Output:** -1
**Explanation:** There is no square streak in nums so return -1.
**Constraints:**
* `2 <= nums.length <= 105`
* `2 <= nums[i] <= 105` | null |
[C++|Java|Python3] brute-force | design-memory-allocator | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/8f409c5e220a4a1a1d7fdfbfcc1dcd24eeead232) for solutions of weekly 323. \n\n**Intuition**\nThis is a brute-force solution where in `allocate` I traverse the whole `memory` array to find the consecutive free block of given size and in `free` I also traverse the whole `memory` to free memory with given id. \n\n**Implementation**\n**C++**\n```\nclass Allocator {\n vector<int> memory; \npublic:\n Allocator(int n) {\n memory.resize(n); \n }\n \n int allocate(int size, int mID) {\n int cnt = 0; \n for (int i = 0; i < memory.size(); ++i) \n if (memory[i] == 0) {\n if (++cnt == size) {\n for (int ii = i; ii >= i-size+1; --ii)\n memory[ii] = mID; \n return i-size+1; \n }\n } else cnt = 0; \n return -1; \n }\n \n int free(int mID) {\n int ans = 0; \n for (int i = 0; i < memory.size(); ++i) \n if (memory[i] == mID) {\n ++ans; \n memory[i] = 0; \n }\n return ans; \n }\n};\n```\n**Java**\n```\nclass Allocator {\n private int[] memory; \n \n public Allocator(int n) {\n memory = new int[n]; \n }\n \n public int allocate(int size, int mID) {\n int cnt = 0; \n for (int i = 0; i < memory.length; ++i) {\n if (memory[i] == 0) {\n if (++cnt == size) {\n for (int ii = i; ii >= i-size+1; --ii) \n memory[ii] = mID; \n return i-size+1; \n }\n } else cnt = 0; \n }\n return -1; \n }\n \n public int free(int mID) {\n int ans = 0; \n for (int i = 0; i < memory.length; ++i) \n if (memory[i] == mID) {\n ++ans; \n memory[i] = 0; \n }\n return ans; \n }\n}\n```\n**Python3**\n```\nclass Allocator:\n\n def __init__(self, n: int):\n self.memory = [0] * n \n\n def allocate(self, size: int, mID: int) -> int:\n cnt = 0 \n for i, x in enumerate(self.memory): \n if x == 0: \n cnt += 1\n if cnt == size: break \n else: cnt = 0 \n else: return -1 \n self.memory[i-size+1 : i+1] = [mID]*size\n return i-size+1\n\n def free(self, mID: int) -> int:\n ans = 0 \n for i, x in enumerate(self.memory): \n if x == mID: \n ans += 1\n self.memory[i] = 0 \n return ans \n```\n**Complexity**\nTime `O(N)` for `allocate` and `free`\nSpace `O(N)` | 1 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
Beats 100% solutions | design-memory-allocator | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport heapq\nclass Allocator:\n\n def __init__(self, n: int):\n self.ht={}\n self.freeMemeory=[[0, n]]\n\n def allocate(self, size: int, mID: int) -> int:\n if self.freeMemeory:\n self.refreshMemeory()\n val = self.giveFreeMemeory(size)\n if not val:\n return -1\n # one mID can have multiple occurrences, so need to keep track of all occurrences.\n if mID in self.ht:\n self.ht[mID].append(val)\n else:\n self.ht[mID]=[val]\n return val[0]\n \n\n def free(self, mID: int) -> int:\n if self.freeMemeory:\n self.refreshMemeory()\n if mID not in self.ht or not self.ht[mID]:\n return 0\n size=0\n # suppose we have multiple occurrences of 1 then in that case we need to remove all the occurrences and return the total size.\n for ids in self.ht[mID]:\n size+=ids[1]-ids[0]\n heapq.heappush(self.freeMemeory,ids)\n # need to reset the HashTable, once every occurrences are removed\n self.ht[mID]=[]\n return size\n\n # giveFreeMemeory is to return FIRST FREE MEMORY which comes in the range of size.\n def giveFreeMemeory(self, size):\n temp=[]\n send=[]\n while self.freeMemeory:\n start, end = heapq.heappop(self.freeMemeory)\n if (end-start)>=size:\n if (end-start)>size:\n heapq.heappush(self.freeMemeory,[start+size, end])\n send=[start, start+size]\n break\n else:\n temp.append([start, end])\n if temp:\n for i in range(len(temp)):\n heapq.heappush(self.freeMemeory,temp[i])\n if not send:\n return 0\n return send\n\n # refreshMemeory function helps us to refactor the memory, suppose we have [[40,50], [12,40]] so this is nothing but [[12,50]], our refreshMemory function will help us do the same.\n def refreshMemeory(self):\n start, end = heapq.heappop(self.freeMemeory)\n temp=[[start, end]]\n while self.freeMemeory:\n newStart, newEnd = heapq.heappop(self.freeMemeory)\n if end==newStart:\n temp.pop()\n end=newEnd\n else:\n start=newStart\n end=newEnd\n temp.append([start, end])\n if temp:\n for i in range(len(temp)):\n heapq.heappush(self.freeMemeory,temp[i])\n \n\n\n# Your Allocator object will be instantiated and called as such:\n# obj = Allocator(n)\n# param_1 = obj.allocate(size,mID)\n# param_2 = obj.free(mID)\n``` | 1 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
✅✅Simplest Python Solution Without HashMap✅✅ | design-memory-allocator | 0 | 1 | # Code\n```\nclass Allocator:\n\n def __init__(self, n: int):\n self.mem = [0]*n\n \n def allocate(self, size: int, mID: int) -> int:\n def checksize(size):\n flag = False \n pos = -1\n count = 0\n for i in range(0, len(self.mem)):\n if self.mem[i] == 0:\n flag = True\n count += 1\n if count == size:\n return pos + 1\n else:\n if count >= size:\n return pos + 1\n pos = i\n count = 0\n return -1\n \n \n idx = checksize(size)\n if idx == -1:\n return -1\n else:\n for i in range(idx, idx+size):\n self.mem[i] = mID\n return idx\n \n def free(self, mID: int) -> int:\n count = 0\n for i in range(0, len(self.mem)):\n if self.mem[i] == mID:\n self.mem[i] = 0\n count += 1\n return count\n\n\n# Your Allocator object will be instantiated and called as such:\n# obj = Allocator(n)\n# param_1 = obj.allocate(size,mID)\n# param_2 = obj.free(mID)\n``` | 1 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
Python simple solution with video explanation | design-memory-allocator | 0 | 1 | # Approach\ncreate an array of length n initialize with -1 \n- for allocate look for a free block of length size, once found set all values in it to mID and returns the start index \n- for free find all those set to mID and set to -1 \n\nVideo explanation: https://www.youtube.com/watch?v=k9l1PvIRNRw\n# Code\n```\nclass Allocator:\n\n def __init__(self, n: int):\n self.blocks = [-1] * n\n self.n = n\n \n def allocate(self, size: int, mID: int) -> int:\n available = 0\n for i in range(self.n):\n if self.blocks[i] == -1:\n available += 1\n else:\n available = 0\n if available == size: \n for j in range(i - available + 1, i + 1):\n self.blocks[j] = mID\n return i - available + 1\n return -1 \n \n def free(self, mID: int) -> int:\n count = 0\n for i in range(self.n):\n if self.blocks[i] == mID:\n count += 1\n self.blocks[i] = -1\n return count\n``` | 8 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
[Python 3] First Fit | design-memory-allocator | 0 | 1 | ```\nclass Allocator:\n\n def __init__(self, n: int):\n self.nums = [0] * n\n \n\n def allocate(self, size: int, mID: int) -> int:\n if size > len(self.nums): return -1\n \n\t\t# availableBlocks is to calculate size of available memory blocks and their starting index.\n availableBlocks = []\n cnt = start = 0\n for idx, i in enumerate(self.nums):\n if i == 0:\n if cnt == 0: start = idx\n cnt += 1\n else:\n if cnt != 0: availableBlocks.append([cnt, start])\n cnt = 0\n if cnt != 0:\n availableBlocks.append([cnt, start])\n \n\t\t# now check the available memory blocks to fit the new incoming block\n for i, j in availableBlocks:\n if size <= i:\n for x in range(j, j + size):\n self.nums[x] = mID\n return j\n return -1\n \n\n def free(self, mID: int) -> int:\n res = 0\n for i in range(len(self.nums)):\n if self.nums[i] == mID:\n res += 1\n self.nums[i] = 0\n return res\n``` | 1 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
Python 3 || Brute Force | design-memory-allocator | 0 | 1 | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n O(n)\n# Code\n```\nclass Allocator:\n\n def __init__(self, n: int):\n self.arr=[0 for i in range(n)]\n self.n=n\n\n def allocate(self, size: int, mID: int) -> int:\n index=-1\n t=0\n for i in range(self.n-1,-1,-1):\n if(self.arr[i]==0):\n t+=1\n if(t>=size):\n index=i\n else:\n t=0\n if(index==-1):\n return index\n for i in range(index,index+size):\n self.arr[i]=mID\n return index\n def free(self, mID: int) -> int:\n t=0\n for i in range(self.n):\n if(self.arr[i]==mID):\n self.arr[i]=0\n t+=1\n return t\n\n\n# Your Allocator object will be instantiated and called as such:\n# obj = Allocator(n)\n# param_1 = obj.allocate(size,mID)\n# param_2 = obj.free(mID)\n``` | 2 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
Python- Abuse strings to beat 97% in O(n) | design-memory-allocator | 0 | 1 | # Approach\nEncode the whole thing as a unicode string, where the free blocks and non-free blocks have identities as characters. Then use the string api to implement behavior.\n\n# Complexity\n- Time complexity:\n$O(n)$, but very nice constant factor\n\n- Space complexity:\n$O(n)$\n\n\n# Code\n```\nFREE = chr(0)\n\nclass Allocator:\n\n def __init__(self, n: int):\n self.data = FREE*n \n\n def allocate(self, size: int, mID: int) -> int:\n i = self.data.find(FREE*size)\n if i != -1:\n self.data = self.data[:i] + chr(mID)*size + self.data[i+size:]\n return i\n\n def free(self, mID: int) -> int:\n freed = self.data.count(chr(mID))\n self.data = self.data.replace(chr(mID), FREE)\n return freed\n\n\n# Your Allocator object will be instantiated and called as such:\n# obj = Allocator(n)\n# param_1 = obj.allocate(size,mID)\n# param_2 = obj.free(mID)\n``` | 3 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
Real allocator that beats 100% | design-memory-allocator | 0 | 1 | # Intuition\n1. Use a linked list to track all memory blocks. It starts with a single block for all the available memory\n2. Use a dict to track all allocations\n\nIf you like my implementation please upvote!\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Allocator:\n class Block:\n def __init__(self, size: int, free: bool = False):\n self.size = size\n self.free = free\n self.next = None\n\n def __init__(self, n: int):\n #self.memo = [0] * n\n self.available = n\n self.allocated = dict()\n self.head = self.Block(0, 0)\n self.head.next = self.Block(self.available, True)\n\n def allocate(self, size: int, mID: int) -> int:\n offset = 0\n if size <= self.available:\n prev = self.head\n p = prev.next\n while p and (not p.free or p.size < size):\n offset += p.size\n prev = p\n p = p.next\n if not p:\n return -1\n if size < p.size:\n sub = self.Block(p.size - size, True)\n sub.next = p.next\n p.next = sub\n p.free = False\n p.size = size\n blocks = self.allocated.setdefault(mID, set())\n blocks.add(p)\n self.available -= size\n return offset\n else:\n return -1\n\n def free(self, mID: int) -> int:\n r = 0\n blocks = self.allocated.get(mID)\n if blocks:\n for block in blocks:\n self.available += block.size\n r += block.size\n self.free_block(block)\n blocks.clear()\n del self.allocated[mID]\n return r\n\n def free_block(self, block: Block):\n block.free = True\n # merge with next block\n if block.next and block.next.free:\n block.size += block.next.size\n block.next = block.next.next\n\n # check if we need to merge with prev block\n prev = self.head\n p = prev.next\n while p and p != block:\n prev = p\n p = p.next\n if prev.free:\n prev.size += block.size\n prev.next = block.next\n\n``` | 2 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
Python Solution | HashMap and List | Easy to Understand | design-memory-allocator | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1) <b>Constructor</b>\n For memory allocation, We use a list i.e. ```self.memory``` and to store indices of allocated memory to ```mID```, We use hashmap i.e. ```self.hashMap``` which stores ```mID``` and all indices allocated to it.\n\n2) <b>Allocate</b>\n To allocate free memory, We need to check free space in the memory vector and allocate it. We also need to store indices of allocated memory in hashmap and return starting index of allocated memory.\n\n3) <b>Free</b>\nTo free allocated memory, we use hashmap to get indices of allocated memory and clear the space by assigning ```0``` to it and return number of indices allocated to ```mID```.\n\n# Complexity\nHere, ```N``` is Memory Size, ```size``` is size of allocated memory, ```M``` is Number of allocated indices\n\n- Time complexity:\n - Constructor: $$O(1)$$\n - Allocate : $$O(N + size)$$\n - Free : $$O(M)$$\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Allocator:\n\n def __init__(self, n: int):\n self.memory, self.sz, self.hashMap = [0] * n, n, defaultdict(list)\n\n def allocate(self, size: int, mID: int) -> int:\n free, idx = 0, 0\n for i in range(self.sz):\n if free == 0: \n idx = i\n if self.memory[i] == 0: \n free += 1\n else: \n free = 0\n if free >= size: \n break\n if free >= size:\n for i in range(idx, idx + size):\n self.memory[i] = mID\n self.hashMap[mID].append(i)\n return idx if free >= size else -1\n\n def free(self, mID: int) -> int:\n count = 0\n for idx in self.hashMap[mID]:\n self.memory[idx] = 0\n count += 1\n del self.hashMap[mID]\n return count\n\n\n# Your Allocator object will be instantiated and called as such:\n# obj = Allocator(n)\n# param_1 = obj.allocate(size,mID)\n# param_2 = obj.free(mID)\n``` | 2 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
python3 beats 98% | design-memory-allocator | 0 | 1 | \nApproach: merge the list of blocks to be freed with the freelist in one pass. This requires list of blocks to be freed to be sorted by offset.\n(if there adjacent blocks in list of blocks to be freed, then combine them before freeing them)\n\n# Code\n```\n\nclass Entry:\n def __init__(self, offset, size, mid):\n self.offset = offset\n self.size = size\n self.mid = mid\n\n def __repr__(self):\n return f"(at={self.offset} sz={self.size} id={self.mid})"\n\nclass Allocator:\n\n def __init__(self, n: int):\n self.arena = [0] * n\n self.free_list = [Entry(0, n, -1,)]\n self.mid_to_mem={}\n \n\n def allocate(self, size: int, mID: int) -> int:\n for idx in range(0, len(self.free_list)):\n elm = self.free_list[idx]\n if elm.size >= size:\n alloc = Entry(elm.offset, size, mID)\n if mID not in self.mid_to_mem:\n self.mid_to_mem[mID] = [ alloc ]\n else:\n self.mid_to_mem[mID].append(alloc)\n\n elm.offset += size\n elm.size -= size\n\n if elm.size == 0:\n self.free_list.pop(idx)\n\n #Allocator.validate(self.free_list)\n return alloc.offset\n \n return -1\n\n def free(self, mID: int) -> int:\n if mID in self.mid_to_mem:\n #to_free = len(self.mid_to_mem[mID])\n\n flist = self.mid_to_mem[mID]\n to_free = reduce(lambda a, b : a + b.size, flist, 0)\n self.mid_to_mem[mID] = []\n\n flist.sort(key = lambda elm : elm.offset)\n #print(f"to free {flist}")\n Allocator.free_all(flist, self.free_list)\n\n #Allocator.validate(self.free_list)\n return to_free\n \n return 0\n \n def free_all(flist, free_list):\n\n idx = 0\n while idx < len(flist):\n if idx + 1 == len(flist):\n break\n if flist[idx].offset + flist[idx].size == flist[idx+1].offset:\n flist[idx].size += flist[idx+1].size\n del flist[idx+1]\n else:\n idx += 1\n\n #print(f"before: {free_list}")\n\n\n\n flist_idx = 0\n if flist_idx >= len(flist):\n return\n e = flist[flist_idx]\n\n idx = 0\n prev = -1\n while idx < len(free_list):\n\n eat = e.offset + e.size\n if eat == free_list[idx].offset:\n\n while True:\n free_list[idx].offset -= e.size\n free_list[idx].size += e.size\n \n if idx - 1 < 0:\n break\n e = free_list[idx-1]\n if free_list[idx].offset != e.offset:\n break\n del free_list[idx-1]\n idx -= 1\n\n flist_idx += 1\n if flist_idx >= len(flist):\n return\n e = flist[flist_idx]\n elif free_list[idx].offset + free_list[idx].size == e.offset:\n while True: \n free_list[idx].size += e.size\n if idx + 1 == len(free_list):\n break \n e = free_list[idx+1]\n if free_list[idx].offset + free_list[idx].size != e.offset:\n break\n del free_list[idx+1]\n\n flist_idx += 1\n if flist_idx >= len(flist):\n return\n e = flist[flist_idx]\n\n\n\n elif eat < free_list[idx].offset:\n free_list.insert(idx, e)\n flist_idx += 1\n if flist_idx >= len(flist):\n return\n e = flist[flist_idx]\n continue\n\n idx += 1\n\n if flist_idx < len(flist):\n free_list.extend(flist[flist_idx:])\n\n def validate(free_list):\n prev = -1 \n for e in free_list:\n if prev >= e.offset:\n print(free_list)\n assert False\n\n assert e.offset >= 0\n assert e.size >= 0\n prev = e.offset + e.size\n\n \n\n\n# Your Allocator object will be instantiated and called as such:\n# obj = Allocator(n)\n# param_1 = obj.allocate(size,mID)\n# param_2 = obj.free(mID)\n``` | 0 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
beats 100 % easy solution | design-memory-allocator | 0 | 1 | # Intuition\n\nThis is similar to non-overlaping ranges solution. if you have solved those problems, you will find this easy too.\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe make a list where we store ranges of memory allocated in sorted manned. This way we can find any memory range in log(n) and delete it. We alse store what all ranges an id has in a dictionry. This way we can find all ranges of memoey allocated to an id in O(1) \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- N Log(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Allocator:\n\n def __init__(self, n: int):\n self.a = [(0,0),(n,n)]\n self.d = defaultdict(list)\n self.n = n\n \n\n def allocate(self, size: int, mID: int) -> int:\n for i in range(len(self.a)-1):\n diff = self.a[i+1][0] - self.a[i][1]\n if diff >= size:\n val = self.a[i][1]\n s,e = self.a[i]\n self.d[mID].append((e, e + size))\n e += size\n \n if e == self.a[i+1][0]:\n e = self.a[i+1][1]\n del self.a[i+1]\n del self.a[i]\n self.a.insert(i,(s,e))\n \n return val\n \n return -1\n\n \n\n def free(self, mID: int) -> int:\n ans = 0\n for s,e in self.d[mID]:\n ans += e-s\n pos = bisect_left(self.a, (s,e))\n if pos-1 >= 0 and self.a[pos - 1][1] >= e:\n s2, e2 = self.a[pos - 1]\n del self.a[pos - 1]\n if s2 != s:\n self.a.insert(pos - 1,(s2,s))\n if e2 != e or e2 == self.n:\n self.a.insert(pos,(e,e2))\n elif pos < len(self.a) and self.a[pos][0] == s:\n s2, e2 = self.a[pos]\n del self.a[pos]\n if e2 != e or e2 == self.n:\n self.a.insert(pos,(e,e2))\n if s == 0:\n self.a.insert(0,(0,0))\n \n else:\n print("PROBLEM", self.a,self.d[mID],s,e,pos)\n self.d[mID] = []\n \n return ans\n\n\n# Your Allocator object will be instantiated and called as such:\n# obj = Allocator(n)\n# param_1 = obj.allocate(size,mID)\n# param_2 = obj.free(mID)\n``` | 0 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the given id `mID`.
**Note** that:
* Multiple blocks can be allocated to the same `mID`.
* You should free all the memory units with `mID`, even if they were allocated in different blocks.
Implement the `Allocator` class:
* `Allocator(int n)` Initializes an `Allocator` object with a memory array of size `n`.
* `int allocate(int size, int mID)` Find the **leftmost** block of `size` **consecutive** free memory units and allocate it with the id `mID`. Return the block's first index. If such a block does not exist, return `-1`.
* `int free(int mID)` Free all memory units with the id `mID`. Return the number of memory units you have freed.
**Example 1:**
**Input**
\[ "Allocator ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "allocate ", "allocate ", "free ", "allocate ", "free "\]
\[\[10\], \[1, 1\], \[1, 2\], \[1, 3\], \[2\], \[3, 4\], \[1, 1\], \[1, 1\], \[1\], \[10, 2\], \[7\]\]
**Output**
\[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0\]
**Explanation**
Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.
loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes \[**1**,\_,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 0.
loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes \[1,**2**,\_,\_,\_,\_,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes \[1,2,**3**,\_,\_,\_,\_,\_,\_,\_\]. We return 2.
loc.free(2); // Free all memory units with mID 2. The memory array becomes \[1,\_, 3,\_,\_,\_,\_,\_,\_,\_\]. We return 1 since there is only 1 unit with mID 2.
loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes \[1,\_,3,**4**,**4**,**4**,\_,\_,\_,\_\]. We return 3.
loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes \[1,**1**,3,4,4,4,\_,\_,\_,\_\]. We return 1.
loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes \[1,1,3,4,4,4,**1**,\_,\_,\_\]. We return 6.
loc.free(1); // Free all memory units with mID 1. The memory array becomes \[\_,\_,3,4,4,4,\_,\_,\_,\_\]. We return 3 since there are 3 units with mID 1.
loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.
loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.
**Constraints:**
* `1 <= n, size, mID <= 1000`
* At most `1000` calls will be made to `allocate` and `free`. | null |
🤯 [Python] Simplest solution | Detailed explanation | BFS + Heap | Codeplug | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\nWe need to traverse to the furthest possible distance from 0,0 for any given query. A BFS can help here, but normal BFS means we explore all possible neighbours, can we improve it by greedily selecting the smallest neighbour first?\n\nAnd as soon as we reach a neighbour thats >= query, we can stop the traversal as we know all other remaining neighbours will not satisfy the condition.\n\n# Approach\n1. We can choose min-heap for greedily choosing the smallest cell to explore in every step of BFS. \n2. We only care about unique query values, since for a given input the output will always be the same.\n3. If we can sort the input queries, we are sure that the incoming query will be > than the previous query, so we start the BFS from where we left off, and increase the previous count during the traversal, so we skip starting from 0,0 again and again. Our heap already preserves the boundary of the previous query, we dont reset it for every new query. We also store the result for prev query in a variable.\n4. We can store the res for a given query in a dicitonary/map so that, in the end form the result array using the query results.\n\n**Upvote if you understood the solution :)**\n# Complexity\n- Time complexity:\n$$O(max(k, m*n*log(m*n)))$$\n\n- Space complexity:\n$$O(max(k, m*n))$$\n\n# Code\n```python []\nclass Solution:\n def maxPoints(self, grid, qs: List[int]) -> List[int]:\n queries = sorted(set(qs))\n res = {}\n rows, cols = len(grid), len(grid[0])\n q = [(grid[0][0], 0, 0)] # heap\n prevCount = 0\n\n for num in queries:\n count = prevCount\n\n while q:\n val, r, c = q[0]\n\n if val >= num: break # pop only when the condition satisfy else break\n else:\n heappop(q)\n grid[r][c] = None\n count += 1\n\n for i, j in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:\n if 0 <= i < rows and 0 <= j < cols and grid[i][j] is not None:\n heappush(q, (grid[i][j], i, j))\n grid[i][j] = None\n\n res[num] = prevCount = count\n\n ans = [res[num] for num in qs]\n return ans\n```\n | 4 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
Python solution: priority queue and then binary search | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to find the threshold to gain a point at each coordinate\nThe answer is the maximum between grid[i][j] and the minimum of thresholds of its neighbours\n\nTherefore I figured I should not be doing BFS, but should use a priority queue instead.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe queries are simple: just sort all the thresholds and use binary search to find points gained\n\n# Code\n```\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n m, n = len(grid), len(grid[0])\n threshold = [[0 for j in range(n)] for i in range(m)]\n heap = []\n heapq.heappush(heap, [grid[0][0], 0, 0])\n while heap:\n while heap and threshold[heap[0][1]][heap[0][2]] > 0:\n heapq.heappop(heap)\n if heap:\n cost, x, y = heapq.heappop(heap)\n threshold[x][y] = cost\n for nx, ny in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:\n if 0 <= nx < m and 0 <= ny < n:\n heapq.heappush(heap, [max(grid[nx][ny], cost), nx, ny])\n elements = []\n for i in range(m):\n for j in range(n):\n elements.append(threshold[i][j])\n elements.sort()\n \n result = []\n for query in queries:\n result.append(bisect.bisect_left(elements, query))\n return result\n \n``` | 3 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
Intuitive Python BFS with Heap explained + complexity | maximum-number-of-points-from-grid-queries | 0 | 1 | Inuition:\n\n* Iterate through the queries from smallest to largest.\n* BFS, starting from top-left. Only visit cells that are smaller than the current query.\n * Once we visit a cell, then we will consider the neighbors.\n * Priority queue / min-heap helps us do this efficiently. Priority is based on value of the grid cell.\n * Increment n_visited when visiting a cell. When there are no more candidate nodes in the heap, then n_visited is the answer for the current query.\n\nComplexity, I believe, is *k\\*log(k) + m\\*n + m\\*n\\*log(m\\*n)*.\n\n* k\\*log(k) for sorting the queue (k = len(queries)).\n* m\\*n for traversing the grid.\n* m\\*n\\*log(m\\*n)) for the heap.\n\n```python\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n # Some setup\n dirs = [(0,1),(1,0),(-1,0),(0,-1)]\n nrows = len(grid)\n ncols = len(grid[0])\n\t\t\n # Sort queries. Keep track of the original index.\n q_and_i = [[queries[i], i] for i in range(len(queries))]\n q_and_i.sort() # Sort based on the value of the query\n\t\n # Prepare for BFS. Start with top-left cell.\n answer = [0 for _ in range(len(queries))]\n heap = [[grid[0][0], 0, 0]]\n seen = {(0,0)} # Cells we have seen (but not necessarily visited)\n n_visited = 0\n\t\t\n # BFS. Go through queries from smallest to largest.\n for q, i in q_and_i:\n\t\t # Only visit a cell if it is less than the current query\n while heap and heap[0][0] < q:\n n_visited += 1\n _, r, c = heapq.heappop(heap)\n\t\t\t\t# Check all neighboring cells\n for h, v in dirs:\n r2, c2 = r + v, c + h\n\t\t\t\t\t# Check that coordinates are valid\n if r2 >= 0 and r2 < nrows and c2 >= 0 and c2 < ncols:\n\t\t\t\t\t # Check that the cell has never been in the heap\n if (r2, c2) not in seen:\n\t\t\t\t\t\t # Add cell to our options\n seen.add((r2, c2))\n heapq.heappush(heap, [grid[r2][c2], r2, c2])\n\t\t\t# Update the answer for the current query\n answer[i] = n_visited\n #\n return answer\n``` | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
Python BFS + Min Heap Solution, Faster than 100% | maximum-number-of-points-from-grid-queries | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can sort queries. Just remember to return the results in the original order. Given a threshold ```query```, we can form a reachable region from (0,0), and we can record the boundary. This can be done by BFS with min heap. Given a larger threshold and a recorded boundary, we can enlarge the reachable region by the same method.\nThe complexity is O(m*n + klogk) because, despite all these queries, we have only one BFS across the whole grid effectively, and we have one sort on queries.\n\n# Code\n```\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n numRows, numCols = len(grid), len(grid[0])\n queriesSorted, hashMap = sorted(queries), {}\n heap, visited = [(grid[0][0], 0, 0)], set()\n visited.add((0, 0))\n for query in queriesSorted:\n while heap:\n val, row, col = heap[0]\n if val >= query:\n break\n heappop(heap)\n for newRow, newCol in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):\n if newRow < 0 or newRow >= numRows or newCol < 0 or newCol >= numCols: \n continue\n if (newRow, newCol) in visited: \n continue\n heappush(heap, (grid[newRow][newCol], newRow, newCol))\n visited.add((newRow, newCol))\n hashMap[query] = len(visited) - len(heap)\n return [hashMap[query] for query in queries]\n\n``` | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
[Python3] BFS + heap + prefixsum | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nKeep visiting smallest nodes as you see them. Keep running maximum and store that track that maximum number -> nodes seen. Take the keys and values out of the array and sort by key. Calculate prefix sum of the values. For each query, perform a binary search to find # of nodes below value `q`\n\n# Complexity\n- Time complexity:\n- $$O(n\\log{n})$$\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- $$O(n)$$\n\n# Code\n```\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n g = defaultdict(int)\n visited = []\n visited.append((grid[0][0], 0,0))\n vis = set()\n m = 0\n while visited:\n tv, tl, tr = heappop(visited)\n if (tl,tr) in vis:\n continue\n vis.add((tl, tr))\n m = max(tv, m)\n print(tv, tl, tr, m)\n \n g[m]+=1\n for x,y in [[-1, 0], [1, 0], [0, 1], [0, -1]]:\n a = tl+x\n b = tr +y\n if a >=0 and a < len(grid) and b >=0 and b < len(grid[0]):\n if (a,b) not in vis:\n heappush(visited, (grid[a][b], a, b))\n print(g)\n res = []\n gsort = [[k,v] for k,v in g.items()]\n gsort.sort()\n for i in range(1, len(gsort)):\n gsort[i][1] += gsort[i-1][1]\n print(gsort)\n for q in queries:\n dex = bisect_left(gsort, [q-1, float(\'inf\')])-1\n if q <= gsort[dex][0]:\n res.append(0)\n continue\n res.append(gsort[dex][1])\n return res\n \n \n \n \n``` | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
Python3 Djikstra Priority Queue | maximum-number-of-points-from-grid-queries | 0 | 1 | Run dijkstra through the matrix. Update the maximum number you\'ve reached as you go along and keep your results in a dictionary. \n-->Your dictionary should keep track of the maximum number of cells each number can reach\nFor each query, find the maximum in your dictionary that you can reach. Could binary search this part if necessary.\n\n```\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n mydict = defaultdict(int)\n dirs = ((0, 1), (0, -1), (1, 0), (-1, 0))\n height, width = len(grid) - 1, len(grid[0]) - 1\n \n # use a priority q to run djikstra\n q = [(grid[0][0], 0, 0)]\n visited = {(0, 0)}\n count, hi = 0, 0\n while q:\n value, row, col = heapq.heappop(q)\n # we get a point for every square\n count += 1\n # keep track of the max number we\'ve gotten to\n hi = max(hi, value)\n # update the value of the maximum value in our dictionary to reflect how many squares it can take\n mydict[hi] = count\n for dir in dirs:\n new_row, new_col = row + dir[0], col + dir[1]\n if 0 <= new_row <= height and 0 <= new_col <= width and (new_row, new_col) not in visited:\n visited.add((new_row, new_col))\n heapq.heappush(q, (grid[new_row][new_col], new_row, new_col))\n \n answer = []\n # For each query check for the highest number we can reach from our dijkstra dictionary\n # Can probably binary search this part to make it faster, but wasn\'t required to pass test cases \n for query in queries:\n hi = 0\n for key, value in mydict.items():\n if key < query:\n hi = max(hi, value)\n else:\n break\n answer.append(hi)\n return answer\n``` | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
[Python] with explanation, dynamic programming, dfs, heap | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe bigger query will cover all nodes traversed by the smaller queries.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. sort the query array and keep track of its original index to solve the problem with dynamic programming\n2. traverse all possible nodes and mark them as visited\n3. if a node is larger or equal to the query we keep track of it, and try to solve it in the next query\n4. try to traverse from the nodes we can\'t solve from the previous query\n\nUsing a heap or using binary search to maintain the order of the nodes to be solved next can save some time. (if not the result will be: TLE)\n# Complexity\n- Time complexity: $$O(Q*M*N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M*N+Q)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nPlease correct me if I\'m wrong, thanks.\n# Code\n```python3\nimport heapq\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n m, n = len(grid), len(grid[0])\n def dfs(q, r=0, c=0):\n dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]\n count = 1\n for dr, dc in dirs:\n nr, nc = r+dr, c+dc\n if nr < 0 or nr >= m or nc < 0 or nc >= n or (nr, nc) in visited:\n continue\n if (nr, nc) in edges_set:\n continue\n if q <= grid[nr][nc]:\n heapq.heappush(edges, (grid[nr][nc], nr, nc))\n edges_set.add((nr, nc))\n continue\n visited.add((nr, nc))\n count += dfs(q, nr, nc)\n\n return count\n \n result = [0] * len(queries)\n pos = [(q, i) for i, q in enumerate(queries)]\n pos.sort()\n visited = set()\n edges = [(grid[0][0], 0, 0)]\n edges_set = set() # to avoid additional node being added to edges(heap)\n edges_set.add((0, 0))\n points = 0\n for q, i in pos:\n for _ in range(len(edges)):\n val, r, c = edges[0]\n if q > val and (r, c) not in visited:\n heapq.heappop(edges)\n edges_set.remove((r, c))\n visited.add((r, c))\n points += dfs(q, r, c)\n else:\n break\n result[i] = points\n \n return result\n``` | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
[C++|Python3] priority queue + binary search | maximum-number-of-points-from-grid-queries | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/8f409c5e220a4a1a1d7fdfbfcc1dcd24eeead232) for solutions of weekly 323. \n\n**Intuition**\nHere I traverse the grid from the top-left cell. In the meantime, I use a priority queue to keep track of the largest value required to reach a cell. A separate counter is updated to indicate how many cells accessible prior to arriving at the current cell. This information is kept in an array via a value-count pair. \nFor each queries, I binary search the array to find the number of cells whose corresponding value is strictly smaller than the given query. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n vector<int> maxPoints(vector<vector<int>>& grid, vector<int>& queries) {\n int m = grid.size(), n = grid[0].size(), dir[5] = {-1, 0, 1, 0, -1}, prefix = 0, prev = INT_MIN; \n vector<pair<int, int>> point; \n priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> pq; \n pq.emplace(grid[0][0], 0, 0); \n grid[0][0] = 0; \n while (pq.size()) {\n auto [v, i, j] = pq.top(); pq.pop(); \n if (prev != v) point.emplace_back(prev, prefix); \n ++prefix; \n prev = v; \n for (int k = 0; k < 4; ++k) {\n int ii = i + dir[k], jj = j + dir[k+1]; \n if (0 <= ii && ii < m && 0 <= jj && jj < n && grid[ii][jj]) {\n int vv = max(v, grid[ii][jj]); \n pq.emplace(vv, ii, jj); \n grid[ii][jj] = 0; \n }\n }\n }\n point.emplace_back(prev, prefix); \n vector<int> ans; \n for (auto& q : queries) {\n auto it = lower_bound(point.begin(), point.end(), make_pair(q, 0)); \n ans.push_back((--it)->second); \n }\n return ans; \n }\n};\n```\n**Java**\n```\nclass Solution {\n public int[] maxPoints(int[][] grid, int[] queries) {\n int m = grid.length, n = grid[0].length, prev = Integer.MIN_VALUE, prefix = 0; \n int[][] dir = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; \n Queue<int[]> pq = new PriorityQueue<>((a, b)->(a[0]-b[0])); \n pq.add(new int[]{grid[0][0], 0, 0}); \n grid[0][0] = 0; \n List<Integer> keys = new ArrayList(); \n List<Integer> vals = new ArrayList(); \n while (pq.size() > 0) {\n int[] elem = pq.remove(); \n int v = elem[0], i = elem[1], j = elem[2]; \n if (prev != v) {\n keys.add(prev); \n vals.add(prefix); \n }\n ++prefix; \n prev = v; \n for (var d : dir) {\n int ii = i + d[0], jj = j + d[1]; \n if (0 <= ii && ii < m && 0 <= jj && jj < n && grid[ii][jj] > 0) {\n int vv = Math.max(v, grid[ii][jj]); \n pq.add(new int[]{vv, ii, jj}); \n grid[ii][jj] = 0; \n }\n }\n } \n keys.add(prev); \n vals.add(prefix); \n int sz = queries.length; \n int[] ans = new int[sz]; \n for (int i = 0; i < sz; ++i) {\n int k = Collections.binarySearch(keys, queries[i]);\n if (k < 0) k = -k-1; \n ans[i] = vals.get(k-1); \n }\n return ans; \n }\n}\n```\n**Python3**\n```\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n m, n = len(grid), len(grid[0])\n point = []\n prefix = 0 \n prev = -inf \n pq = [(grid[0][0], 0, 0)]\n grid[0][0] = 0 \n while pq: \n v, i, j = heappop(pq)\n if prev != v: point.append((prev, prefix))\n prefix += 1\n prev = v\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj]: \n vv = max(v, grid[ii][jj])\n heappush(pq, (vv, ii, jj))\n grid[ii][jj] = 0\n point.append((prev, prefix))\n ans = []\n for q in queries: \n i = bisect_left(point, q, key=lambda x: x[0]) - 1\n ans.append(point[i][1])\n return ans \n```\n**Complexity**\nTime `O((MN+Q)logMN)`\nSpace `O(MN+Q)` | 11 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
Python 3 Solution with Explanation - Heap + Binary Search + BFS | maximum-number-of-points-from-grid-queries | 1 | 1 | **Explanation**\nIt is an graph based question we just have to get the full path from the top left (0,0).\nAnd after that we have to just do a simple binary search (bisect_left or lower_bound) in the *order*\nto get the result.\n\n\n\n\n\n\n\n\tclass Solution:\n\t\tdef maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n\t\t\t#It is a simple questions based on the concept of graph\n\t\t\t#As we all know we can represent a matrix/grid into a graph\n\t\t\t#Then we can use the heap(min Heap) to get a perfect path.\n\t\t\t#Then we are using maxYet(means max till that index).\n\t\t\tm = len(grid)\n\t\t\tn = len(grid[0])\n\t\t\theap = [(grid[0][0], 0, 0)]\n\t\t\tv = {(0, 0)}\n\t\t\torder = []\n\t\t\twhile len(heap) > 0:\n\t\t\t\tcurr, i, j = heapq.heappop(heap)\n\t\t\t\torder.append(curr)\n\t\t\t\tfor x, y in [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]:\n\t\t\t\t\tif 0 <= x < m and 0 <= y < n and (x, y) not in v:\n\t\t\t\t\t\tv.add((x, y))\n\t\t\t\t\t\theapq.heappush(heap, (grid[x][y], x, y))\n\t\t\tmaxYet = -1\n\t\t\tfor i in range(len(order)):\n\t\t\t\tmaxYet = max(maxYet, order[i])\n\t\t\t\torder[i] = maxYet\n\t\t\tres = []\n\t\t\tfor q in queries:\n\t\t\t\tres.append(bisect.bisect_left(order, q))\n\t\t\treturn res | 26 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
[Python] EVERY DETAIL Documented | Short Elegant Heap Solution | maximum-number-of-points-from-grid-queries | 0 | 1 | # Raw Answer (Documented code below)\n\n```\nclass Solution(object):\n def maxPoints(self, grid, queries):\n """\n Original answer: https://leetcode.com/problems/maximum-number-of-points-from-grid-queries/solutions/2899594/python-3-solution-with-explanation-heap-binary-search/\n """\n \n m,n = len(grid), len(grid[0])\n heap = [(grid[0][0],0,0)]\n heapq.heapify(heap)\n visited = {(0,0)}\n path = []\n \n while len(heap)>0:\n val, i, j = heappop(heap)\n path.append(val)\n\n for a,b in [(i,j+1),(i,j-1),(i+1,j),(i-1,j)]:\n if 0<=a<m and 0<=b<n and (a,b) not in visited:\n heapq.heappush(heap, (grid[a][b], a, b))\n visited.add((a,b))\n\n for i in range(1,len(path)):\n path[i] = max(path[i], path[i-1])\n \n return [bisect.bisect_left(path, q) for q in queries]\n \n```\n\n# Explaination w. Documented Code\n\nThe intuition here is to find an "optimized path" through the graph by greedily go to the available block with the lowest score.\n\nThen we can simply count how far each query can go in the optimized path using binary search.\n\nWe use the following data structures / algorithms to speed up our answer:\n\n- Heap: quickly find the smallest element in all available blocks.\n- Hash Map / Dictionary: quickly check if a block was visited before (so we count each block only once)\n- Binary Search: quickly find how many elements in the path are smaller than the query number\n\n```\nclass Solution(object):\n def maxPoints(self, grid, queries):\n """\n :type grid: List[List[int]]\n :type queries: List[int]\n :rtype: List[int]\n\n Original answer: https://leetcode.com/problems/maximum-number-of-points-from-grid-queries/solutions/2899594/python-3-solution-with-explanation-heap-binary-search/\n """\n\n m,n = len(grid), len(grid[0])\n\n # The heap would be important since it allows us to quickly find the block with lowerst score\n # We use it to keep track of all the available blocks\n heap = [(grid[0][0],0,0)]\n heapq.heapify(heap)\n\n # We use a hash table to quickly check if a block has been visited before\n # as we want to make sure each block only gives us score once\n visited = {(0,0)}\n\n # This would be the optimized path\n path = []\n \n while len(heap)>0:\n\n # The heappop function gives the element in the heap with the smallest value (and removes it)\n # We are using a tuple, it by default gives us the one with the smallest first value\n # (In this case the first value is the value of the block)\n val, i, j = heappop(heap)\n\n # We add the smallest first value to the path\n path.append(val)\n \n\n # For all valid blocks next to the visited block that has not been visited before,\n # we add them to the queue to mark them as available \n for a,b in [(i,j+1),(i,j-1),(i+1,j),(i-1,j)]:\n if 0<=a<m and 0<=b<n and (a,b) not in visited:\n heapq.heappush(heap, (grid[a][b], a, b))\n\n # Make sure we don\'t double count by making them visited\n visited.add((a,b))\n \n # Note that in order to access the next block in the path we\'ll have to visit the blocks before it\n # So the value of the query need to be larger than everything before it to access the block\n # e.g. the 1 in the bottom right corner of example 1 has a small value but can only be accessed\n # after the query visits the 5 next to it. In the queue it would only be added after 5 has\n # been visited, and therefore would only be appended to path after the 5\n\n # Thus we make each element to be the max of itself and all elements before it in the path\n # Then if the value of query is larger than the n^th element it has access to the element\n for i in range(1,len(path)):\n path[i] = max(path[i], path[i-1])\n \n # Finally, we use binary search to find the number of elements the query is larger than\n # Do this for each q in query and find the answer\n # Note that by construction the path is a sorted list, which is pretty nice!\n return [bisect.bisect_left(path, q) for q in queries]\n \n``` | 2 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
Python - Heap + Binary Search - Video Solution | maximum-number-of-points-from-grid-queries | 0 | 1 | I have explained the solution in this [video](https://youtu.be/zZWSZM7fboI).\n\n**Time**: `O( mn. log(mn) + k. log(mn))`\n\n**Space**: `O(mn)`\n\nIf this was helpful, please **Upvote**, like the video and subscribe to the channel.\n\n\n```\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n m, n = len(grid), len(grid[0])\n \n min_heap = [(grid[0][0], 0, 0)]\n visited = set()\n visited.add((0,0))\n \n threshold_order = []\n threshold = -1\n \n while min_heap:\n val, r, c = heapq.heappop(min_heap)\n threshold = max(threshold, val)\n threshold_order.append(threshold)\n \n for x,y in [(r+1, c), (r-1, c), (r, c+1), (r, c-1)]:\n if x < 0 or x >= m or y < 0 or y>=n or (x, y) in visited:\n continue\n visited.add((x, y))\n heapq.heappush(min_heap, (grid[x][y], x, y))\n \n res = []\n for q in queries:\n res.append(bisect.bisect_left(threshold_order, q))\n \n return res | 4 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
Python |Binary search | Prioritise BFS | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport heapq\nfrom collections import defaultdict\nfrom bisect import bisect_left\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n \n dirr=[(0,1),(1,0),(0,-1),(-1,0)]\n\n row=len(grid)\n col=len(grid[0])\n visited=set()\n stc=[]\n stc.append((grid[0][0],0,0))\n heapq.heapify(stc)\n visited.add((0,0))\n result=defaultdict(int)\n count=0\n while stc:\n start=stc[0][0]\n result[start]=count\n while stc and stc[0][0]<=start:\n K=heapq.heappop(stc)\n val=K[0]\n r=K[1]\n c=K[2]\n for d in dirr:\n if r+d[0] in range(row) and c+d[1] in range(col) and (r+d[0],c+d[1]) not in visited:\n visited.add((r+d[0],c+d[1]))\n heapq.heappush(stc,(grid[r+d[0]][c+d[1]],r+d[0],c+d[1]))\n count+=1\n ans=[]\n KEY=list(result.keys())\n KEY.sort()\n lk=len(KEY)\n for i in queries:\n K=bisect_left(KEY,i)\n if K<lk:\n ans.append(result[KEY[K]])\n else:\n ans.append(row*col)\n return ans\n \n\n\n \n \n \n\n\n \n``` | 0 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
* Otherwise, you do not get any points, and you end this process.
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
Return _the resulting array_ `answer`.
**Example 1:**
**Input:** grid = \[\[1,2,3\],\[2,5,7\],\[3,5,1\]\], queries = \[5,6,2\]
**Output:** \[5,8,1\]
**Explanation:** The diagrams above show which cells we visit to get points for each query.
**Example 2:**
**Input:** grid = \[\[5,2,1\],\[1,1,2\]\], queries = \[3\]
**Output:** \[0\]
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= grid[i][j], queries[i] <= 106` | null |
Count Pairs Of Similar Strings | count-pairs-of-similar-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n count = 0\n for i in range(len(words)):\n for j in range(i + 1, len(words)):\n if set(words[i]) == set(words[j]):\n count += 1\n return count\n``` | 1 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
[Python] symmetric difference of two Set, Explained. | count-pairs-of-similar-strings | 0 | 1 | We get the character set for each word, and then, we just need to check the difference between any pair of two character sets.\n\nThe python set method: `symmetric_difference` can do the job.\n\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n wd_set = collections.defaultdict(set)\n for idx, wd in enumerate(words):\n wd_set[idx] = set(wd)\n \n ans = 0\n for i in range(len(words) - 1):\n for j in range(i + 1, len(words)):\n if len(wd_set[i].symmetric_difference(wd_set[j])) == 0:\n ans += 1\n return ans\n``` | 1 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
CodeDominar Solution | count-pairs-of-similar-strings | 0 | 1 | # Code\n```\n@1st approach \n\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n d=Counter()\n count=0\n for current_word in words:\n word="".join(sorted(set(current_word)))\n count+=d[word]\n d[word]+=1\n return count \n#####################################\n@2nd approach\n\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n return sum(set(words[i])==set(words[j]) for i in range(len(words)) for j in range(i+1,len(words)))\n\n\n``` | 1 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
[Python 3] Dictionary key is tuple of sorted set || beats 100% || 51ms 🥷🏼 | count-pairs-of-similar-strings | 0 | 1 | ```python3 []\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n d = defaultdict(int)\n for n in words:\n d[tuple(sorted(set(n)))] += 1\n\n return sum(v * (v-1) // 2 for v in d.values())\n```\n\n | 3 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
O(1) space, O(n*k) Time || Hashmap approach [Python3] | count-pairs-of-similar-strings | 0 | 1 | Bear with me, answer isn\'t hard at all\njust follow the intuition\n> Please Leave a like if you liked the approach\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAnalyzing the input array `words` and the problem description `Two strings are similar if they consist of the same characters.` we can see that words can be broken down into their unique characters. For example: *abba* is just \'ab\' and *acab* is just \'acb\'\n\nwith that, I realized that we could store all of the unique chars as keys for a hash and the corresponding values would be the **counts of similar strings**\n{ KEY (unique value): VALUE (**count of similar strings**) }\n\nFor example \n`Example 1: Input: words = ["aba","aabb","abcd","bac","aabc"]`\nwould look something like this:\n\n\nNow that we know how many words share the same letters we can find out how many unique pairs there are by using the n(n-1) /2 formula which finds the non-repeating pairs (idk the name of that formula, and YOU\'RE NOT EXPECTED TO KNOW THAT FORMULA).\n\n *Wondering that if I know the number of elements, how would I know how many unique pairs we can form -> I googled that and found that formula.*\n\nanyway, now that we know that formula and how many instances there are for similar strings, we can iterate through every similar string key in the map, apply that formula to the value and add the result to a counter\n\nlastly, we return that counter\n\n\n# How to convert the word to a key\nTo convert the word to a key we do this in order:\n1. convert string into a set (time complexity of this operation will be K: the average length of word[i])\n`This has a flaw,\nif words are in order like \'abba\' it will work ok since it will store it as \'ab\' but if words are not in order like "bac" it will store it out of order, and it will not match with it\'s corresponding \'abc\' key`\n2. To "order" the characters we will sort the set (time complexity will be O(26) at most, since the set made sure we only have unique characters and we know the string only contains lowercase characters)\n3. Finally we convert this sorted list into a string by using the ".join() operator. This is also constant time since there are max 26 characters.\n\n# Complexity\n- Time complexity: O(n * k) where n is the size of `words` and k is the average length of `words[i]`\n - we traverse the whole `words` array : O(n) \n - inside that traversal, we create create a set for every word: O(k)\n - we sort that set: O(26) -> O(1)\n - we `"".join()` to create sorted array into a string: O(26) -> O(1)\n\n - we traverse the hashmap: O(26) -> O(1)\n\n- Space complexity: O(1)\n - we create a set but it will have at most (26) characters\n - we create a hash, but since the keys will only be unique chars we know that this takes constant space (see image)\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n> Please Leave a like if you liked the approach\n\n# Code\n``` python []\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n wordMap = {}\n\n #we traverse the input array\n for word in words:\n #convert the word into a (unique characters) hashable key\n #(see notes above for explanation)\n curr = sorted(set(word))\n curr = \'\'.join(curr)\n\n #add count of this "similar string" instances\n if curr in wordMap:\n wordMap[curr]+=1\n else:\n wordMap[curr]=1\n\n pairs = 0\n #traverse through all "similar string" keys\n #and add pairs using the unique combination formula\n #(see notes above for explanation)\n for word in wordMap:\n count = wordMap[word]\n pairs += (count* (count-1))//2\n\n \n return pairs\n #Time Compelxity: O(N*K)\n #Space Complexity: O(26) -> O(1)\n\n\n```\n\n> Please Leave a like if you liked the approach | 42 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
[C++|Java|Python3] frequency table + mask | count-pairs-of-similar-strings | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/af6e415cd101768ea8743ea9e4d22d788c9461c3) for solutions of weekly 324. \n\n**Intuition**\nHere, we can use a mask to indicate what characters appear in a word, and use a hash table to indicate the frequency of a mask. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic: \n\tint similarPairs(vector<string>& words) {\n\t\tint ans = 0; \n\t\tunordered_map<int, int> freq; \n\t\tfor (auto& word : words) {\n\t\t\tint mask = 0; \n\t\t\tfor (auto& c : word) mask |= 1 << (c-\'a\'); \n\t\t\tans += freq[mask]++; \n\t\t}\n\t\treturn ans; \n\t}\n};\n```\n**Java**\n```\nclass Solution {\n\tpublic int similarPairs(String[] words) {\n\t\tint ans = 0; \n\t\tHashMap<Integer, Integer> freq = new HashMap(); \n\t\tfor (var word : words) {\n\t\t\tint mask = 0; \n\t\t\tfor (var ch : word.toCharArray()) \n\t\t\t\tmask |= 1<<ch-\'a\'; \n\t\t\tans += freq.getOrDefault(mask, 0); \n\t\t\tfreq.merge(mask, 1, Integer::sum); \n\t\t}\n\t\treturn ans; \n\t}\n}\n```\n**Python3**\n```\nclass Solution: \n\tdef similarPairs(self, words: List[str]) -> int: \n\t\tans = 0\n\t\tfreq = Counter()\n\t\tfor word in words: \n\t\t\tmask = reduce(or_, (1<<ord(ch)-97 for ch in word))\n\t\t\tans += freq[mask]\n\t\t\tfreq[mask] += 1\n\t\treturn ans\n```\n**Complexity**\nTime O(NW) \nSpace O(N) \n | 52 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
Python Easy to Understand code || Accepted✅ | count-pairs-of-similar-strings | 0 | 1 | # Approach\nusing sets to check if two words in the array words contain same characters. \n\n# Complexity\n- Time complexity:\nsince a nested for is used, O(n^2)\n\n# Code\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n count = 0\n for i in range(len(words)):\n for j in range(i):\n #checking if 2 words has characters and then incrementing count\n if set(words[i]) == set(words[j]):\n count += 1\n return count\n``` | 2 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
Python 3 || 1-5 lines, tuple and Counter , w/ explanation || T/M: 61 ms / 13.9 MB | count-pairs-of-similar-strings | 0 | 1 | ```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n\n words = [set (w) for w in words] # <\u2013\u2013 map each word to its letter-set\n words = [sorted(w) for w in words] # <\u2013\u2013 map each letter-set to its sorted list\n words = [tuple (w) for w in words] # <\u2013\u2013 map each list to a tuple to facilitate\n # the use of `Counter`.\n\n c = Counter(words)\n \n return sum(n*(n-1) for n in c.values())//2 # <\u2013\u2013 count the piars of similar strings\n```\nThe one-liner:\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n\n return sum(n*(n-1) for n in Counter([tuple(sorted(set(w)))\n for w in words]).values())//2\n```\n\n[https://leetcode.com/problems/count-pairs-of-similar-strings/submissions/861730499/](http://)\n\nI could be wrong, but I think that time is *O*(*N*) and space is *O*(*N*). | 5 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
Python3 Simple Hash Map Solution | count-pairs-of-similar-strings | 0 | 1 | \n# Approach\n1. We can hash the word as its unique characters sorted i.e `bacddd == abcd`.\n2. Now loop through the words updating the counts of each word type to find the amount of similar words. \n3. To find how many pairs there are we use the $$nC_2$$ formula which is simplified as $$\\frac{n*(n-1)}{2}$$\n\n# Code\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n counts = {}\n \n for word in words:\n s = str(sorted(set(word)))\n \n if s in counts:\n counts[s] += 1\n else:\n counts[s] = 1\n \n return sum(int(n*(n-1)/2) for n in counts.values())\n\n``` | 1 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
Python 3 count distinct pairs and adding into count variable | count-pairs-of-similar-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n\n d=Counter()\n count=0\n for current_word in words:\n word="".join(sorted(set(current_word)))\n count+=d[word]\n d[word]+=1\n\n return count \n\n\n``` | 2 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
Python | Easy Solution✅ | count-pairs-of-similar-strings | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n count = 0\n for i in range(len(words)):\n for j in range(i):\n if set(words[i]) == set(words[j]):\n count +=1\n return count\n\n``` | 6 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
Python Accepted ✅ | count-pairs-of-similar-strings | 0 | 1 | ```\nclass Solution:\n def similarPairs(self, w: List[str]) -> int:\n cnt=0\n for i in range(len(w)):\n for j in range(i):\n # print(i,j)\n if set(w[i])==set(w[j]):\n cnt+=1\n return cnt\n \n``` | 10 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
Simple python solution using Brute-Force | count-pairs-of-similar-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n c=0\n for i in range(len(words)):\n for j in range(i+1,len(words)):\n a=[letter for letter in words[i]]\n b=[letter for letter in words[j]]\n if(set(a)==set(b)):\n c=c+1\n\n return c\n \n \n\n``` | 0 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the same characters.
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
**Example 1:**
**Input:** words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]
**Output:** 2
**Explanation:** There are 2 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 3 and j = 4 : both words\[3\] and words\[4\] only consist of characters 'a', 'b', and 'c'.
**Example 2:**
**Input:** words = \[ "aabb ", "ab ", "ba "\]
**Output:** 3
**Explanation:** There are 3 pairs that satisfy the conditions:
- i = 0 and j = 1 : both words\[0\] and words\[1\] only consist of characters 'a' and 'b'.
- i = 0 and j = 2 : both words\[0\] and words\[2\] only consist of characters 'a' and 'b'.
- i = 1 and j = 2 : both words\[1\] and words\[2\] only consist of characters 'a' and 'b'.
**Example 3:**
**Input:** words = \[ "nba ", "cba ", "dba "\]
**Output:** 0
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consist of only lowercase English letters. | null |
Python 3 || 10 lines, recursion, w/ brief explanation || T/M: 128 ms / 13.8MB | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | ```\nclass Solution:\n def smallestValue(self, n):\n\n prev, ans = n, 0\n\n while not n%2: # 2 is the unique even prime\n ans += 2\n n//= 2\n\n for i in range(3,n+1,2): # <\u2013\u2013 prune even divisors...\n while not n%i:\n ans += i\n n//= i\n\n return self.smallestValue(ans) if ans != prev else ans\n```\n[https://leetcode.com/problems/smallest-value-after-replacing-with-sum-of-prime-factors/submissions/861795582/](http://)\n | 3 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Output:** 5
**Explanation:** Initially, n = 15.
15 = 3 \* 5, so replace n with 3 + 5 = 8.
8 = 2 \* 2 \* 2, so replace n with 2 + 2 + 2 = 6.
6 = 2 \* 3, so replace n with 2 + 3 = 5.
5 is the smallest value n will take on.
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** Initially, n = 3.
3 is the smallest value n will take on.
**Constraints:**
* `2 <= n <= 105` | null |
Python3 | Finding prime factors | Intuitive | Easy to understand | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | \n# Code\n```\nclass Solution:\n def prime_factors(self, n):\n i = 2\n factors = []\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n factors.append(i)\n if n > 1:\n factors.append(n)\n return factors\n \n def smallestValue(self, n: int) -> int:\n num = n\n seen = set()\n while num > 0:\n factors = self.prime_factors(num)\n if len(factors) == 1:\n return factors[0]\n num = sum(factors)\n if num in seen:\n break\n seen.add(num)\n return num\n \n \n \n``` | 2 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Output:** 5
**Explanation:** Initially, n = 15.
15 = 3 \* 5, so replace n with 3 + 5 = 8.
8 = 2 \* 2 \* 2, so replace n with 2 + 2 + 2 = 6.
6 = 2 \* 3, so replace n with 2 + 3 = 5.
5 is the smallest value n will take on.
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** Initially, n = 3.
3 is the smallest value n will take on.
**Constraints:**
* `2 <= n <= 105` | null |
SIMPLE PYTHON SOLUTION | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | # Intuition\nMy intuition is that if I encounter any prime number in the process then that is the minimum of till now will be the answer or if we come across same number twice then we will return the minimum value.\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```\nfrom math import sqrt\n\nclass Solution:\n def primeFactors(self,n):\n x=0\n while n % 2 == 0:\n x+=2\n n = n // 2\n\n for i in range(3,int(math.sqrt(n))+1,2):\n while n % i== 0:\n x+=i\n n = n // i\n if n > 2:\n x+=n\n return x\n\n def isPrime(self,n):\n prime_flag = 0\n if(n > 1):\n for i in range(2, int(sqrt(n)) + 1):\n if (n % i == 0):\n prime_flag = 1\n break\n if (prime_flag == 0):\n return True\n else:\n return False\n else:\n return True\n\n def smallestValue(self, n: int) -> int:\n lst=[0]*100001\n mn=n\n \n while True:\n if lst[n]==1:\n return mn\n if self.isPrime(n):\n return min(n,mn)\n lst[n]=1\n n=self.primeFactors(n)\n mn=min(mn,n)\n\n \n``` | 1 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Output:** 5
**Explanation:** Initially, n = 15.
15 = 3 \* 5, so replace n with 3 + 5 = 8.
8 = 2 \* 2 \* 2, so replace n with 2 + 2 + 2 = 6.
6 = 2 \* 3, so replace n with 2 + 3 = 5.
5 is the smallest value n will take on.
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** Initially, n = 3.
3 is the smallest value n will take on.
**Constraints:**
* `2 <= n <= 105` | null |
Easy python solution | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n ---> 61 ms\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n \n# Code\n```\nclass Solution:\n def smallestValue(self, n: int) -> int:\n def pr(n):\n x=[]\n while n % 2 == 0:\n x.append(2)\n n = n / 2\n for i in range(3,int(math.sqrt(n))+1,2):\n while n % i== 0:\n x.append(i)\n n = n / i\n if n > 2:\n x.append(n)\n return sum(x)\n while(n!=pr(n)):\n n=pr(n)\n return int(n) \n \n``` | 1 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Output:** 5
**Explanation:** Initially, n = 15.
15 = 3 \* 5, so replace n with 3 + 5 = 8.
8 = 2 \* 2 \* 2, so replace n with 2 + 2 + 2 = 6.
6 = 2 \* 3, so replace n with 2 + 3 = 5.
5 is the smallest value n will take on.
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** Initially, n = 3.
3 is the smallest value n will take on.
**Constraints:**
* `2 <= n <= 105` | null |
CodeDominar Solution | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | # Code\n```\nclass Solution:\n def smallestValue(self, n: int) -> int:\n def find_factors_sum(n):\n sum_ = 0\n for i in range(2,n):\n while n%i==0:\n sum_+=i\n n = n//i\n return sum_\n while find_factors_sum(n) and n!=find_factors_sum(n):\n n = find_factors_sum(n)\n return n\n \n \n \n``` | 1 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Output:** 5
**Explanation:** Initially, n = 15.
15 = 3 \* 5, so replace n with 3 + 5 = 8.
8 = 2 \* 2 \* 2, so replace n with 2 + 2 + 2 = 6.
6 = 2 \* 3, so replace n with 2 + 3 = 5.
5 is the smallest value n will take on.
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** Initially, n = 3.
3 is the smallest value n will take on.
**Constraints:**
* `2 <= n <= 105` | null |
[Python3] Enumerate all possible cases for 2 and 4 odd-degree nodes in the graph | add-edges-to-make-degrees-of-all-nodes-even | 0 | 1 | **Observation**\nThe key is to note that we can add **at most** two additional edges (possibly none) to the graph.\n\n**Implementation**\nStep 1: Build the graph by going through all edges.\nStep 2: Find every node with an odd degree.\nStep 3: Consider each of the case where the number of the nodes with an odd degree is 0, 1, 2, 3, 4, and > 4.\n\n**Solution**\n```\nclass Solution:\n def isPossible(self, n: int, edges: List[List[int]]) -> bool:\n graph = defaultdict(set)\n for a, b in edges:\n graph[a].add(b)\n graph[b].add(a)\n odds = [a for a in graph if len(graph[a]) % 2 == 1]\n if not odds:\n return True\n elif len(odds) > 4 or len(odds) == 1 or len(odds) == 3:\n return False\n elif len(odds) == 2:\n a, b = odds[0], odds[1]\n if a not in graph[b]:\n return True\n for i in range(1, n + 1):\n if i not in graph[a] and i not in graph[b]:\n return True\n return False\n else:\n a, b, c, d = odds[0], odds[1], odds[2], odds[3]\n if a not in graph[b] and c not in graph[d]:\n return True\n if a not in graph[c] and b not in graph[d]:\n return True\n if a not in graph[d] and b not in graph[c]:\n return True\n return False\n``` | 5 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.
Return `true` _if it is possible to make the degree of each node in the graph even, otherwise return_ `false`_._
The degree of a node is the number of edges connected to it.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2\],\[2,3\],\[3,4\],\[4,2\],\[1,4\],\[2,5\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding an edge.
Every node in the resulting graph is connected to an even number of edges.
**Example 2:**
**Input:** n = 4, edges = \[\[1,2\],\[3,4\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding two edges.
**Example 3:**
**Input:** n = 4, edges = \[\[1,2\],\[1,3\],\[1,4\]\]
**Output:** false
**Explanation:** It is not possible to obtain a valid graph with adding at most 2 edges.
**Constraints:**
* `3 <= n <= 105`
* `2 <= edges.length <= 105`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `ai != bi`
* There are no repeated edges. | null |
[C++|Java|Python3] 3 cases for true | add-edges-to-make-degrees-of-all-nodes-even | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/af6e415cd101768ea8743ea9e4d22d788c9461c3) for solutions of weekly 324. \n\n**Intuition**\nThere are 3 cases where it is possible to get all even degrees with at most two more edges; \n1) The nodes already have all even degrees; \n2) There are two nodes with odd degrees, for which as long it is possible as there is a node not connecting to either of them; \n3) There are four nodes with odd degrees, for which they can be separated into two groups not connecting to each other. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic: \n bool isPossible(int n, vector<vector<int>>& edges) {\n vector<unordered_set<int>> graph(n); \n for (auto& e : edges) {\n graph[e[0]-1].insert(e[1]-1); \n graph[e[1]-1].insert(e[0]-1); \n }\n vector<long> odd; \n for (int i = 0; i < n; ++i) \n if (graph[i].size() & 1) odd.push_back(i); \n return odd.size() == 0 \n || odd.size() == 2 && any_of(graph.begin(), graph.end(), [&](auto& g) { return !g.count(odd[0]) && !g.count(odd[1]); })\n || odd.size() == 4 && (!graph[odd[0]].count(odd[1]) && !graph[odd[2]].count(odd[3]) || !graph[odd[0]].count(odd[2]) && !graph[odd[1]].count(odd[3]) || !graph[odd[0]].count(odd[3]) && !graph[odd[1]].count(odd[2]));\n }\n};\n```\n**Java**\n```\nclass Solution {\n\tpublic boolean isPossible(int n, List<List<Integer>> edges) {\n\t\tHashSet<Integer>[] graph = new HashSet[n]; \n for (int i = 0; i < n; ++i) graph[i] = new HashSet(); \n\t\tfor (var e : edges) {\n graph[e.get(0)-1].add(e.get(1)-1); \n graph[e.get(1)-1].add(e.get(0)-1); \n\t\t}\n\t\tList<Integer> odd = new ArrayList(); \n\t\tfor (int i = 0; i < n; ++i) \n\t\t\tif (graph[i].size() % 2 == 1) odd.add(i); \n\t\tif (odd.size() == 2) {\n\t\t\tfor (int i = 0; i < n; ++i) \n\t\t\t\tif (!graph[i].contains(odd.get(0)) && !graph[i].contains(odd.get(1))) return true; \n\t\t\treturn false; \n\t\t}\n\t\tif (odd.size() == 4) \n\t\t\treturn !graph[odd.get(0)].contains(odd.get(1)) && !graph[odd.get(2)].contains(odd.get(3)) \n || !graph[odd.get(0)].contains(odd.get(2)) && !graph[odd.get(1)].contains(odd.get(3)) \n || !graph[odd.get(0)].contains(odd.get(3)) && !graph[odd.get(1)].contains(odd.get(2)); \n\t\treturn odd.size() == 0; \n\t}\n}\n```\n**Python3**\n```\nclass Solution: \n def isPossible(self, n: int, edges: List[List[int]]) -> bool: \n graph = [set() for _ in range(n)]\n for u, v in edges: \n graph[u-1].add(v-1)\n graph[v-1].add(u-1)\n odd = [i for i, x in enumerate(graph) if len(x)&1]\n return len(odd) == 0 or len(odd) == 2 and any(odd[0] not in graph[x] and odd[1] not in graph[x] for x in range(n)) or len(odd) == 4 and (odd[0] not in graph[odd[1]] and odd[2] not in graph[odd[3]] or odd[0] not in graph[odd[2]] and odd[1] not in graph[odd[3]] or odd[0] not in graph[odd[3]] and odd[1] not in graph[odd[2]])\n```\n**Complexity**\nTime `O(N)`\nSpace `O(N)` | 3 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.
Return `true` _if it is possible to make the degree of each node in the graph even, otherwise return_ `false`_._
The degree of a node is the number of edges connected to it.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2\],\[2,3\],\[3,4\],\[4,2\],\[1,4\],\[2,5\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding an edge.
Every node in the resulting graph is connected to an even number of edges.
**Example 2:**
**Input:** n = 4, edges = \[\[1,2\],\[3,4\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding two edges.
**Example 3:**
**Input:** n = 4, edges = \[\[1,2\],\[1,3\],\[1,4\]\]
**Output:** false
**Explanation:** It is not possible to obtain a valid graph with adding at most 2 edges.
**Constraints:**
* `3 <= n <= 105`
* `2 <= edges.length <= 105`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `ai != bi`
* There are no repeated edges. | null |
Case by case python solution | add-edges-to-make-degrees-of-all-nodes-even | 0 | 1 | # Intuition\nProblem is only solvable if odd nodes are 2 or 4. Note that it is impossible for there to be 1 or 3 odd nodes, since sum(degrees) %2 == 0\n\n# Approach\nWith 2 odds, they can either connect to each other or to some other vertex that neither is connected to\n\nWith 4 odds, there must be two separate pairs of vertices that are unconnected.\n\n# Complexity\n- Time complexity:\nO(n) since the longest loop is making the graph\n\n- Space complexity:\nO(n)\n\n# Code\n(note: was updated from previous incorrect solution)\n```\nclass Solution:\n def isPossible(self, n: int, edges: List[List[int]]) -> bool:\n neighbors = [set() for _ in range(n)]\n for edge in edges:\n a, b = edge\n a -=1\n b -=1\n neighbors[a].add(b)\n neighbors[b].add(a)\n oddDegreesNodes = [i for i in range(n) if (len(neighbors[i]) % 2 == 1)]\n numOdd = len(oddDegreesNodes)\n if numOdd == 0:\n return True\n elif numOdd == 4:\n # Only possible if there are two pairs of vertices which are not connected\n o1, o2, o3, o4 = oddDegreesNodes\n return (o1 not in neighbors[o2] and o3 not in neighbors[o4]) or (o1 not in neighbors[o3] and o2 not in neighbors[o4]) or (o1 not in neighbors[o4] and o2 not in neighbors[o3])\n elif numOdd == 2:\n # Only possible if both not connected or both connected but there is another node to connect to\n o1, o2 = oddDegreesNodes\n if o1 not in neighbors[o2]:\n # Case 1: Not connected\n return True\n # Case 2\n bothConnectedTo = neighbors[o1] | neighbors[o2]\n # Oops, no other node to connect to!\n return len(bothConnectedTo) != n\n return False\n``` | 1 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.
Return `true` _if it is possible to make the degree of each node in the graph even, otherwise return_ `false`_._
The degree of a node is the number of edges connected to it.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2\],\[2,3\],\[3,4\],\[4,2\],\[1,4\],\[2,5\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding an edge.
Every node in the resulting graph is connected to an even number of edges.
**Example 2:**
**Input:** n = 4, edges = \[\[1,2\],\[3,4\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding two edges.
**Example 3:**
**Input:** n = 4, edges = \[\[1,2\],\[1,3\],\[1,4\]\]
**Output:** false
**Explanation:** It is not possible to obtain a valid graph with adding at most 2 edges.
**Constraints:**
* `3 <= n <= 105`
* `2 <= edges.length <= 105`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `ai != bi`
* There are no repeated edges. | null |
HRT CodeSignal test problem | add-edges-to-make-degrees-of-all-nodes-even | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI actually encountered this problem on HRT online OA\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThere are only 3 cases to return true:\n1. All nodes are even\n2. 2 nodes are odd, find a free node or between themselves and link them up\n3. 4 nodes are odd, Link the 4 of them up\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(V+E)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(E)\n# Code\n```\nclass Solution:\n def isPossible(self, n: int, edges: List[List[int]]) -> bool:\n graph = [set() for i in range(n)]\n for a, b in edges:\n graph[a-1].add(b-1)\n graph[b-1].add(a-1)\n \n odd = 0\n oddVertices = []\n for i in range(n):\n if len(graph[i]) % 2 == 1:\n odd += 1\n oddVertices.append(i)\n if odd == 0:\n return True\n elif odd == 2:\n a, b = oddVertices\n for i in range(n):\n if i not in graph[a] and i not in graph[b]:\n return True\n elif odd == 4:\n a, b, c, d = oddVertices\n if (b not in graph[a] and d not in graph[c]) or (c not in graph[a] and d not in graph[b]) or (d not in graph[a] and c not in graph[b]):\n return True\n return False\n \n \n``` | 1 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.
Return `true` _if it is possible to make the degree of each node in the graph even, otherwise return_ `false`_._
The degree of a node is the number of edges connected to it.
**Example 1:**
**Input:** n = 5, edges = \[\[1,2\],\[2,3\],\[3,4\],\[4,2\],\[1,4\],\[2,5\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding an edge.
Every node in the resulting graph is connected to an even number of edges.
**Example 2:**
**Input:** n = 4, edges = \[\[1,2\],\[3,4\]\]
**Output:** true
**Explanation:** The above diagram shows a valid way of adding two edges.
**Example 3:**
**Input:** n = 4, edges = \[\[1,2\],\[1,3\],\[1,4\]\]
**Output:** false
**Explanation:** It is not possible to obtain a valid graph with adding at most 2 edges.
**Constraints:**
* `3 <= n <= 105`
* `2 <= edges.length <= 105`
* `edges[i].length == 2`
* `1 <= ai, bi <= n`
* `ai != bi`
* There are no repeated edges. | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.