title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Number of Laser Beams in a Bank
number-of-laser-beams-in-a-bank
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank.
Array,Math,String,Matrix
Medium
What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input to such an array, skip any row with no security device, then find the sum of the product between adjacent elements.
5,743
66
**Explanation**:\nTo find the total number of `laser beams` we have to do 2 things:\n1. Find the `number of laser beams` between \'adjacent rows\'. A row here is considered only if it has atleast 1 `security device`. Otherwise the row is simply ignored. \nThus if: \nRow `1`: 3 security devices \nRow `2`: 0 security devices \nRow `3`: 2 security devices\nWe can ignore row `2` and say that row `1` is adjacent to row `3`. To find the `number of laser beams` between \'adjacent rows\' we can multiply the number of security devices in the first row of the pair to the number of security devices in the second row of the pair.\n2. Doing step 1 only solves a part of the problem. We now need to find the sum of all the `laser beams` from each pair of \'adjacent rows\'.\n\n**Algorithm**:\nFor each string in bank:\n* `count` = number of ones in string\n* Multiply `count` by the non-zero `count` of previous string and add it to `ans`\n<iframe src="" frameBorder="0" width="500" height="275"></iframe>\n\nTime Complexity: `O(mn)`, `m` = length of bank, `n` = length of string
105,719
Number of Laser Beams in a Bank
number-of-laser-beams-in-a-bank
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank.
Array,Math,String,Matrix
Medium
What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input to such an array, skip any row with no security device, then find the sum of the product between adjacent elements.
1,046
15
**PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n* First count the number of `1` in each layer as N<sub>i<sub>\n* skip or remove the layers which do not contain `1`\n* So the number of connections between any two adjacent layers is N<sub>i</sub> * N<sub>i-1</sub>\n\t* return the sum of N<sub>i</sub> * N<sub>i-1</sub>\n\n![image]()\n\n```\nTime Complexity: O(MN)\nSpace Complexity: O(1)\n```\n\n**C++**\n```\nclass Solution {\npublic:\n int numberOfBeams(vector<string>& bank) {\n int ans = 0, pre = 0;\n for (int i = 0;i < bank.size(); i ++) {\n int n = count(bank[i].begin(), bank[i].end(), \'1\');\n if (n == 0) continue;\n ans += pre * n;;\n pre = n;\n }\n return ans;\n }\n};\n```\n**Python**\n```\nclass Solution(object):\n def numberOfBeams(self, bank):\n ans, pre = 0, 0\n for s in bank:\n n = s.count(\'1\')\n if n == 0: continue\n ans += pre * n\n pre = n\n return ans\n```\n**Java**\n```\nclass Solution {\n public int numberOfBeams(String[] bank) {\n int ans = 0, pre = 0;\n for (int i = 0;i < bank.length; i ++) {\n int n = 0;\n for (int j = 0; j < bank[i].length(); j ++) if(bank[i].charAt(j) == \'1\') n ++;\n if (n == 0) continue;\n ans += pre * n;;\n pre = n;\n }\n return ans;\n }\n}\n```\n\n**PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.**
105,739
Number of Laser Beams in a Bank
number-of-laser-beams-in-a-bank
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank.
Array,Math,String,Matrix
Medium
What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input to such an array, skip any row with no security device, then find the sum of the product between adjacent elements.
635
7
Please check out this [commit]() for solutions of weekly 274. \n\n```\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n ans = prev = 0 \n for row in bank: \n curr = row.count(\'1\')\n if curr: \n ans += prev * curr\n prev = curr \n return ans \n```
105,743
Number of Laser Beams in a Bank
number-of-laser-beams-in-a-bank
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank.
Array,Math,String,Matrix
Medium
What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input to such an array, skip any row with no security device, then find the sum of the product between adjacent elements.
575
5
**Q & A**\n\nQ1: How we got to know that we are required to do product of adjacent rows with count of 1s? \nA1: According to the problem:\nThere is one laser beam between any two security devices if both conditions are met:\n\n1. The two devices are located on two different rows: r1 and r2, where r1 < r2.\n2. For each row i where r1 < i < r2, there are no security devices in the ith row.\n\n**End of Q & A**\n\n----\n\nGet rid of empty rows and then sum the product of each pair of neighbors.\n```java\n public int numberOfBeams(String[] bank) {\n int cnt = 0, prev = 0;\n for (String devs : bank) {\n // devs.chars() cost more than O(1) space. - credit to @bharathkalyans.\n // int cur = devs.chars().map(i -> i == \'1\' ? 1 : 0).sum();\n int cur = 0;\n for (int i = 0; i < devs.length(); ++i) {\n cur += devs.charAt(i) == \'1\' ? 1 : 0;\n }\n cnt += prev * cur;\n if (cur > 0) {\n prev = cur;\n }\n }\n return cnt;\n }\n```\n```python\n def numberOfBeams(self, bank: List[str]) -> int:\n cnt = prev = 0\n for devs in bank:\n cur = devs.count(\'1\')\n cnt += cur * prev\n if cur > 0:\n prev = cur\n return cnt\n```\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`, where `n` is the **total** number of characters in `bank`.
105,744
Number of Laser Beams in a Bank
number-of-laser-beams-in-a-bank
Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank.
Array,Math,String,Matrix
Medium
What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input to such an array, skip any row with no security device, then find the sum of the product between adjacent elements.
527
9
Runtime: **87 ms, faster than 94.93%** of Python3 online submissions for Number of Laser Beams in a Bank.\nMemory Usage: **15.9 MB, less than 99.13%** of Python3 online submissions for Number of Laser Beams in a Bank.\n\n```\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n a, s = [x.count("1") for x in bank if x.count("1")], 0\n\n\t\t# ex: bank is [[00101], [01001], [00000], [11011]]\n\t\t# a would return [2, 2, 4]\n\n for c in range(len(a)-1):\n s += (a[c]*a[c+1])\n\n\t\t\t# basic math to find the total amount of lasers\n\t\t\t# for the first iteration: s += 2*2\n\t\t\t# for the second iteration: s += 2*4\n\t\t\t# returns s = 12\n\n return s\n \n
105,745
Destroying Asteroids
destroying-asteroids
You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid. You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed. Return true if all asteroids can be destroyed. Otherwise, return false.
Array,Greedy,Sorting
Medium
Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the asteroids in non-decreasing order by mass, then greedily try to collide with the asteroids in that order.
3,742
23
```java\n public boolean asteroidsDestroyed(int mass, int[] asteroids) {\n long m = mass;\n Arrays.sort(asteroids);\n for (int ast : asteroids) {\n if (m < ast) {\n return false;\n }\n m += ast;\n }\n return true;\n }\n```\nIn case you do NOT like using `long`, we can use the constraints: `1 <= asteroids[i] <= 10^5`: once mass is greater than all asteroids, we can conclude all can be destroyed.\u3000-- inspired by **@Zudas**.\n\n```java\n public boolean asteroidsDestroyed(int mass, int[] asteroids) {\n Arrays.sort(asteroids);\n for (int ast : asteroids) {\n if (mass < ast) {\n return false;\n }else if (mass > 100_000) { // now we can conclude all can be destroyed.\n return true;\n }\n mass += ast;\n }\n return true;\n }\n```\n```python\n def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n for a in sorted(asteroids):\n if mass < a:\n return False\n mass += a\n return True\n```\n**Analysis:**\n\nTime: `O(n * log(n))`, space: `O(n)` - including sorting space.
105,764
Maximum Employees to Be Invited to a Meeting
maximum-employees-to-be-invited-to-a-meeting
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.
Depth-First Search,Graph,Topological Sort
Hard
From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by selecting a cycle of the graph. It can be proven that in this case, the employees that do not lie in the cycle can never be seated at the table. The second way is by combining acyclic chains. At most two chains can be combined by a cycle of length 2, where each chain ends on one of the employees in the cycle.
1,489
16
**PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.** \n* We first construct a directed graph, the vertices are employees, if a favorite b then a directed edge points from a to b\n* Through union find set, we divide the graph into several disconnected islands. It can be proved that each island has one and only one cycle. Moreover since there is one and only one cycle on every island, we can also find out the cycle directly without UnionFind, and the nodes connected to eacy cycle forms an island.\n\t* If the circle is greater than 2, employees in this circle can only sit at a table alone.\n\t* If the circle is equal to 2, the two employees in the circle favor each other, and a favorite chain can be gathered on their left and right sides to form a free sequence.\n\t\t* Note that all free sequences can be concated and sit at a table together.\n\t\n![image]()\n* Now I explain the detail step by step with the help of the examples in the figure.\n\t* we can easily find out that there are 3 islands in the graph via union find set and denoted by A B C respectively.\n\t* for each island we find out the only cycle on it, for example A has the cycle (A1, A2, A3, A4) and B has the cycle (B1, B2). since there is one and only one cycle on every island, we can also find out the cycle directly without UnionFind. \n\t* If we invite anyone in (A1, A2, A3, A4), we must invite them all and we cannot invite any other one on or not on island A. Actually employees on island A but not belong to the cycle cannot be invited forever.\n\t* However on island B, it is much more different. (B1, B2) is the cycle and they faver eacy other, and B3 who favors B1 can sit on the other side of B2 without conflict. (B3, B1, B2) form a free sequence.\n\t* The situation on Island C is similar to Island B. After selecting C1 and C2 on the circle, we can further invite the longest favorite chain on both sides of them to form the longest free sequence on the island together with C1 and C2, that is (C3, C4, C6, C7, C1, C2, C11, C12)\n\t* Finally we concat all the free sequences because they can sit together without confilit. that is (B3, B1, B2, C3, C4, C6, C7, C1, C2, C11, C12)\n\t* The answer is the maximum of the longest single cycle and the concated free sequences.\n\t\t* the longest single cycle\n\t\t\t* (A1, A2, A3, A4)\n\t\t* the concated free sequences\n\t\t\t* (B3, B1, B2, C3, C4, C6, C7, C1, C2, C11, C12)\n\n```\nTime Complexity: O(N) for each node would be visited only once, we use a set named seen to avoid repeat.\nSpace Complexity: O(N)\n```\n\n**Python Without Union Find**\n```\nclass Solution(object):\n def maximumInvitations(self, favorite):\n pre = collections.defaultdict(list)\n for i, j in enumerate(favorite):\n pre[j].append(i)\n\n seen, max_cycle_length, sequence_length = set(), 0, 0\n\n for node in range(len(favorite)): # for each island, there is one and only one cycle\n # find the cycle and its length\n if node in seen: continue\n path = [node]\n while favorite[path[-1]] not in seen:\n seen.add(favorite[path[-1]])\n path.append(favorite[path[-1]])\n if favorite[path[-1]] not in path: continue\n cycle_length = len(path) - path.index(favorite[path[-1]])\n\n if cycle_length == 2: # cycle can concat with other sequential nodes on the island at both left and right\n # via dfs or bfs through pre, we can find out the longest sequence left and right of the cycle\n # finally we concat the left longest sequence and the cycle itself and the right longest sequence as\n # the longest valid sequence of the island.\n max_sub_len = [0, 0]\n cycle = path[-2:]\n pre[cycle[0]].remove(cycle[1])\n pre[cycle[1]].remove(cycle[0])\n for k in [0, 1]: # the left and right of the cycle as the start point of dfs respectively\n dq = collections.deque([(cycle[k], 0)])\n while dq:\n i, depth = dq.pop() # DFS\n # i, depth = dq.popleft() # BFS\n if i in pre:\n for j in pre[i]:\n dq.append((j, depth + 1))\n seen.add(j)\n else:\n max_sub_len[k] = max(max_sub_len[k], depth) # get the length of longest sequence\n # 2 is the length of cycle, max_sub_len are lengths of longest sequence of both left and right ends\n sequence_length += 2 + sum(max_sub_len)\n else: # greater than 2, the cycle can\'t concat with any other node\n max_cycle_length = max(max_cycle_length, cycle_length)\n\n # either a big cycle or some free sequences will be the final answer\n return max(max_cycle_length, sequence_length)\n```\n\n**Python With Union Find**\n```\nclass UnionFind(object): # standard union find set class\n def __init__(self, n):\n self.parent = range(n)\n self.level = [0] * n\n\n def find(self, i):\n while self.parent[i] != i:\n i = self.parent[i]\n return i\n\n def union(self, i, j):\n i = self.find(i)\n j = self.find(j)\n if self.level[i] < self.level[j]:\n self.parent[i] = j\n elif self.level[j] < self.level[i]:\n self.parent[j] = i\n else:\n self.parent[j] = i\n self.level[i] += 1\n\n\nclass Solution(object):\n def maximumInvitations(self, favorite):\n pre = collections.defaultdict(list)\n uf = UnionFind(len(favorite))\n for i, j in enumerate(favorite):\n uf.union(i, j)\n pre[j].append(i)\n islands = collections.defaultdict(list)\n for i in range(len(favorite)):\n islands[uf.find(i)].append(i)\n\n max_cycle_length = 0\n sequence_length = 0\n\n for nodes in islands.values(): # for each island, there is one and only one cycle\n # find the cycle and its length\n path = [nodes[0]]\n path_set = set([nodes[0]])\n while favorite[path[-1]] not in path_set:\n path_set.add(favorite[path[-1]])\n path.append(favorite[path[-1]])\n cycle_length = len(path) - path.index(favorite[path[-1]])\n\n if cycle_length == 2: # cycle can concat with other sequential nodes on the island at both left and right\n # via dfs or bfs through pre, we can find out the longest sequence left and right of the cycle\n # finally we concat the left longest sequence and the cycle itself and the right longest sequence as\n # the longest valid sequence of the island.\n max_sub_len = [0, 0]\n cycle = path[-2:]\n pre[cycle[0]].remove(cycle[1])\n pre[cycle[1]].remove(cycle[0])\n for k in [0, 1]: # the left and right of the cycle as the start point of dfs respectively\n dq = collections.deque([(cycle[k], 0)])\n while dq:\n i, depth = dq.pop() # DFS\n # i, depth = dq.popleft() # BFS\n if i in pre:\n for j in pre[i]:\n dq.append((j, depth + 1))\n else:\n max_sub_len[k] = max(max_sub_len[k], depth) # get the length of longest sequence\n # 2 is the length of cycle, max_sub_len are lengths of longest sequence of both left and right ends\n sequence_length += 2 + sum(max_sub_len)\n else: # greater than 2, the cycle can\'t concat with any other node\n max_cycle_length = max(max_cycle_length, cycle_length)\n\n # either a big cycle or some free sequences will be the final answer\n return max(max_cycle_length, sequence_length)\n```\n**PLEASE UPVOTE if you like** \uD83D\uDE01 **If you have any question, feel free to ask.**
105,821
Maximum Employees to Be Invited to a Meeting
maximum-employees-to-be-invited-to-a-meeting
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.
Depth-First Search,Graph,Topological Sort
Hard
From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by selecting a cycle of the graph. It can be proven that in this case, the employees that do not lie in the cycle can never be seated at the table. The second way is by combining acyclic chains. At most two chains can be combined by a cycle of length 2, where each chain ends on one of the employees in the cycle.
1,699
7
This problem can be separated to two problems.\nProblem 1 : Get maximum length of cycle of the graph.\nProblem 2 : Make back edge graph. Get sum of max depth of the trees which the root node is the node that i == favorite[favorite[i]]. \nFinal answer is max value of problem1\'s answer and problem2\'s answer.\n\nc++ code :\n```c++\nclass Solution {\npublic:\n int maximumInvitations(vector<int>& A) {\n int ret = 0, n = A.size();\n vector<vector<int>> bg(n);\n for(auto i = 0; i < n; ++i) bg[A[i]].push_back(i);\n vector<bool> visited(n), inpath(n);\n vector<int> time(n);\n auto ct = 1;\n function<void(int)> dfs = [&](auto cur) {\n visited[cur] = inpath[cur] = true, time[cur] = ct++;\n auto nxt = A[cur];\n if(!visited[nxt]) dfs(nxt);\n if(inpath[nxt]) ret = max(ret, time[cur] - time[nxt] + 1);\n inpath[cur] = false;\n };\n for(auto i = 0; i < n; ++i) if(!visited[i]) dfs(i);\n function<int(int)> dfs2 = [&](auto cur) {\n int ret = 1;\n for(auto nxt : bg[cur]) if(nxt != A[cur]) ret = max(ret, dfs2(nxt) + 1);\n return ret;\n };\n int ret2 = 0;\n for(auto i = 0; i < n; ++i) if(i == A[A[i]] && i < A[i]) ret2 += dfs2(i) + dfs2(A[i]);\n return max(ret, ret2);\n }\n};\n```\n\npython code :\n```python\nclass Solution:\n def maximumInvitations(self, favorite: List[int]) -> int:\n n = len(favorite)\n visited_time = [0] * n\n inpath = [False] * n\n cur_time = 1\n def get_max_len_cycle(cur) :\n nonlocal cur_time\n inpath[cur], visited_time[cur], nxt = True, cur_time, favorite[cur]\n cur_time += 1\n ret = 0 if not inpath[nxt] else visited_time[cur] - visited_time[nxt] + 1\n if visited_time[nxt] == 0 : ret = max(ret, get_max_len_cycle(nxt))\n inpath[cur] = False\n return ret\n \n ret_cycle = 0\n for i in range(n) :\n if visited_time[i] == 0 :\n ret_cycle = max(ret_cycle, get_max_len_cycle(i))\n \n ret_not_cycle = 0\n back_edge_graph = [[] for _ in range(n)]\n for i in range(n) : back_edge_graph[favorite[i]].append(i)\n def get_max_depth(cur) :\n ret = 0\n for nxt in back_edge_graph[cur] :\n if favorite[cur] != nxt :\n ret = max(ret, get_max_depth(nxt) + 1)\n return ret\n \n for i in range(n) :\n if favorite[favorite[i]] == i : ret_not_cycle += get_max_depth(i) + 1\n \n ret = max(ret_cycle, ret_not_cycle)\n return ret\n```
105,825
Maximum Employees to Be Invited to a Meeting
maximum-employees-to-be-invited-to-a-meeting
A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.
Depth-First Search,Graph,Topological Sort
Hard
From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by selecting a cycle of the graph. It can be proven that in this case, the employees that do not lie in the cycle can never be seated at the table. The second way is by combining acyclic chains. At most two chains can be combined by a cycle of length 2, where each chain ends on one of the employees in the cycle.
1,668
5
Please check out this [commit]() for solutions of weekly 274. \n\n```\nclass Solution:\n def maximumInvitations(self, favorite: List[int]) -> int:\n n = len(favorite)\n graph = [[] for _ in range(n)]\n for i, x in enumerate(favorite): graph[x].append(i)\n \n def bfs(x, seen): \n """Return longest arm of x."""\n ans = 0 \n queue = deque([x])\n while queue: \n for _ in range(len(queue)): \n u = queue.popleft()\n for v in graph[u]: \n if v not in seen: \n seen.add(v)\n queue.append(v)\n ans += 1\n return ans \n \n ans = 0 \n seen = [False]*n\n for i, x in enumerate(favorite): \n if favorite[x] == i and not seen[i]: \n seen[i] = seen[x] = True \n ans += bfs(i, {i, x}) + bfs(x, {i, x})\n \n dp = [0]*n\n for i, x in enumerate(favorite): \n if dp[i] == 0: \n ii, val = i, 0\n memo = {}\n while ii not in memo: \n if dp[ii]: \n cycle = dp[ii]\n break\n memo[ii] = val\n val += 1\n ii = favorite[ii]\n else: cycle = val - memo[ii]\n for k in memo: dp[k] = cycle\n return max(ans, max(dp))\n```
105,831
Minimum Cost of Buying Candies With Discount
minimum-cost-of-buying-candies-with-discount
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.
Array,Greedy,Sorting
Easy
If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost?
41
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumCost(self, cost: List[int]) -> int:\n sum=0\n cost.sort(reverse=True)\n print(cost)\n for i in range(len(cost)):\n if (i+1)%3==0 and i!=0:\n pass\n else:\n sum=sum+cost[i]\n return sum\n\n```
105,859
Minimum Cost of Buying Candies With Discount
minimum-cost-of-buying-candies-with-discount
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.
Array,Greedy,Sorting
Easy
If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost?
477
6
# Code\u2705\n```\nclass Solution:\n def minimumCost(self, cost: List[int]) -> int:\n cost = sorted(cost,reverse=True)\n i =0 \n output = 0\n while i<len(cost):\n output += cost[i] if i == len(cost)-1 else cost[i] + cost[i+1]\n i +=3\n return output\n\n\n```\n![Screen Shot 2023-02-07 at 4.21.14 PM.png]()\n
105,868
Minimum Cost of Buying Candies With Discount
minimum-cost-of-buying-candies-with-discount
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.
Array,Greedy,Sorting
Easy
If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost?
5,708
89
# **Explanation**\nFor the max value, we have to pay for it.\nFor the second max value, we still have to pay for it.\nFor the third max value, we can get it free one as bonus.\nAnd continuely do this for the rest.\n\nThe the core of problem, is need to sort the input.\nAll `A[i]` with `i % 3 == n % 3`, we can get it for free.\n<br>\n\n# **Complexity**\nTime `O(sort)`\nSpace `O(sort)`\n<br>\n\n**Java**\n```java\n public int minimumCost(int[] A) {\n Arrays.sort(A);\n int res = 0, n = A.length;\n for (int i = 0; i < n; ++i)\n if (i % 3 != n % 3)\n res += A[i];\n return res;\n }\n```\n\n**C++**\n```cpp\n int minimumCost(vector<int>& A) {\n sort(A.begin(), A.end());\n int res = 0, n = A.size();\n for (int i = 0; i < A.size(); ++i)\n if (i % 3 != n % 3)\n res += A[i];\n return res;\n }\n```\n\n**Python**\n```py\n def minimumCost(self, A):\n return sum(a for i,a in enumerate(sorted(A)) if (len(A) - i) % 3)\n```\n```\n def minimumCost(self, A):\n return sum(A) - sum(sorted(A)[-3::-3])\n```\n
105,870
Minimum Cost of Buying Candies With Discount
minimum-cost-of-buying-candies-with-discount
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.
Array,Greedy,Sorting
Easy
If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost?
1,279
17
Sort cost descending, and then sum, skipping every third cost.\n\n**Python 3**\n```python\nclass Solution:\n minimumCost = lambda self, cost: sum(c for i, c in enumerate(sorted(cost, reverse=True)) if i % 3 != 2)\n```\n\n**C++**\nSame logic in C++.\n```cpp\nint minimumCost(vector<int>& cost) {\n int res = 0;\n sort(rbegin(cost), rend(cost));\n for (int i = 0; i < cost.size(); ++i)\n res += i % 3 == 2 ? 0 : cost[i];\n return res;\n}\n```
105,880
Minimum Cost of Buying Candies With Discount
minimum-cost-of-buying-candies-with-discount
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.
Array,Greedy,Sorting
Easy
If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost?
547
6
Your goal is: skip the costly items as many as possible.\n\nTo do so, you choose the two largest items in the list, and then skip the next largest item. Repeat this process greedily.\n\nAlgorithm is to sort the item in an descending order, and take the first 2 items and move the index by 3, and repeat this until you reach the end.\n\nTime complexity: sort dominates and O(NlogN)\nSpace complexity: O(1)\n\n```\nclass Solution:\n def minimumCost(self, cost: List[int]) -> int:\n cost.sort(reverse=True)\n res, idx, N = 0, 0, len(cost)\n while idx < N:\n res += sum(cost[idx : idx + 2])\n idx += 3\n return res\n```
105,884
Minimum Cost of Buying Candies With Discount
minimum-cost-of-buying-candies-with-discount
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.
Array,Greedy,Sorting
Easy
If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost?
908
10
Understanding:\nReverse sort the array of costs. Now the first two will be highest costs which can help us get the third one for free and so on. \n\nAlgorithm:\n- Reverse sort the array\n- Initialize index i at 0, resultant cost as 0 and N as length of array cost\n- Add the cost of 2 candies to result, i.e., the cost at index and the next one\n- Increment index by 3, continue this step and above one till index reaches length of array\n- Return the result\n\nPython code :\n```\nclass Solution:\n def minimumCost(self, cost: List[int]) -> int:\n cost.sort(reverse=True)\n res, i, N = 0, 0, len(cost)\n while i < N:\n res += sum(cost[i : i + 2])\n i += 3\n return res\n```
105,894
Minimum Cost of Buying Candies With Discount
minimum-cost-of-buying-candies-with-discount
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.
Array,Greedy,Sorting
Easy
If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost?
354
5
Please pull this [commit]() for solutions of biweekly 70. \n\n**Intuition**\nSort the candies in descending order and group them by every 3 candies. Among each group, add the cost of largest 2 to the final answer. \n\n```\nclass Solution:\n def minimumCost(self, cost: List[int]) -> int:\n return sum(x for i, x in enumerate(sorted(cost, reverse=True)) if (i+1)%3)\n```\n\n**AofA**\ntime complexity `O(NlogN)` \nspace complexity `O(N)`
105,906
Count the Hidden Sequences
count-the-hidden-sequences
You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0.
Array,Prefix Sum
Medium
Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the value of x does not affect this. We now have the ‘range’ of the sequence (difference between min and max element), we can then calculate how many ways there are to fit this range into the given range of lower to upper. Answer is (upper - lower + 1) - (range of sequence)
6,504
113
# **Explanation**\nAssume we start with `a = 0`,\ncontinuously calculate the next value by `difference`.\nWe only need to record the current value `a`, the `max` and the `min` value in this sequence.\n\nNow we need to put the sequence with range `[min, max]` into a range of `[lower, upper]`.\n\nIf `upper - lower < max - min`, no possible hidden sequences.\nIf `upper - lower == max - min`, we have only 1 possible hidden sequences.\nIf `upper - lower == max - min + 1`, we have 2 possible hidden sequences.\nIf `upper - lower == max - min + k`, we have k + 1 possible hidden sequences.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int numberOfArrays(int[] diff, int lower, int upper) {\n long a = 0, ma = 0, mi = 0;\n for (int d: diff) {\n a += d;\n ma = Math.max(ma, a);\n mi = Math.min(mi, a);\n }\n return (int)Math.max(0, (upper - lower) - (ma - mi) + 1);\n }\n```\n\n**C++**\n```cpp\n int numberOfArrays(vector<int>& diff, int lower, int upper) {\n long a = 0, ma = 0, mi = 0;\n for (int d: diff) {\n a += d;\n ma = max(ma, a);\n mi = min(mi, a);\n }\n return max(0L, (upper - lower) - (ma - mi) + 1);\n }\n```\n\n**Python3**\n```py\n def numberOfArrays(self, diff, lower, upper):\n A = list(accumulate(diff, initial = 0))\n return max(0, (upper - lower) - (max(A) - min(A)) + 1)\n```\n
105,910
Count the Hidden Sequences
count-the-hidden-sequences
You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0.
Array,Prefix Sum
Medium
Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the value of x does not affect this. We now have the ‘range’ of the sequence (difference between min and max element), we can then calculate how many ways there are to fit this range into the given range of lower to upper. Answer is (upper - lower + 1) - (range of sequence)
516
5
Assuming that the starting point is zero, we determine the range of the hidden sequence ([left, right]).\n\nIf this range is smaller than [lower, upper] - we can form a valid sequence. The difference between those two ranges tells us how many valid sequences we can form: `upper - lower - (right - left) + 1`.\n\n**Python 3**\n```python\nclass Solution:\n def numberOfArrays(self, diff: List[int], lower: int, upper: int) -> int:\n diff = list(accumulate(diff, initial = 0))\n return max(0, upper - lower - (max(diff) - min(diff)) + 1)\n```\n**C++**\n```cpp\nint numberOfArrays(vector<int>& diff, int lower, int upper) {\n long long left = 0, right = 0, cur = 0;\n for (int d : diff) {\n cur += d;\n left = min(left, cur);\n right = max(right, cur);\n }\n return max(0LL, upper - lower - (right - left) + 1);\n}\n```
105,919
Count the Hidden Sequences
count-the-hidden-sequences
You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i]. You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain. Return the number of possible hidden sequences there are. If there are no possible sequences, return 0.
Array,Prefix Sum
Medium
Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the value of x does not affect this. We now have the ‘range’ of the sequence (difference between min and max element), we can then calculate how many ways there are to fit this range into the given range of lower to upper. Answer is (upper - lower + 1) - (range of sequence)
497
7
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe idea is to calculate constraints for every element of the hidden sequence starting from the beginning. The last constraint will be equal to the range that the last element of the sequence can take. Considering that the value of elements in the sequence depends on each other, the number of values that the last element can take is equal to the number of possible sequences, i.e. this is our answer. \n\nExample: `differences = [1,-3,4], lower = 1, upper = 6`. Let the hidden sequence be `[a, b, c, d]`. Thus:\n```\nb - a = 1\nc - b = -3\nd - c = 4\n```\nLet\'s isolate every element:\n```\na = b - 1\nb = c + 3\nc = d - 4\n```\nCalculate constraints for every element:\n```\nlower <= a <= upper\n\nlower <= b - 1 <= upper\nlower + 1 <= b <= upper + 1\n\nlower + 1 <= c + 3 <= upper + 1\nlower + 1 - 3 <= c <= upper + 1 - 3\n\nlower + 1 - 3 <= d - 4 <= upper + 1 - 3\nlower + 1 - 3 + 4 <= d <= upper + 1 - 3 + 4\n```\nOn every step, we clip the resulting boundaries to the range `lower .. upper`, and also check if we got out of the range and return 0.\n\nTime: **O(n)** - linear\nSpace: **O(1)** - nothing stored \n\nRuntime: 1288 ms, faster than **89.22%** of Python3 online submissions for Count the Hidden Sequences.\nMemory Usage: 28.5 MB, less than **95.81%** of Python3 online submissions for Count the Hidden Sequences.\n\n```\ndef numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:\n\tlo, up = lower, upper\n\tfor diff in differences:\n\t\tlo, up = max(lower, lo + diff), min(upper, up + diff)\n\t\tif lo > upper or up < lower: return 0\n\n\treturn up - lo + 1\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
105,941
K Highest Ranked Items Within a Price Range
k-highest-ranked-items-within-a-price-range
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k. You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.
Array,Breadth-First Search,Sorting,Heap (Priority Queue),Matrix
Medium
Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as the answer.
2,210
16
**Q & A**\n\nQ1: Why do you have `ans.size() < k` in the `while` condition?\nA1: The `PriorityQueue/heap` is sorted according to the rank specified in the problem. Therefore, the `ans` always holds highest ranked items within the given price range, and once it reaches the size of `k`, the loop does NOT need to iterate any more.\n\n**End of Q & A**\n\n----\n\nUse a `PriorityQueue/heap` to store (distance, price, row, col) and a HashSet to prune duplicates.\n```java\n private static final int[] d = {0, 1, 0, -1, 0};\n public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {\n int R = grid.length, C = grid[0].length;\n int x = start[0], y = start[1], low = pricing[0], high = pricing[1];\n Set<String> seen = new HashSet<>(); // Set used to prune duplicates.\n seen.add(x + "," + y);\n List<List<Integer>> ans = new ArrayList<>();\n // PriorityQueue sorted by (distance, price, row, col).\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] == b[1] ? a[2] == b[2] ? a[3] - b[3] : a[2] - b[2] : a[1] - b[1] : a[0] - b[0]);\n pq.offer(new int[]{0, grid[x][y], x, y}); // BFS starting point.\n while (!pq.isEmpty() && ans.size() < k) {\n int[] cur = pq.poll();\n int distance = cur[0], price = cur[1], r = cur[2], c = cur[3]; // distance, price, row & column.\n if (low <= price && price <= high) { // price in range?\n ans.add(Arrays.asList(r, c));\n }\n for (int m = 0; m < 4; ++m) { // traverse 4 neighbors.\n int i = r + d[m], j = c + d[m + 1];\n // in boundary, not wall, and not visited yet?\n if (0 <= i && i < R && 0 <= j && j < C && grid[i][j] > 0 && seen.add(i + "," + j)) {\n pq.offer(new int[]{distance + 1, grid[i][j], i, j});\n }\n }\n }\n return ans;\n }\n```\n```python\n def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:\n R, C = map(len, (grid, grid[0]))\n ans, (x, y), (low, high) = [], start, pricing\n heap = [(0, grid[x][y], x, y)]\n seen = {(x, y)}\n while heap and len(ans) < k:\n distance, price, r, c = heapq.heappop(heap)\n if low <= price <= high:\n ans.append([r, c])\n for i, j in (r, c + 1), (r, c - 1), (r + 1, c), (r - 1, c):\n if R > i >= 0 <= j < C and grid[i][j] > 0 and (i, j) not in seen: \n seen.add((i, j))\n heapq.heappush(heap, (distance + 1, grid[i][j], i, j))\n return ans\n```\n\nIn case you prefer negating the `grid` values to using HashSet, please refer to the following codes.\nOf course, the input is modified.\n\n```java\n private static final int[] d = {0, 1, 0, -1, 0};\n public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {\n int R = grid.length, C = grid[0].length;\n int x = start[0], y = start[1], low = pricing[0], high = pricing[1];\n List<List<Integer>> ans = new ArrayList<>();\n // PriorityQueue sorted by (distance, price, row, col).\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] == b[1] ? a[2] == b[2] ? a[3] - b[3] : a[2] - b[2] : a[1] - b[1] : a[0] - b[0]);\n pq.offer(new int[]{0, grid[x][y], x, y}); // BFS starting point.\n grid[x][y] *= -1;\n while (!pq.isEmpty() && ans.size() < k) {\n int[] cur = pq.poll();\n int distance = cur[0], price = cur[1], r = cur[2], c = cur[3]; // distance, price, row & column.\n if (low <= price && price <= high) { // price in range?\n ans.add(Arrays.asList(r, c));\n }\n for (int m = 0; m < 4; ++m) { // traverse 4 neighbors.\n int i = r + d[m], j = c + d[m + 1];\n // in boundary, not wall, and not visited yet?\n if (0 <= i && i < R && 0 <= j && j < C && grid[i][j] > 0) {\n pq.offer(new int[]{distance + 1, grid[i][j], i, j});\n grid[i][j] *= -1;\n }\n }\n }\n return ans;\n }\n```\n```python\n def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:\n R, C = map(len, (grid, grid[0]))\n ans, (x, y), (low, high) = [], start, pricing\n heap = [(0, grid[x][y], x, y)]\n grid[x][y] *= -1\n while heap and len(ans) < k:\n distance, price, r, c = heapq.heappop(heap)\n if low <= price <= high:\n ans.append([r, c])\n for i, j in (r, c + 1), (r, c - 1), (r + 1, c), (r - 1, c):\n if R > i >= 0 <= j < C and grid[i][j] > 0: \n heapq.heappush(heap, (distance + 1, grid[i][j], i, j))\n grid[i][j] *= -1\n return ans\n```\n**Analysis:**\n\nTime: `O(R * C * log(R * C))`, space: `O(R * C)`, where `R = grid.length, C = grid[0].length`.
105,967
K Highest Ranked Items Within a Price Range
k-highest-ranked-items-within-a-price-range
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following: It takes 1 step to travel between adjacent grid cells. You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k. You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.
Array,Breadth-First Search,Sorting,Heap (Priority Queue),Matrix
Medium
Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as the answer.
14,287
6
If you are new to Dijkstra, see my other posts with graph explanations. \n\nFor such matrix-like problem, can always think about coverting it to a graph problem: each cell represents a node in graph and is connected to its for different neighbors. The number of the cell represent the the weight.\n\nThen the question is then translated to: starting from the start point, find k nodes (meaing that the cell\'s value should not be 0 according to the question) according to the **rule** provided.\n\nThinking about the Dijkstra Algorithm, it can rank the nodes accoding a **rule** of measuing the accumulated weights of edges from the starting point to the nodes. In this sense, we can just use the Dikstra Algorithm and replace its classical rule with the rule provided here. Bingo!\n\nSimilar Leetcode problems can be solved with the same paradigm:\n\n\n\n```\nimport heapq\nclass Solution:\n def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:\n row, col = len(grid), len(grid[0])\n q = [(0, grid[start[0]][start[1]], start[0], start[1])]\n visit = set()\n result = []\n while q:\n dis, price, x, y = heapq.heappop(q)\n if (x, y) in visit:\n continue\n visit.add((x, y))\n if price != 1 and price >= pricing[0] and price <= pricing[1]:\n result.append([x, y])\n if len(result) == k:\n return result\n for dx, dy in (0, 1), (0, -1), (1, 0), (-1, 0):\n new_x, new_y = x + dx, y + dy\n if 0 <= new_x < row and 0 <= new_y < col and (new_x, new_y) not in visit:\n temp = grid[new_x][new_y]\n if temp == 0:\n continue\n elif temp == 1:\n heapq.heappush(q, (dis + 1, 1, new_x, new_y))\n else:\n heapq.heappush(q, (dis + 1, temp, new_x, new_y))\n \n return result\n```
105,980
Number of Ways to Divide a Long Corridor
number-of-ways-to-divide-a-long-corridor
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0.
Math,String,Dynamic Programming
Hard
Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k plants between two adjacent segments, there are k + 1 positions (ways) you could install the divider you must install. The problem now becomes: Find the product of all possible positions between every two adjacent segments.
439
15
# Intuition\nConsider two seats as a pair.\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:05` Return 0\n`0:38` Think about a case where we can put dividers\n`4:44` Coding\n`7:18` Time Complexity and Space Complexity\n`7:33` Summary of the algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 3,258\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n## How we think about a solution\n\n\nLet\'s think about simple cases\n```\nInput: corridor = "SSPS"\n```\nIn this case, we can\'t create division with `2` seats because we have `3` seats in the corridor.\n\nHow about this?\n```\nInput: corridor = "SSPSPSS"\n```\nIn this case, we can\'t create division with `2` seats because we have `5` seats in the corridor.\n\n---\n\n\u2B50\uFE0F Points\n\nIf we have odd number of seats, return 0\n\n---\n\nLet\'s think about this case.\n```\nInput: corridor = "SSPPSPS"\n```\nWe need to have `2` seats in each division. In other words the first `2` seats should be a pair and third seat and fourth seat also should be pair.\n\nThat\'s why we can put dividers only between pairs.\n```\n"SS|PPSPS"\n"SSP|PSPS"\n"SSPP|SPS"\n```\n```\nOutput: 3\n```\n- How can you calculate the output?\n\nWe can put divider between pairs. In the above example, we have `2` plants between pairs and output is `3`. What if we have `1` plant between pairs\n```\nInput: corridor = "SSPSPS"\n```\n```\n"SS|PSPS"\n"SSP|SPS"\n```\n```\nOutput: 2\n```\nSo, number of divider should be `number of plants + 1`. More precisely, we can say `index of thrid seat - index of second seat` is the same as `number of plants + 1`.\n\n```\n 0123456\n"SSPPSPS"\n \u2191 \u2191\n\n4 - 1 = 3\n\n 012345\n"SSPSPS"\n \u2191 \u2191\n\n3 - 1 = 2\n```\nLet\'s say we have `2` ways(x and y) to put dividers so far and find `3` new ways(a,b and c) to put dividers, in that case, we have `6` ways to put dividers.\n\n```\nx + a\ny + a\nx + b\ny + b\nx + c\ny + c\n= 6 ways\n```\n\n\n---\n\n\u2B50\uFE0F Points\n\nEvery time we find new ways, we should multiply number of new ways with current number of ways. That happens when we have more than 2 seats and find odd number of seats (= between pairs).\n\n---\n\nI think we talk about main points.\nLet\'s see a real algorithm!\n\n\n---\n\n\n\n### 1. Initialization:\n\n#### Code:\n```python\nmod = 10**9 + 7 \nres = 1\nprev_seat = 0\nnum_seats = 0\n```\n#### Explanation:\n- Set `mod` to `10**9 + 7` as the modulo value for the final result.\n- Initialize `res` to 1. This variable will be updated during iteration and represents the result.\n- Initialize `prev_seat` to 0. This variable tracks the index of the previous seat encountered.\n- Initialize `num_seats` to 0. This variable counts the number of seats encountered.\n\n### 2. Iteration through the Corridor:\n\n#### Code:\n```python\nfor i, c in enumerate(corridor):\n if c == \'S\':\n num_seats += 1\n\n if num_seats > 2 and num_seats % 2 == 1:\n res *= i - prev_seat\n\n prev_seat = i\n```\n#### Explanation:\n- Use a for loop to iterate through each character `c` and its index `i` in the corridor.\n- Check if the character `c` is equal to \'S\', indicating the presence of a seat.\n - Increment `num_seats` by 1, as a seat is encountered.\n - Check if there are more than 2 consecutive seats and an odd number of seats.\n - If the condition is met, update `res` by multiplying it with the distance between the current seat and the previous seat (`i - prev_seat`).\n - Update `prev_seat` to the current index `i`.\n\n### 3. Final Result:\n\n#### Code:\n```python\nreturn res % mod if num_seats > 1 and num_seats % 2 == 0 else 0\n```\n\n#### Explanation:\n- Return the final result, calculated as `res % mod`, only if there are more than 1 seat and an even number of seats. Otherwise, return 0.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\nclass Solution:\n def numberOfWays(self, corridor: str) -> int:\n mod = 10**9 + 7 # Define the modulo value for the final result\n res = 1 # Initialize the result variable to 1 (will be updated during iteration)\n prev_seat = 0 # Initialize the variable to track the index of the previous seat\n num_seats = 0 # Initialize the variable to count the number of seats encountered\n\n for i, c in enumerate(corridor):\n if c == \'S\':\n num_seats += 1 # Increment the seat count when \'S\' is encountered\n # Check if there are more than 2 consecutive seats and an odd number of seats\n if num_seats > 2 and num_seats % 2 == 1:\n # Update the answer using the distance between the current seat and the previous seat\n res *= i - prev_seat\n prev_seat = i # Update the previous seat index to the current index\n\n # Return the answer only if there are more than 1 seat and an even number of seats\n return res % mod if num_seats > 1 and num_seats % 2 == 0 else 0\n```\n```javascript []\n/**\n * @param {string} corridor\n * @return {number}\n */\nvar numberOfWays = function(corridor) {\n const mod = 1000000007; // Define the modulo value for the final result\n let res = 1; // Initialize the result variable to 1 (will be updated during iteration)\n let prevSeat = 0; // Initialize the variable to track the index of the previous seat\n let numSeats = 0; // Initialize the variable to count the number of seats encountered\n\n for (let i = 0; i < corridor.length; i++) {\n const c = corridor.charAt(i);\n if (c === \'S\') {\n numSeats += 1; // Increment the seat count when \'S\' is encountered\n // Check if there are more than 2 consecutive seats and an odd number of seats\n if (numSeats > 2 && numSeats % 2 === 1) {\n // Update the answer using the distance between the current seat and the previous seat\n res = res * (i - prevSeat) % mod;\n }\n prevSeat = i; // Update the previous seat index to the current index\n }\n }\n\n // Return the answer only if there are more than 1 seat and an even number of seats\n return numSeats > 1 && numSeats % 2 === 0 ? res : 0; \n};\n```\n```java []\npublic class Solution {\n public int numberOfWays(String corridor) {\n final int mod = 1000000007; // Define the modulo value for the final result\n long res = 1; // Initialize the result variable to 1 (will be updated during iteration)\n int prevSeat = 0; // Initialize the variable to track the index of the previous seat\n int numSeats = 0; // Initialize the variable to count the number of seats encountered\n\n for (int i = 0; i < corridor.length(); i++) {\n char c = corridor.charAt(i);\n if (c == \'S\') {\n numSeats += 1; // Increment the seat count when \'S\' is encountered\n // Check if there are more than 2 consecutive seats and an odd number of seats\n if (numSeats > 2 && numSeats % 2 == 1) {\n // Update the answer using the distance between the current seat and the previous seat\n res = res * (i - prevSeat) % mod;\n }\n prevSeat = i; // Update the previous seat index to the current index\n }\n }\n\n // Return the answer only if there are more than 1 seat and an even number of seats\n return numSeats > 1 && numSeats % 2 == 0 ? (int)res : 0;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numberOfWays(string corridor) {\n const int mod = 1000000007; // Define the modulo value for the final result\n long res = 1; // Initialize the result variable to 1 (will be updated during iteration)\n int prevSeat = 0; // Initialize the variable to track the index of the previous seat\n int numSeats = 0; // Initialize the variable to count the number of seats encountered\n\n for (int i = 0; i < corridor.length(); i++) {\n char c = corridor[i];\n if (c == \'S\') {\n numSeats += 1; // Increment the seat count when \'S\' is encountered\n // Check if there are more than 2 consecutive seats and an odd number of seats\n if (numSeats > 2 && numSeats % 2 == 1) {\n // Update the answer using the distance between the current seat and the previous seat\n res = res * (i - prevSeat) % mod; \n }\n prevSeat = i; // Update the previous seat index to the current index\n }\n }\n\n // Return the answer only if there are more than 1 seat and an even number of seats\n return numSeats > 1 && numSeats % 2 == 0 ? res : 0; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n\u25A0 Twitter\n\n\n### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:03` Right shift\n`1:36` Bitwise AND\n`3:09` Demonstrate how it works\n`6:03` Coding\n`6:38` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:05` How we can move columns\n`1:09` Calculate height\n`2:48` Calculate width\n`4:10` Let\'s make sure it works\n`5:40` Demonstrate how it works\n`7:44` Coding\n`9:59` Time Complexity and Space Complexity\n`10:35` Summary of the algorithm with my solution code\n
106,010
Number of Ways to Divide a Long Corridor
number-of-ways-to-divide-a-long-corridor
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0.
Math,String,Dynamic Programming
Hard
Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k plants between two adjacent segments, there are k + 1 positions (ways) you could install the divider you must install. The problem now becomes: Find the product of all possible positions between every two adjacent segments.
3,840
15
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe can say that to compute three values at index indexindexindex, we need only three values at index index+1index + 1index+1. Hence, we can save only three variables, namely zero, one, and two that represent the values at the most recent computed index index+1index + 1index+1.\n\n- Initially\n\n zero = 0\n one = 0\n two = 1\n- If corridor[index] is S, then\n\n new_zero = one\n new_one = two\n new_two = one\nThen we can update the values of zero, one, and two as zero = new_zero, one = new_one, and two = new_two.\n\nHowever, it is worth noting that zero is not used in the computation of any new variables. Thus, zero = one will work, and we are not overwriting the value of zero before using it.\nAdding to it, next we just need to swap the values of one and two. Hence, the final update is as\n\n zero = one\n swap(one, two). For this, we can do an XOR swap or can use a temporary variable.\n- If corridor[index] is P, then\n\n new_zero = zero\n new_one = one\n new_two = (zero + two) % MOD\nThen we can update the values of zero, one, and two as zero = new_zero, one = new_one, and two = new_two.\n\nHowever, it is worth noting that zero and one remain unchanged in all of these assignments. Thus, updating zero and one is redundant.\nRegarding two, we just need to add zero in it, and then take modulo MOD. Hence, the final update is as\n\n two = (two + zero) % MOD\nDue to the symmetry of count, the corridor traversal is possible from left to right as well as from right to left. We will traverse the corridor from left to right this time.\n\nAt last, our answer will be stored in variable zero, as initially, we have zero number of S.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.Store 1000000007 in the variable MOD for convenience. It is a good practice to store constants.\n2.Initialize three variables zero, one, and two to 0, 0, and 1 respectively.\n\n3.Traverse corridor from left to right, for index from 0 to n - 1\n\n- if corridor[index] is S, then\nzero = one\nswap(one, two)\n- if corridor[index] is P, then\ntwo = (two + zero) % MOD\n4. Return zero as we have a zero number of S initially.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe are linearly traversing the corridor. In each iteration, we are updating three variables, which will take constant time. Thus, the time complexity will be O(N)\u22C5O(1)O(N) \\cdot O(1)O(N)\u22C5O(1), which is O(N)O(N)O(N).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe are using a handful of variables, which will take constant extra space. Thus, the space complexity will be O(1)O(1)O(1).\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int numberOfWays(string corridor) {\n // Store 1000000007 in a variable for convenience\n const int MOD = 1e9 + 7;\n\n // Initial values of three variables\n int zero = 0;\n int one = 0;\n int two = 1;\n\n // Compute using derived equations\n for (char thing : corridor) {\n if (thing == \'S\') {\n zero = one;\n swap(one, two);\n } else {\n two = (two + zero) % MOD;\n }\n }\n\n // Return the result\n return zero;\n }\n};\n```\n```javascript []\nclass Solution {\n numberOfWays(corridor) {\n const MOD = 1e9 + 7;\n let zero = 0;\n let one = 0;\n let two = 1;\n\n for (const thing of corridor) {\n if (thing === \'S\') {\n zero = one;\n [one, two] = [two, one];\n } else {\n two = (two + zero) % MOD;\n }\n }\n\n return zero;\n }\n}\n```\n```python []\nclass Solution:\n def numberOfWays(self, corridor):\n MOD = 10**9 + 7\n zero = 0\n one = 0\n two = 1\n\n for thing in corridor:\n if thing == \'S\':\n zero = one\n one, two = two, one\n else:\n two = (two + zero) % MOD\n\n return zero\n```\n```Java []\npublic class Solution {\n public int numberOfWays(String corridor) {\n final int MOD = 1000000007;\n int zero = 0;\n int one = 0;\n int two = 1;\n\n for (char thing : corridor.toCharArray()) {\n if (thing == \'S\') {\n zero = one;\n int temp = one;\n one = two;\n two = temp;\n } else {\n two = (two + zero) % MOD;\n }\n }\n\n return zero;\n }\n}\n\n```
106,016
Number of Ways to Divide a Long Corridor
number-of-ways-to-divide-a-long-corridor
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant. One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way. Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0.
Math,String,Dynamic Programming
Hard
Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k plants between two adjacent segments, there are k + 1 positions (ways) you could install the divider you must install. The problem now becomes: Find the product of all possible positions between every two adjacent segments.
7,415
42
\n# Solution 1\n\n- We need to place a dividor after 2 seats.\n- When a dividor is placed between any 2 seats : \n- * `Number of ways to do so = (Number of plants in between seats + 1)`\n\nSo we iterate through the String\n1. After every two seats : Count the number of plants till next seat\n2. Number of ways to put dividor = `(Number of plants in between seats + 1)`\n3. Multiply all the number of ways to get the answer.\nReturn modulo `10^9 + 7`\n\n``` Python []\nclass Solution:\n def numberOfWays(self, corridor):\n seat, res, plant = 0, 1, 0\n for i in corridor:\n if i==\'S\':\n seat += 1\n else:\n if seat == 2:\n plant += 1\n if seat == 3:\n res = res*(plant+1) % (10**9 + 7)\n seat , plant = 1 , 0\n if seat != 2:\n return 0\n return res\n```\n``` C++ []\nnt numberOfWays(std::string corridor) {\n int seat = 0, res =1, plant = 0;\n\n for (char i : corridor) {\n if (i == \'S\')\n seat += 1;\n else\n if (seat == 2)\n plant += 1;\n\n if (seat == 3) {\n res = (res * (plant + 1)) % (1000000007);\n seat = 1;\n plant = 0;\n }\n }\n\n if (seat != 2)\n return 0;\n\n return res;\n }\n```\n\n\n# Solution 2\nIf seats == odd , then ```answer -> 0```\nIf seats == even, then there is always a possible division.\n\nWe can only put a DIVIDER after every two seats\n\n# Explanation\n\n`x` -> number of way to put divider betweem seats, current number of seats. It mean, when x > 0 it mean we have counted 1 or 2 seats.\n\n`y` -> state variable, if y > 0 it means we have counted 1 seat.\n`z` -> total ways to put divider.\n\nThe flow of the algo:\n- `x` start with 1, due to we counted no seat. y, z = 0 hence we counted 0 seats and 0 ways to put divider.\n- When we counted first seat, x = 0, y = 1, z = 0.\n- When we counted second seat, x = 0, y = 0, z = 1. After the second seat, x is increase by z every time we meet a plant.\n- When we meet a seat again, the swap happen -> `z=y, y = x, x = 0`. When we meet the second seat, the swap become -> `z = y, y = x, x = 0`. so, this basically update number of way we counted to z when we have countered 2 more seat again, if not, z stay 0.\n\nCreating variables\n```\nx -> 0 seats\ny -> 1 seat\nz -> 2 seats\n```\n\nFor each ``"s"`` in string :\n\n``x -> x + z``\n``z -> y``\n``y -> x``\n``x -> 0``\nElse\n``\nx -> x + z\n``\n\n\n\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n\n``` C++ []\nclass Solution {\npublic:\n int numberOfWays(string corridor) {\n int x = 1; // 0 seat\n int y = 0; // 1 seat\n int z = 0; // 2 seats\n for (char& ch: corridor)\n if (ch == \'S\')\n x = (x + z) % int(1e9 + 7), z = y, y = x, x = 0;\n else\n x = (x + z) % int(1e9 + 7);\n return z;\n }\n};\n```\n``` Python []\nclass Solution:\n def numberOfWays(self, corridor):\n x = 1 # 0 seat\n y = 0 # 1 seat\n z = 0 # 2 seats\n for char in corridor:\n if char == \'S\':\n x, y, z = 0, x + z, y\n else:\n x, y, z = x + z, y, z\n return z % (10**9+7) \n```\n```JAVA []\nclass Solution {\n public int numberOfWays(String corridor) {\n int x = 1; // 0 seat\n int y = 0; // 1 seat\n int z = 0; // 2 seats\n int mod = (int)1e9 + 7;\n for (int i = 0; i < corridor.length(); ++i)\n if (corridor.charAt(i) == \'S\') {\n x = (x + z) % mod;\n z = y; \n y = x;\n x = 0;\n } else {\n x = (x + z) % mod;\n }\n return z;\n }\n}\n\n```\n\n![IMG_3725.JPG]()\n
106,031
Check if Every Row and Column Contains All Numbers
check-if-every-row-and-column-contains-all-numbers
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Array,Hash Table,Matrix
Easy
Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.
11,399
69
**Q & A**\n\nQ: How does declaring sets inside 1st loop different from declaring ouside the loops?\nA: They only exist during each iteration of the outer loop; Therefore, we do NOT need to clear them after each iteration. Otherwise their life cycle will NOT terminate till the end of the whole code, and also we have to clear them after each iteration of outer for loop.\n\n**End of Q & A**\n\n----\n\n**Method 1: Use HashSet to check each row / column**\n\nCredit to **@uprightclear** for improvement of Java code.\n```java\n public boolean checkValid(int[][] matrix) {\n for (int r = 0, n = matrix.length; r < n; ++r) {\n Set<Integer> row = new HashSet<>();\n Set<Integer> col = new HashSet<>();\n for (int c = 0; c < n; ++c) {\n if (!row.add(matrix[r][c]) || !col.add(matrix[c][r])) {\n return false;\n }\n }\n }\n return true;\n }\n```\n```python\n def checkValid(self, matrix: List[List[int]]) -> bool:\n n = len(matrix)\n for row, col in zip(matrix, zip(*matrix)):\n if len(set(row)) != n or len(set(col)) != n:\n return False\n return True\n```\n\n----\n\n**Method 2: BitSet/bytearray**\n\n```java\n public boolean checkValid(int[][] matrix) {\n for (int r = 0, n = matrix.length; r < n; ++r) {\n BitSet row = new BitSet(n + 1), col = new BitSet(n + 1);\n for (int c = 0; c < n; ++c) {\n if (row.get(matrix[r][c]) || col.get(matrix[c][r])) {\n return false;\n }\n row.set(matrix[r][c]);\n col.set(matrix[c][r]);\n }\n } \n return true;\n }\n```\n```python\n def checkValid(self, matrix: List[List[int]]) -> bool:\n n = len(matrix)\n for r in range(n):\n row = bytearray(n + 1) \n col = bytearray(n + 1) \n for c in range(n):\n ro, co = matrix[r][c], matrix[c][r]\n row[ro] += 1\n col[co] += 1\n if row[ro] > 1 or col[co] > 1:\n return False\n return True\n```\n**Analysis:**\n\nTime: `O(n * n)`, space: O(n), where `n = matrix.length`.
106,059
Check if Every Row and Column Contains All Numbers
check-if-every-row-and-column-contains-all-numbers
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Array,Hash Table,Matrix
Easy
Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.
4,071
26
Create a set containing the integers from `1...n` then check that each set of rows and columns is equal to this set.\n\n`zip(*matrix)` is a convenient way of obtaining the columns of a matrix\n\n```python\n def checkValid(self, matrix: List[List[int]]) -> bool:\n set_ = set(range(1,len(matrix)+1))\n return all(set_ == set(x) for x in matrix+list(zip(*matrix)))\n```
106,066
Check if Every Row and Column Contains All Numbers
check-if-every-row-and-column-contains-all-numbers
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Array,Hash Table,Matrix
Easy
Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.
614
5
```\nclass Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n N = len(matrix)\n \n s = set(i + 1 for i in range(N))\n \n for i in range(N):\n sumRow, sumCol = set(), set()\n for j in range(N):\n sumRow.add(matrix[i][j])\n sumCol.add(matrix[j][i])\n \n if sumRow != s or sumCol != s:\n return False\n \n return True\n```
106,083
Check if Every Row and Column Contains All Numbers
check-if-every-row-and-column-contains-all-numbers
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Array,Hash Table,Matrix
Easy
Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.
837
5
As suggested by @kartik135065, \nsimple XOR method can be wrong as the code could not pass the test case such as [[1,2,2,4,5,6,6],[2,2,4,5,6,6,1],[2,4,5,6,6,1,2],[4,5,6,6,1,2,2],[5,6,6,1,2,2,4],[6,6,1,2,2,4,5],[6,1,2,2,4,5,6]]\n\nI crafted the correct codes using the XOR idea and easily passed the above test case. Pls upvote is you find it helpful. \n\nTime complexity O(N^2)\nSpace complexity O(1)\n\nInitial Code: May have overflow issue if n is too large\n```\nclass Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n # bitmask\n n = len(matrix)\n\n for i in range(n):\n row_bit, col_bit, bitmask = 1, 1, 1\n for j in range(n):\n row_bit ^= 1 << matrix[i][j]\n col_bit ^= 1 << matrix[j][i]\n bitmask |= 1 << j + 1\n\n if row_bit ^ bitmask or col_bit ^ bitmask:\n return False\n \n return True\n```\n\nUsing the third bitmask to avoid the overflow issue\n```\nclass Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n # bitmask\n n = len(matrix)\n\n for i in range(n):\n row_bit, col_bit, bitmask = 1, 1, 1\n for j in range(n):\n row_bit ^= 1 << matrix[i][j]\n col_bit ^= 1 << matrix[j][i]\n bitmask |= 1 << j + 1\n\n if row_bit ^ bitmask or col_bit ^ bitmask:\n return False\n \n return True\n```
106,090
Check if Every Row and Column Contains All Numbers
check-if-every-row-and-column-contains-all-numbers
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Array,Hash Table,Matrix
Easy
Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.
1,711
12
```\nclass Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n lst = [0]*len(matrix)\n for i in matrix:\n if len(set(i)) != len(matrix):\n return False\n for j in range(len(i)):\n lst[j] += i[j]\n return len(set(lst)) == 1\n```
106,091
Check if Every Row and Column Contains All Numbers
check-if-every-row-and-column-contains-all-numbers
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Array,Hash Table,Matrix
Easy
Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.
597
5
Here is what I did:\nNote the popular idiom of transposing the matrix in python: `zip(*matrix)`\n\n```python\n def checkValid(self, matrix: List[List[int]]) -> bool:\n nums = set(range(1, len(matrix) + 1))\n for row in matrix:\n if set(row) != nums:\n return False\n for col in zip(*matrix):\n if set(col) != nums:\n return False\n return True\n```
106,094
Check if Every Row and Column Contains All Numbers
check-if-every-row-and-column-contains-all-numbers
An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive). Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Array,Hash Table,Matrix
Easy
Use for loops to check each row for every number from 1 to n. Similarly, do the same for each column. For each check, you can keep a set of the unique elements in the checked row/col. By the end of the check, the size of the set should be n.
1,274
5
Please checkout this [commit]() for solutions of weekly 275. \n\n```\nclass Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n return all(len(set(row)) == len(matrix) for row in matrix) and all(len(set(col)) == len(matrix) for col in zip(*matrix))\n```
106,104
Minimum Swaps to Group All 1's Together II
minimum-swaps-to-group-all-1s-together-ii
A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.
Array,Sliding Window
Medium
Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of 0’s in the subarray. To eliminate the circular property of the array, we can append the original array to itself. Then, we check each subarray of length total. How do we avoid recounting the number of 0’s in the subarray each time? The Sliding Window technique can help.
9,915
210
*Intuition*: \nWhenever you are faced with a circular array question, you can just append the array to itself to get rid of the circular array part of the problem\n\n***Explanation***:\n* Count number of ones in nums, let the number of ones be stored in the variable `ones`\n* Append nums to nums because we have to look at it as a circular array\n* Find the maximum number of ones in a window of size `ones` in the new array\n* Number of swaps = `ones` - maximum number of ones in a window of size `ones`\n<iframe src="" frameBorder="0" width="600" height="300"></iframe>\n\nWe can also solve the same in O(1) space. Loop through the array twice:\n```\ndef minSwaps(self, nums: List[int]) -> int:\n\tones, n = nums.count(1), len(nums)\n\tx, onesInWindow = 0, 0\n\tfor i in range(n * 2):\n\t\tif i >= ones and nums[i % n - ones]: x -= 1\n\t\tif nums[i % n] == 1: x += 1\n\t\tonesInWindow = max(x, onesInWindow)\n\treturn ones - onesInWindow\n```
106,110
Minimum Swaps to Group All 1's Together II
minimum-swaps-to-group-all-1s-together-ii
A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.
Array,Sliding Window
Medium
Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of 0’s in the subarray. To eliminate the circular property of the array, we can append the original array to itself. Then, we check each subarray of length total. How do we avoid recounting the number of 0’s in the subarray each time? The Sliding Window technique can help.
1,324
22
First, by appending nums to nums, you can ignore the effect of split case.\nThen, you look at the window whose width is `width`. Here, `width` = the number of 1\'s in the original nums. This is because you have to gather all 1\'s in this window at the end of some swap operations. Therefore, the number of swap operation is the number of 0\'s in this window. \nThe final answer should be the minimum value of this.\n\n```\nclass Solution:\n def minSwaps(self, nums: List[int]) -> int:\n width = sum(num == 1 for num in nums) #width of the window\n nums += nums\n res = width\n curr_zeros = sum(num == 0 for num in nums[:width]) #the first window is nums[:width]\n \n for i in range(width, len(nums)):\n curr_zeros -= (nums[i - width] == 0) #remove the leftmost 0 if exists\n curr_zeros += (nums[i] == 0) #add the rightmost 0 if exists\n res = min(res, curr_zeros) #update if needed\n \n return res\n```
106,115
Minimum Swaps to Group All 1's Together II
minimum-swaps-to-group-all-1s-together-ii
A swap is defined as taking two distinct positions in an array and swapping the values in them. A circular array is defined as an array where we consider the first element and the last element to be adjacent. Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.
Array,Sliding Window
Medium
Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of 0’s in the subarray. To eliminate the circular property of the array, we can append the original array to itself. Then, we check each subarray of length total. How do we avoid recounting the number of 0’s in the subarray each time? The Sliding Window technique can help.
927
8
Denote as `winWidth` the total number of `1`\'s in the input array, then the goal of swaps is to get a window of size `winWidth` full of `1`\'s. Therefore, we can maintain a sliding window of size `winWidth` to find the maximum `1`\'s inside, and accordingly the minimum number of `0`\'s inside the sliding window is the solution.\n\n```java\n public int minSwaps(int[] nums) {\n int winWidth = 0;\n for (int n : nums) {\n winWidth += n;\n }\n int mx = 0;\n for (int lo = -1, hi = 0, onesInWin = 0, n = nums.length; hi < 2 * n; ++hi) {\n onesInWin += nums[hi % n];\n if (hi - lo > winWidth) {\n onesInWin -= nums[++lo % n];\n }\n mx = Math.max(mx, onesInWin);\n }\n return winWidth - mx;\n }\n```\n```python\n def minSwaps(self, nums: List[int]) -> int:\n win_width = sum(nums)\n lo, mx, ones_in_win = -1, 0, 0\n n = len(nums)\n for hi in range(2 * n):\n ones_in_win += nums[hi % n]\n if hi - lo > win_width:\n lo += 1\n ones_in_win -= nums[lo % n]\n mx = max(mx, ones_in_win) \n return win_width - mx\n```\n\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`, where `n = nums.length`.
106,125
Count Words Obtained After Adding a Letter
count-words-obtained-after-adding-a-letter
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.
Array,Hash Table,String,Bit Manipulation,Sorting
Medium
Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords?
7,011
94
Please checkout this [commit]() for solutions of weekly 275. \n\n```\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n seen = set()\n for word in startWords: \n m = 0\n for ch in word: m ^= 1 << ord(ch)-97\n seen.add(m)\n \n ans = 0 \n for word in targetWords: \n m = 0 \n for ch in word: m ^= 1 << ord(ch)-97\n for ch in word: \n if m ^ (1 << ord(ch)-97) in seen: \n ans += 1\n break \n return ans \n```
106,162
Count Words Obtained After Adding a Letter
count-words-obtained-after-adding-a-letter
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.
Array,Hash Table,String,Bit Manipulation,Sorting
Medium
Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords?
3,350
27
1. Use HashMap/dict to group the hashs of the anagrams in `startWords` by their lengths;\n2. Traverse `targetWords`, for each word, compute its hashs after remove one character; Then check if we can find the hashs among the HashMap/dict corresponding to `startWord`; If yes, increase the counter `cnt` by `1`;\n\n**Method 1: Use char[]/String as hash**\n\n```java\n public int wordCount(String[] startWords, String[] targetWords) {\n Map<Integer, Set<String>> groups = new HashMap<>();\n for (String w : startWords) {\n char[] ca = getHash(w);\n groups.computeIfAbsent(w.length(), s -> new HashSet<>()).add(String.valueOf(ca));\n }\n int cnt = 0;\n outer:\n for (String w : targetWords) {\n int sz = w.length() - 1;\n if (groups.containsKey(sz)) {\n char[] ca = getHash(w);\n for (char c : w.toCharArray()) {\n --ca[c - \'a\'];\n if (groups.get(sz).contains(String.valueOf(ca))) {\n ++cnt;\n continue outer;\n }\n ++ca[c - \'a\'];\n }\n }\n }\n return cnt;\n }\n private char[] getHash(String w) {\n char[] ca = new char[26];\n for (char c : w.toCharArray()) {\n ++ca[c - \'a\'];\n }\n return ca;\n }\n```\n```python\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n \n def getHash(w: str) -> List[int]:\n h = [0] * 26\n for c in w:\n h[ord(c) - ord(\'a\')] = 1\n return h\n \n groups = defaultdict(set)\n for w in startWords:\n h = getHash(w)\n groups[len(w)].add(tuple(h))\n cnt = 0\n for w in targetWords:\n if groups[len(w) - 1]:\n h = getHash(w)\n for c in w:\n h[ord(c) - ord(\'a\')] = 0\n if tuple(h) in groups[len(w) - 1]:\n cnt += 1\n break\n h[ord(c) - ord(\'a\')] = 1\n return cnt\n```\n\n----\n\n**Method 2: Use int as hash - bit manipulation**\n\n```java\n public int wordCount(String[] startWords, String[] targetWords) {\n Map<Integer, Set<Integer>> groups = new HashMap<>();\n for (String w : startWords) {\n groups.computeIfAbsent(w.length(), s -> new HashSet<>()).add(getHash(w));\n }\n int cnt = 0;\n for (String w : targetWords) {\n int hash = getHash(w), len = w.length() - 1;\n for (char c : w.toCharArray()) {\n if (groups.containsKey(len) && groups.get(len).contains(hash ^ (1 << c - \'a\'))) {\n ++cnt;\n break;\n }\n }\n }\n return cnt;\n }\n private int getHash(String w) {\n int hash = 0;\n for (char c : w.toCharArray()) {\n hash |= 1 << c - \'a\';\n }\n return hash;\n }\n```\n```python\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n \n def getHash(w: str) -> int:\n h = 0\n for c in w:\n h |= 1 << ord(c) - ord(\'a\')\n return h \n \n cnt, groups = 0, defaultdict(set)\n for w in startWords:\n groups[len(w)].add(getHash(w))\n for w in targetWords:\n h = getHash(w)\n if any((h ^ (1 << ord(c) - ord(\'a\'))) in groups[len(w) - 1] for c in w):\n cnt += 1\n return cnt\n```\n\n**Analysis:**\n\nDenote `S = startWords.length` and `T = targetWords.length`. Let `m` and `n` be the average sizes of the words in `startWords` and `targetWords` respectively, then,\n\nTime & space: `O(S * m + T * n)`.
106,168
Count Words Obtained After Adding a Letter
count-words-obtained-after-adding-a-letter
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.
Array,Hash Table,String,Bit Manipulation,Sorting
Medium
Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords?
646
10
My output is 253 and result is 254.\nCan every one tell me where\'s wrong logic?\n\n```\n["mgxfkirslbh","wpmsq","pxfouenr","lnq","vcomefldanb","gdsjz","xortwlsgevidjpc","kynjtdlpg","hmofavtbgykidw","bsefprtwxuamjih","yvuxreobngjp","ihbywqkteusjxl","ugh","auydixmtogrkve","ox","wvknsj","pyekgfcab","zsunrh","ecrpmxuw","mtvpdgwr","kpbmwlxgus","ob","gfhqz","qvjkgtxecdoafpi","rnufgtom","vijqecrny","lkgtqcxbrfhay","eq","mbhf","iv","bzevwoxrnjp","wgusokd","cnkexvsquwlgbfp","zebrwf","gdxleczutofajir","x","mtraowpeschbkxi","daickygrp","p","xjlwcbapyszdtv","hgab","nlgf","z","mt","oumqabs","alf","whfruolazjdcb","tf","dxngwmft","ibuvnosrqdgjyp","hftpg","jcnah","recavwlgfxiuk","stjuiedvlfwbhpq","dqakvgfrc","nzqtouwbism","dwymhgcsx","zvqr","c","hevgr","jbsvmrtcnow","fptlcxg","wsiqcgnlfxb","zapnjquycdsxvi","lcvabg","hpuzsbgqkeixwr","ornd","eqgukchjnwids","ysxbhdzpvgcew","ji","ozna","be","muhikqnd","axlhyftvrpkucs","aedofvlhzqmxrt","g","leifus","i","qlgcrxsdnmytb","t","fbhlgrvozsyxajt","puyqhksclinob","vfbpcedhn","nqism","zi","qgb","qweg","sh","qmbunh","sp","cainjebqmvyslo","hya","ifyrxkgemqc","hmcrgabdlqkfs","o","abikmjqpr","hbzedog","yxijqknhl","g","jhbav","n","bvglmordite","r","ulmkqdwytxipvao","ngfkuvxatzqryl","wzmxuiyj","jguv","vzgmelrnjpsoa","lgndsxvuiq","cflwyxbezdgsqj","tiqznalvrdepws","znofuykwilps","srquzgomnlkcb","fuktdpbinwl","bevucxl","zgxahrynjqfsmu","digtkmachbrxven","zlkpqatvibr","awdilqtmbrvceg","oswhbncfx","ruzqfvtjphg","x","i","cydkbxnl","zprdiwholgm","bheaiprnvodm","ftihvlsjayw","agdub","v","ahlqydvnkgeju","jkv","bepnzdw","ogjuhltpnmaire","gojxtmraiqz","sfhv","pgmjzehnfxrbk","msat","aodegjbmt","n","fpanl","ghylfn","vzxysgwncmeb","onyeabqimcrtwp","dvcbqueixzfwgo","lafgbztpmdnyws","ydaixthclnjgkq","mgyajwfieus","jinvoyud","xrb","g","ceivybxtljdzu","ijrqzdegpxs","gjw","kczrpqbtwjulamv","alrvb","usftxanbdw","hitvrca","aybtr","kbxpwivucnley","tv","lgpbaytvjdfeowx","igmkqlnedjaxsc","qlvwszxhbrfe","bofcmzyvsg","gc","zojkdvixfbant","cstlvhpkfrdwney","nblsowtza","zjqthpwfbgsae","xqrvdfusnhcbwlj","lmsgtn","dvwyxbch","jagbesnvwhkfxoc","rs","ocyph","rgmfyvwbekxad","ynov","w","xlizrsf","lctpaxqizb","tmovsbjxqeh","aqcoslvfmkg","odpqkzlrxh","osyfzjwbthpamue","atihkjxbcmdfu","ocrjlfnug","psjwqyeibu","fgkjnmpc","bkljzrc","rfgwkp","kygcnhdu","zjmwei","lctvhjrngafo","ouvgm","kmcrx","y","r","anri","gtlrnepusmjbwh","rketigxb","zompxictdrqhy","nbcavygtpldwmsr","fdjbo","dokmrypczgnf","gjidtncwouer","gdclb","pbehgj","rmzgxscqolnh","pgwyiu","rozvjcekpgudl","ngzjyotwepavc","rexjomgdfblsu","ihjsz","uy","ivmx","fmewhrgsxj","ftdbcxpaglunhj","yxnatjghfbzd","rnqbmdhtwzgpsoi","kabsdq","aifosqdtmlxprjy","vzcnmyfu","zcogsdvrpy","maorzpfqus","jmxrhfgtepqoz","srkoghcuvewxfdz","jvrfdtgihb","ndg","kxtqhg","ftdlihv","gklsuycht","yxcv","axsydfeg","ayostk","fhrwkb","ezxauvsjfodit","gdzxkbcowtyrnqp","lxjraocfhi","idge","afptqjcvd","rpdagkqows","uvjregzl","vaeknyjci","ztuavj","qtodpfaxslmc","hxamecynpdq","nlzwr","owbzkhcqlnyd","axsioeklpbcuyq","xpczv","aruicpsw","ebolyfqshp","tuyjgbqxkcnav","mcnyewxfvsi","izb","w","ybrfj","yrpchjik","erljaoiyfxpkght","swjgimbzaqc","aiq","nstwhcabkd","pyrnahv","ckezagrnw","bqrxjysckmzife","cqeslp","bpcxfwy","z","eqypbakhzsdj","dijepvmtohsbg","tokfxvnzrsl","vnamdoblrqwfx","udfmzj","txornzeiykw","qzgjeidfybavhpc","bcnasehw","doqlptju","uciwskjzfpdtlr","orcayhmvgzx","wvyq","uixyfapoznleb","zsawrfun","ifjcovxalpmbryk","cdvajtmnyr","d","vyu","vwcknlphbite","xarzstglin","adm","ifpkuzhs","hlfrkscuzimb","kliwz","trcqxlmy","gidhkfcvmzab","cjxyoszh","bhunojsazwfxvi","l","mwqfzlsguaeoi","fqdomyght","j","swtqiovuaphm","unyjg","ieyxp","aolfrbg","pyovktzmrjuie","uew","l","npwisxm","a","rkexvymhaof","yuipgq","qzvnsx","bwatpdu","vthizgue","eh","oxubpyaqjmfsd","zxlsftu","dusl","rpdsmljtcoaqveg","jfgnilepzhc","nz","wftpvsijg","larx","ylv","drptekxzainhybo","kamdovjbsnizq","igoaprsznvjfkwb","jt","gcpfi","ihvkomuc","qnbgcdxviwulke","cxuhyvdkesprq","lixvrwskot","wngphsjztvx","wv","rcbsphoqijdtmv","nhprx","a","m","wctzuk","fingedrwyjsbl","kbyqad","xtgbyqovckn","xr","ygaenxqc","dnibrxzohft","jy","fbyxqadrewshu","rvfcdtgmkypwai","wr","csotefgijw","rabphzvwcndqil","zk","zwycqvaiubers","pty","qrgtk","kagdqfo","efharqwngoicds","tmgyub","fln","paqesokun","nilutckzejqxgdv","xtuzogl","htfzpqywla","wsmo","glbfvmjzs","brsc","ojcqrn","yqsncexfjumzgo","sunqiwjhvbtxokm","hw","gy","m","wfli","eqazhgjvfydtusr","bu","lwu","mnpobr","xtv","aysfkui","vwmjgknbxheu","ktabp","yqjpfxwen","podsig","erqdbxgckiwlht","emdbpfvzl","gauhjcvxrtmd","eykrotbig","qfhwydcn","njgtvwmzlk","n","urtnipf","c","ptdwigz","qgvutfsrxp","mczxv","whayfszc","wqcaskzb","ox","ngqpswbhd","tabc","lwtf","lbukxpzacyevw","tvsjzbaqohgwke","qspcakoudj","mho","jdw","situxhcgfnq","vhopwt","yqk","pblx","haxbyjvinrq","gbiehqudwprjn","hlg"]\n["nsewcbujhad","aeb","phvbaeinctkwl","cybwlsuzinvk","qwhxytpvefrjz","gvy","ixcalbqfz","igftodzvcnswjlm","thbdfgivurj","nbd","dgqolunivxs","bcsovemfldan","unhzrsd","skwlendhyucapzi","zyrmohljp","qum","btmzgfqaspwjeh","jgkmzqoyvtw","tlgrawcxkn","qdwogyrfs","gephoxvsdj","dfvxywjknm","wru","jnumkcfydo","ewhbxfqgkclsj","lz","ghxopqbey","xc","jiznkxvcues","uykrcxaofhm","vmqdipal","zjkmbqxtyefsicr","fiawpvldc","h","dompynwi","zbkynwmcxgves","mxi","ranoytupxb","pyaqedhvzgjcbifl","fy","nrobdxvspqyjgui","snrm","gfyknowupqrta","wivmt","qtxyhcblrakfdg","vfczbhtoa","reho","o","rzn","rabsgdfxij","gpyhft","jiv","ufqji","xe","pnifxjhmtosa","j","vzodg","cthzjspulafxiwb","ohbmuqn","rdliztsjukcwfpv","saoqpd","pxu","kxnguybvejfwo","fukagtlbndmpry","sqlpaytnvhkrmo","pm","umco","imjqrd","riq","vywxz","npiu","rvzjq","qso","epkloxmr","racvl","znkcwbg","sfp","mguztnorf","pnjogwuyztacev","qdyxcfzbhp","bcwhdqzjultrai","sfvheigw","vgqb","brsyjegvmhdc","xwuadlp","aft","pinl","gctwje","ufjzmdp","ohbxag","cdfamgpntkwu","ruaekpdbfqtzclj","cesowgvpltxjihdr","nfy","jftgxplc","zhlgtxou","tljanzupriodew","rlesyncqbkftuoh","eqslt","giotujnrwfdce","qldztvnyguwxso","vjkdfzuaseitxo","rdimnopgzhlw","ckrjyqwplitsfo","dwvj","wgje","qcmrxk","qgflbvxhn","qoniymsa","ftdcoxpqakigrejv","hrusofb","qcm","scwykazqb","riswegfoctj","tq","ekoc","sjpkg","dikj","sqigfbrel","eoknxfrup","ot","djfsbwkpuhl","yvafsiku","clnbxzg","ivbhygjqrxan","rit","msprwq","hfdjmckqzpulrw","hfwazycos","kdmnqztsi","nrhol","lctab","svf","crxngv","gczkqjs","agfqzhmy","dvoxgmh","ndvcuykgh","vct","nywvhcxbd","e","pbufvcszi","ql","agvpjizktbwsorfn","zxvgbkwca","omeayvfwhqzrpi","fmgcxeutzdk","ldpbcrayxztsjvw","nxt","ypluzeavsqw","zmbv","rucwispfa","iucj","jnhbzw","vqhetubalnf","poivetgflayxkjhr","tje","nr","spygwiqr","ewyuforkmpicnx","vg","hakjcn","aygvphcszitqwku","baovglc","qmurcdzbhy","wucgnfmlsjz","kslongxrqhcmz","pgfvquewxncalksb","drqhje","parmfuzhdkvb","orfwcqbsv","uoq","iocesyphtzxvuwk","oisafxherlpvjd","xrbw","iktsg","dag","ifpyer","onerqivbwmjz","ia","kemzasyxndgjhoc","ukvj","celxkzuhwypbva","y","agejbtoqislvh","xiopwdtfkba","fqbihmywglxdnc","cjmeizw","ghzfqw","eylv","jbuylhnfk","pkyfr","rf","dyvhipqjmgrezaf","kcolxfmgnqvyz","nphgbcujmo","fqupgtrxvis","f","drishmtobjqcapv","exutnvc","pkzcqhmgnf","ycgqbdtsenmlhf","k","wtgerl","lqa","ku","i","ydlzsgfirbjx","owecuxrpm","i","ekr","tglokjeyc","ckmfij","coxekquhwmd","kfsdwcq","hnpymjovxue","twqyv","demvwrtcsiabglq","y","kvnqszx","g","ewtuijhxyo","mwhrsfxjgeb","dwxfbntusoa","lhiboak","kune","ow","awzpn","jqesgiuzrdpx","rijvynudo","ycvutdmgkroiexa","qvo","wupmsxni","rcpnhx","wsbcanhpe","sdelrbyxqukzmw","qhrygcuabnv","fruaynbsedwqxh","flyhcwnaoej","ni","rbtopmn","jvtdensy","few","dn","a","chg","h","tiwdrbp","tdm","qghetodvsjimbp","hymzfvgsobc","kdqstyjznvhapb","oem","lb","mhod","adjhexcpqmny","ljsiq","whgdyxmzcs","tc","vyquexhzlwirbo","gykq","qhmjgo","wmcrasnoxf","xzrbwvpefnoj","eyhaqspxvkrdcu","ncbtsvzfr","kwal","slfyi","fz","nzbdmr","akpdhycirg","ofrbxuc","ajkyobq","tkxhd","tjcxrw","qiruxdljayvw","xhvakznmibru","shgizj","mtgbuokycqjwz","lbodjf","xbgmzwslkup","ix","tefw","szlqbfcrvewxh","yugjdax","aekjsruy","womqkfdny","jgzw","lavbxr","lijybwtshfva","fwvlt","abhvjc","ub","qew","kwimvrfxsn","mldvjhbsxkfqtp","gfewmbh","oe","adurofqsiwcyek","mrahvpzxqo","gxtbcrjvnayquk","agdukwhevqynjl","fal","jzrvwinkusldbot","qnia","kwhuiacrvobp","ewmr","rmwdsvtgp","zctjunxidevybl","ckuexlrgpn","dh","dczbrilvhnwpaqt","ustilnpkfowzy","bknrejhxopmgzf","uzvteaj","xnkie","dxbtswmrekfvncu","yeuaxkilbcshopq","ax","suchdoxfbn","iegrpnd","qetwovbjs","kxrobvsuwzd","suwj","xsgdcavhoeyrznl","fo","vtpyhaowszmq","hfwonijbvdzxsua","onatjk","sau","dvbwoatyjsxpgefl","na","mglfynh","ywlkdcbnx","qwvojklutydran","aql","gdol","m","ufskachixjtmbd","kxlwg","klgmyuparhtox","fvshdugarpyejqzt","ejidg","uknhpsfqdotvjya","novyphxwj","blxps","d","kc","cnaroqj","qu","incfrutp","ci","dtugyziblrqh","dsfoquxevlarht","zwmnptjau","ytecmgvjf","maoictxvjus","uwhxytnv","tbmzpscehxkarwoi","ztxv","kigyjb","frlapn","wcveqlpj","arz","bfqkiatlmvsueo","jkepaqwimx","jefodwbt","xcnqwdhtlkmiryp","xulkbnq","ot","m","jchodig","wcqgmilbajzs","zekqsxwgfdjyblc","nmxavdocguybrtp","bkyczmptogqiu","mastzincjxqb","nzm","dxpfaoelg","hygbrxamzcov","b","pkgvdzsrcyo","whqopvdgexfntaz","iowrnxkltsv","f","nvcuymzwf","sxevmktrdyqpga","ulwzsntvhgo","fkvzgxbadmihc","kmferiap","gnpylhidxqvre","zfunlhxpajsmte","psomxbu","tpyz","vrbnpzicehqlk","vut","hmosw","wrcoegynlmihktq","ehujpgb","teurhbpola","te","qmhvgazpy","qn","xgkevnmujhbcw","cednjuyzfrk","bl","tvjsdkzgbfrnolx","o","jeszr","lf","pxmrstykena","etkaqgywb","xitepcoqmywnabr","phfeo","tuzkb","ltcpynmzkhe","qf","jceaqor","vikewzdsflayrh","amipvtk","bqjxfctm","xyuflbwdni","zjn","avnyhxtgcbmsj","fyxztlw","rhiksqzwbncdu","jnsgkmxz","mbhfu","unrqvayjeiocsld","ugb","iu","orjyfb","cfxyv","dkrzslecipt","rh","otuwqevildhsfpbj","lsxrizef","ufwl","vpbsgxlucam","zldruejvg","qdszvjpgh","omqlsijg","zrjsyimekutopv","tqiwgkjxhp","pmldfswutjenyo","juzltnvkgwm","istbrgxek","zsekjfihrbmdgtl","ntxlkarzsfvo","tfzmsyn","junvwaoiy","iuehozgtv","gwpfkry","jyuwpvil","zor","mrxfkeiguqcy","tlops","jvratnwemgupsl","ufvrzmts","dpkjsfmthglwic","bhkandtjwvgpr","gbcmstwonrvj","gnsxietuyvohjc","np","rpjyhckie","tj","fhoxkpinujs","boq","vlytmzbcj","nboyucs","f","tmkrbvcequgolsi","inthajrleycopd","mzpkoteqjfhgxr","wifjoezhqlaydrg","dufr","zsg","rafzbmldtkc","uamgpkrzet","eajgftqzl","ifkgbcwn","mbgqnsrv","thgewzbiufdp","ng","oszkxyeritnw","npvryhas","gqwpnlft","gtbsreykoi","ytcuaefbkwo","whv","indxwfc","zqi","snvihkaglfxp","zjlefovgdby","jlkwuacx","jzkocbnaismqdv","qxnz","fehcipdbnv","qwhpxnejfy","lrnwjz","jfduoehpxgs","md","dej","erbipdhgnquwjc","utyabgm","mrghpwtnaiqkfc","mlcoq","smxavtwkeizo","j","anjwekzo","gvsoqdbwnc","ribnmhugpt","zxqgtkh","lh","zvib","ianrw","ozekxhrdqpl","gdns","fxymzdjbthang","vynmo","segtfrnjzuvd","h","x","qlfwdxjzna","jmlrotpyhcuv","zfwsqrgxk","lmq","qwdifkjecshung","utdihflv","mnuvsawckq","ucakhswdtbn","oaedpl","rohtbfdxnzei","cu","vdlcw","tsgudkwo","ugijehftmalzv","ehmkjblipgv","n","bd","sgko","neb","qxbuingv","fcvtpjadqz","zqnrskbme","ldgxwijqnkrfcp","cnj","lcqxgyena","hufobzqekpxvldm","ctxn","ab","aolvmzespbrnjg","io","kbhwspg","jwhomcr","npfl","zidqsvpunjbyaxc","bav","tmwrjlsed","jzibvwcstlgrk","hizmbwqyge","onyxbergpvjul","o","noigbrtqzhuwpsdm","wgyoitnkacj","cleatwzurifgdxoj","ydprewfczknlt","yjiemrltqhkfzd","qbhe","y","uhgq","a","eptlxqmoairfyjds","pytesjdvo","ulajndfgx","knvpfcmldwbios","ejqxawcop","c","xhloesfqypb","j","yflgq","vcyu","chqztuvn","vmwubperxk","samxt","po","t","exfdpatnwosk","xcqonaptfmlsd","tlmayecdkisrpbz","hgyvzlbxetufjmw","fsgakpcndiuzeb","m","luevtfj","avguom","afqwnblsomk","qlozdybwcfnhk","fosmbqua","afdmrgsqwxvo","lzdfjtbqc","qhagb","qeimns","xnhrs","xdtwiymhskqoa","hfbgnwjuzevlkpr","by","ogtlerhvdmbi","epcdgwajviourbx","pdohxc","oxqkbethrlwnpma","pwdhq","tkgnzbhverafc","zlpbvitakqrf","ynbfxwpc","ygmxtiv","ybtpaudw","nagxrepfl","rvp","rhbiavct","vmqspyzfuw","ajex","fgjrad","zr","wzk","jk","rkqzmjabip","ditpyqoxwnzgja","ybsnciveoakjlmq","ywverqzmujginxc","czvrm","bazyusfmdtjgie","yhmlbrtxskuwqa","pnqgesyzuvwkt","ahpntv","kmgcndrfyzpoj","zobskapmlj"]\n```\n\n```\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n sw = {}\n \n for ss in startWords:\n sw[ss] = Counter(ss)\n \n \n S = set()\n \n for target in targetWords:\n counter_t = Counter(target)\n \n for ss in sw:\n if len(target) == len(ss) + 1 and len(counter_t.keys()) == len(sw[ss].keys()) + 1:\n s = sum([val for key, val in (sw[ss] & counter_t).items()])\n if s == len(ss):\n S.add(target)\n break\n\n return len(S)\n```
106,169
Count Words Obtained After Adding a Letter
count-words-obtained-after-adding-a-letter
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.
Array,Hash Table,String,Bit Manipulation,Sorting
Medium
Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords?
718
10
```python\n# Brute Force\n# O(S * T); S := len(startWors); T := len(targetWords)\n# TLE\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n cnt = 0\n for target in targetWords:\n for start in startWords:\n if len(target) - len(start) == 1 and len(set(list(target)) - set(list(start))) == 1:\n cnt += 1\n break\n return cnt\n\n# Sort + HashSet Lookup\n# O(S + T) Time\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n # Sort each start word and add it to a hash set\n startWords_sorted = set()\n # O(S*26*log(26))\n for word in startWords:\n startWords_sorted.add("".join(sorted(list(word))))\n \n # sort each target word and add it to a list\n # O(T*26*log(26))\n targetWords_sorted = []\n for word in targetWords:\n targetWords_sorted.append(sorted(list(word)))\n \n # for each sorted target word, we remove a single character and \n # check if the resulting word is in the startWords_sorted\n # if it is, we increment cnt and break the inner loop\n # otherwise we keep removing until we either find a hit or reach the\n # end of the string\n # O(T*26) = O(T)\n cnt = 0\n for target in targetWords_sorted:\n for i in range(len(target)):\n w = target[:i] + target[i+1:]\n w = "".join(w)\n if w in startWords_sorted:\n cnt += 1\n break\n \n return cnt\n\n# Using Bit Mask\n# O(S + T) Time\n# Similar algorithm as the one above, implemented using a bit mask to avoid the sorts\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n start_set = set()\n # O(S * 26)\n for word in startWords:\n m = 0\n for ch in word:\n i = ord(ch) - ord(\'a\')\n m |= (1 << i)\n start_set.add(m)\n \n # O(T * 2 * 26)\n cnt = 0\n for word in targetWords:\n m = 0\n for ch in word:\n i = ord(ch) - ord(\'a\')\n m |= (1 << i)\n \n for ch in word:\n i = ord(ch) - ord(\'a\')\n if m ^ (1 << i) in start_set:\n cnt += 1\n break\n return cnt\n```
106,176
Count Words Obtained After Adding a Letter
count-words-obtained-after-adding-a-letter
You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only. For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords. The conversion operation is described in the following two steps: Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords. Note that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.
Array,Hash Table,String,Bit Manipulation,Sorting
Medium
Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords?
462
6
Let M be the number of startWords, N be the number of targetWords and 26 is the number of characters.\nRuntime is O(M x 26) to generate the startWords set\nRuntime is O(N x 26) to look up the targetWords in the startWords set\nRuntime O(M+N)\n\nThe next natural step would be to not use a binary tuple to represent the word, but use actual bits of e.g. an INT. Principle is the same, implementation of createWordTuple differs.\n```\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n # represent chars in word with binary encoding "ca" = (1,0,1,...,0)\n def createWordTuple(word):\n ans = [0]*26\n for c in word:\n ans[ord(c) - ord(\'a\')] = 1\n return tuple(ans)\n \n # create set with binary encoded words\n words = set()\n for word in startWords:\n words.add(createWordTuple(word))\n \n # for each targetWord remove one char and look in the set whether \n # the reduced binary encoded character string is there\n ans = 0\n for word in targetWords:\n for i in range(len(word)):\n cutWord = word[:i] + word[i+1:]\n if createWordTuple(cutWord) in words:\n ans += 1\n break\n \n return ans\n```
106,186
Earliest Possible Day of Full Bloom
earliest-possible-day-of-full-bloom
You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each: From the beginning of day 0, you can plant the seeds in any order. Return the earliest possible day where all seeds are blooming.
Array,Greedy,Sorting
Hard
List the planting like the diagram above shows, where a row represents the timeline of a seed. A row i is above another row j if the last day planting seed i is ahead of the last day for seed j. Does it have any advantage to spend some days to plant seed j before completely planting seed i? No. It does not help seed j but could potentially delay the completion of seed i, resulting in a worse final answer. Remaining focused is a part of the optimal solution. Sort the seeds by their growTime in descending order. Can you prove why this strategy is the other part of the optimal solution? Note the bloom time of a seed is the sum of plantTime of all seeds preceding this seed plus the growTime of this seed. There is no way to improve this strategy. The seed to bloom last dominates the final answer. Exchanging the planting of this seed with another seed with either a larger or smaller growTime will result in a potentially worse answer.
1,247
5
```\nclass Solution:\n def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:\n comb=[(plantTime[i],growTime[i]) for i in range(len(plantTime))]\n mx,passed_days=0,0\n comb.sort(key=lambda x:(-x[1],x[0]))\n for i in range(len(plantTime)):\n mx=max(mx,(passed_days+comb[i][0]+comb[i][1]))\n passed_days+=comb[i][0]\n return mx\n```
106,210
Divide a String Into Groups of Size k
divide-a-string-into-groups-of-size-k
A string s can be partitioned into groups of size k using the following procedure: Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s. Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.
String,Simulation
Easy
Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group.
1,280
10
```\ndef divideString(self, s: str, k: int, fill: str) -> List[str]:\n l=[]\n if len(s)%k!=0:\n s+=fill*(k-len(s)%k)\n for i in range(0,len(s),k):\n l.append(s[i:i+k])\n return l\n```
106,278
Divide a String Into Groups of Size k
divide-a-string-into-groups-of-size-k
A string s can be partitioned into groups of size k using the following procedure: Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s. Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.
String,Simulation
Easy
Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group.
550
7
Understanding:\nSlice the strings in length of k, append them to a list. Check the length of the last item in the list, if its length is less than k then add the fill letter (length of last item - k) times\n\nAlgorithm:\n- Loop: from index 0 till index less than length of string\n- Append s[i:i+k] to list\n- Increment index by k\n- End loop\n- If length of last element in list is less than k then\n- Last element = last element + fill*(k-len(last element))\n- Return list\n\nPython code :\n```\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n l, i, N = [], 0, len(s)\n while i<N:\n l.append(s[i:i+k])\n i += k\n last = l[-1]\n if(len(last)<k):\n l[-1] += fill*(k-len(last))\n return l\n```
106,289
Divide a String Into Groups of Size k
divide-a-string-into-groups-of-size-k
A string s can be partitioned into groups of size k using the following procedure: Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s. Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.
String,Simulation
Easy
Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group.
283
5
Please check out this [commit]() for solutions of weekly 276. \n\n```\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n ans = []\n for i in range(0, len(s), k): \n ss = s[i:i+k]\n ans.append(ss + (k-len(ss))*fill)\n return ans \n```
106,296
All Divisions With the Highest Score of a Binary Array
all-divisions-with-the-highest-score-of-a-binary-array
You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright: The division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright. Return all distinct indices that have the highest possible division score. You may return the answer in any order.
Array
Medium
When you iterate the array, maintain the number of zeros and ones on the left side. Can you quickly calculate the number of ones on the right side? The number of ones on the right side equals the number of ones in the whole array minus the number of ones on the left side. Alternatively, you can quickly calculate it by using a prefix sum array.
717
5
\n# Python 3 \u2714\u2714 Linear Time Solution\n\n## Main Idea\nStep 1. Expand from **left to right** to calculate **0**s\nStep 2. Expand from **right to left** to calculate **1**s\nStep 3. Calculate Sum of zeroFromLeft and oneFromRight and return where maximum value\'s index\n## Complexity Analysis\n* Time: O(n) : Let *n* be nums\'s length\n* Space: O(n): Store zeroFromLeft and oneFromRight take O(n)\n\n\n## Code\n```\nclass Solution:\n def maxScoreIndices(self, nums: List[int]) -> List[int]:\n zeroFromLeft = [0] * (len(nums) + 1)\n oneFromRight = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n if nums[i] == 0:\n zeroFromLeft[i + 1] = zeroFromLeft[i] + 1\n else:\n zeroFromLeft[i + 1] = zeroFromLeft[i]\n \n for i in range(len(nums))[::-1]:\n if nums[i] == 1:\n oneFromRight[i] = oneFromRight[i + 1] + 1\n else:\n oneFromRight[i] = oneFromRight[i + 1]\n \n allSum = [0] * (len(nums) + 1)\n currentMax = 0\n res = []\n for i in range(len(nums) + 1):\n allSum[i] = oneFromRight[i] + zeroFromLeft[i]\n if allSum[i] > currentMax:\n res = []\n currentMax = allSum[i]\n if allSum[i] == currentMax:\n res.append(i)\n return res\n \n```\n\n* See more 2022 Daily Challenge Solution : [GitHub]()\n\n
106,320
Maximum Running Time of N Computers
maximum-running-time-of-n-computers
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously.
Array,Binary Search,Greedy,Sorting
Hard
For a given running time, can you determine if it is possible to run all n computers simultaneously? Try to use Binary Search to find the maximal running time
4,274
31
# Intuition\nWhen I first read this problem, I realized that it\'s not just about using each battery to its full capacity before moving on to the next. The goal here is to maximize the running time of all computers, and a simple linear approach would not achieve that. The challenge here lies in striking a balance between using batteries that have the most power and ensuring that no energy is wasted.\n\n## Video Explenation & Live Coding\n\n\n# Approach\nThe approach I took for this problem is to find a balance between using batteries that have the most power and ensuring that no energy is wasted. I employed a binary search strategy to locate the maximum possible running time.\n\nInitially, I set 1 as the left boundary and the total power of all batteries divided by \'n\' as the right boundary. This is because 1 is the minimum time a computer can run (given the constraints that battery power is at least 1) and `sum(batteries) / n` is the maximum time all computers can run if we could distribute the power of all batteries evenly among the computers.\n\nIn the binary search, I set a target running time and checked if we could reach this target with the available batteries. This check is done using the line of code `if sum(min(battery, target) for battery in batteries) >= target * n:`. \n\nThe expression `min(battery, target) for battery in batteries` calculates how much of each battery\'s power we can use to achieve the target running time. If a battery\'s power is more than the target, we can only use power equal to the target from it. If a battery\'s power is less than the target, we can use all of its power. The sum of these amounts is the total power we can use to achieve the target running time.\n\nIf this total power is greater than or equal to `target * n` (the total power needed to run all `n` computers for `target` time), it means we can achieve the target running time with the available batteries, so I update the left boundary to the target.\n\nIf we couldn\'t achieve the target running time (i.e., the total power is less than `target * n`), I update the right boundary to one less than the target. I continue this process until the left and right boundaries meet, at which point we\'ve found the maximum possible running time.\n\n# Complexity\n- Time complexity: The time complexity for this problem is \\(O(m log k)\\), where \\(m\\) is the length of the input array batteries and \\(k\\) is the maximum power of one battery.\n\n- Space complexity: The space complexity for this problem is \\(O(1)\\). During the binary search, we only need to record the boundaries of the searching space and the power extra, and the accumulative sum of extra, which only takes constant space.\n\n# Code\n```Python []\nclass Solution:\n def maxRunTime(self, n: int, batteries: List[int]) -> int:\n left, right = 1, sum(batteries) // n \n while left < right: \n target = right - (right - left) // 2 \n if sum(min(battery, target) for battery in batteries) >= target * n: \n left = target \n else: \n right = target - 1 \n return left \n```\n``` C++ []\nclass Solution {\npublic:\n long long maxRunTime(int n, std::vector<int>& batteries) {\n std::sort(batteries.begin(), batteries.end());\n long long left = 1, right = std::accumulate(batteries.begin(), batteries.end(), 0LL) / n;\n while (left < right) {\n long long target = right - (right - left) / 2;\n long long total = std::accumulate(batteries.begin(), batteries.end(), 0LL, [&target](long long a, int b) { return a + std::min(static_cast<long long>(b), target); });\n if (total >= target * n) {\n left = target;\n } else {\n right = target - 1;\n }\n }\n return left;\n }\n};\n```\n``` Java []\npublic class Solution {\n public long maxRunTime(int n, int[] batteries) {\n Arrays.sort(batteries);\n long left = 1, right = (long)Arrays.stream(batteries).asLongStream().sum() / n;\n while (left < right) {\n long target = right - (right - left) / 2;\n long total = Arrays.stream(batteries).asLongStream().map(battery -> Math.min(battery, target)).sum();\n if (total >= target * n) {\n left = target;\n } else {\n right = target - 1;\n }\n }\n return left;\n }\n}\n```\n``` C# []\npublic class Solution {\n public long MaxRunTime(int n, int[] batteries) {\n Array.Sort(batteries);\n long left = 1, right = (long)batteries.Sum(b => (long)b) / n;\n while (left < right) {\n long target = right - (right - left) / 2;\n long total = batteries.Sum(battery => Math.Min((long)battery, target));\n if (total >= target * n) {\n left = target;\n } else {\n right = target - 1;\n }\n }\n return left;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number} n\n * @param {number[]} batteries\n * @return {number}\n */\nvar maxRunTime = function(n, batteries) {\n batteries.sort((a, b) => a - b);\n let left = 1, right = Math.floor(batteries.reduce((a, b) => a + b) / n);\n while (left < right) {\n let target = right - Math.floor((right - left) / 2);\n let total = batteries.reduce((a, b) => a + Math.min(b, target), 0);\n if (total >= target * n) {\n left = target;\n } else {\n right = target - 1;\n }\n }\n return left;\n};\n``` \n## Video Python & JavaScript\n\n \n \n
106,409
Maximum Running Time of N Computers
maximum-running-time-of-n-computers
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously.
Array,Binary Search,Greedy,Sorting
Hard
For a given running time, can you determine if it is possible to run all n computers simultaneously? Try to use Binary Search to find the maximal running time
934
6
\n```\nclass Solution:\n def maxRunTime(self, n: int, batteries: List[int]) -> int:\n left=0\n right=sum(batteries)//n+1\n def check(time):\n return sum(min(time,b) for b in batteries)>=n*time\n\n while left<=right:\n mid=(left+right)//2\n if check(mid):\n left=mid+1\n\n else:\n right=mid-1\n\n return right \n```
106,410
Maximum Running Time of N Computers
maximum-running-time-of-n-computers
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously.
Array,Binary Search,Greedy,Sorting
Hard
For a given running time, can you determine if it is possible to run all n computers simultaneously? Try to use Binary Search to find the maximal running time
16,400
333
# **Intuition**\nThe staright idea, is to use all baterial evenly.\nSo we take advantage of all the energy wihout any left.\nIn this case, we can run up to `sum(A) / n` minutes.\nThis average value is an upper bounde of the final result.\nIt\'s great to start with this enviromental intuition.\n\n# **Explanation**\nHowever, there may be some betteries that has too much energy.\nThey are in charge all the time,\nbut still can\'t run out all they have,\nthen their energy wastes.\n\n\nSo we can compare the average value with the most powerful battery `max(A)`.\nIf `max(A)` is bigger, then we can use this battery to charge a computer all the time.\nNow we reduce the problem to the left bettery and `n - 1` computers.\n\nWe continue doing this process,\nuntil the most powerful bettery `max(A)` can not run average time `sum(A) / n`.\nThen the left betteries can help each other and be use evenly until the end.\nOne key point of this problem, it\'s to find out, why betteries can be used "evenly" in this situation.\n\nOne quick "prove" is that, the `max(A)` is smaller than the running time, \nso the maximum battery won\'t get wasted,\nthe other smaller betteries won\'t even get easted.\n<br>\n\n# **Complexity**\nTime `O(sort)`\nSpace `O(sort)`\n\nThe best solution can be `O(A)`, similar to quick select algo.\n<br>\n\n**Java**\n```java\n public long maxRunTime(int n, int[] A) {\n Arrays.sort(A);\n long sum = 0;\n for (int a: A)\n sum += a;\n int k = 0, na = A.length;\n while (A[na - 1 - k] > sum / (n - k))\n sum -= A[na - 1 - k++];\n return sum / (n - k);\n }\n```\n\n**C++**\n```cpp\n long long maxRunTime(int n, vector<int>& A) {\n sort(A.begin(), A.end());\n long long sum = accumulate(A.begin(), A.end(), 0L);\n int k = 0, na = A.size();\n while (A[na - 1 - k] > sum / (n - k))\n sum -= A[na - 1 - k++];\n return sum / (n - k);\n }\n```\n\n**Python**\n```py\n def maxRunTime(self, n, A):\n A.sort()\n su = sum(A)\n while A[-1] > su / n:\n n -= 1\n su -= A.pop()\n return su / n\n```\n
106,452
Maximum Running Time of N Computers
maximum-running-time-of-n-computers
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. Note that the batteries cannot be recharged. Return the maximum number of minutes you can run all the n computers simultaneously.
Array,Binary Search,Greedy,Sorting
Hard
For a given running time, can you determine if it is possible to run all n computers simultaneously? Try to use Binary Search to find the maximal running time
211
16
# Python | 6 Lines of Code | Easy to Understand | Hard Problem | 2141. Maximum Running Time of N Computers\n```\nclass Solution:\n def maxRunTime(self, n: int, batteries: List[int]) -> int:\n batteries.sort()\n total = sum(batteries)\n while batteries[-1] > total//n:\n n -= 1\n total -= batteries.pop()\n return total//n\n```
106,457
Minimum Sum of Four Digit Number After Splitting Digits
minimum-sum-of-four-digit-number-after-splitting-digits
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2.
Math,Greedy,Sorting
Easy
Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place.
9,106
61
Please upvote if you like my solution. Let me know in the comments if you have any suggestions to increase performance or readability. \n\n**Notice** that:\n1. We do not need to generate all possible combinations of spliting the input into two numbers. In the ideal solution, num1 and num2 will always be of equal length.\n2. We will step by step build num1 and num2 as we go through the algorithm. It is not necessary to generate all combinations of num1 and num2 (with both numbers having equal length).\n3. We do not need to save num1 and num2 in a variable. We can keep adding to the total sum as we go through the algorithm. \n4. The algorithm below works for any input length. If you want you can simplify it, since you know the input length is 4. \n\n**My algorithm** goes as follows:\n1. convert the input into a list of digits\n2. sort the list of digits in descending order\n3. iterate through the list of digits\n3.1 with each iteration, multiply the current digit with 10*current position in num1/num2. \n3.2 add the current digit to the result\n3.3 if you already added an even number of digits to the total of results, then increase the current position by one\n4. return result\n\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n num = sorted(str(num),reverse=True)\n n = len(num) \n res = 0\n even_iteration = False\n position = 0\n for i in range(n):\n res += int(num[i])*(10**position)\n if even_iteration:\n position += 1\n even_iteration = False\n else:\n even_iteration = True\n return res\n```\n\nif you know that the input is going to be exaclty 4 digits, you can simplify it:\n\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n num = sorted(str(num),reverse=True)\n return int(num[0]) + int(num[1]) + int(num[2])*10 + int(num[3])*10\n```\n
106,477
Minimum Sum of Four Digit Number After Splitting Digits
minimum-sum-of-four-digit-number-after-splitting-digits
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2.
Math,Greedy,Sorting
Easy
Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place.
1,727
14
```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n d = sorted(str(num))\n return int(d[0] + d[2]) + int(d[1] + d[3])\n\n```
106,479
Minimum Sum of Four Digit Number After Splitting Digits
minimum-sum-of-four-digit-number-after-splitting-digits
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2.
Math,Greedy,Sorting
Easy
Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place.
1,138
5
\n\n# Code\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n l=[]\n while num != 0:\n l.append(num % 10)\n num = num // 10\n \n l.sort()\n res = (l[1] * 10 + l[2]) + (l[0] * 10 + l[3])\n return res\n```
106,489
Minimum Sum of Four Digit Number After Splitting Digits
minimum-sum-of-four-digit-number-after-splitting-digits
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2.
Math,Greedy,Sorting
Easy
Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place.
763
8
# 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 minimumSum(self, num: int) -> int:\n string=str(num)\n s=sorted(string)\n m=s[0]+s[2]\n n=s[1]+s[3]\n return (int(m)+int(n))\n#please upvote me it would encourage me alot\n \n```
106,494
Minimum Sum of Four Digit Number After Splitting Digits
minimum-sum-of-four-digit-number-after-splitting-digits
You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. Return the minimum possible sum of new1 and new2.
Math,Greedy,Sorting
Easy
Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place.
580
5
# Code\n```\nclass Solution:\n def minimumSum(self, num: int) -> int:\n nums=list(str(num))\n nums.sort()\n return int(nums[0]+nums[-1])+int(nums[1]+nums[2])\n \n```
106,498
Partition Array According to Given Pivot
partition-array-according-to-given-pivot
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Return nums after the rearrangement.
Array,Two Pointers,Simulation
Medium
Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result?
4,528
22
### 1. Stable Partition\n**C++**\n```c++\nvector<int> pivotArray(vector<int>& n, int p) {\n stable_partition(stable_partition(begin(n), end(n), [&](int n){ return n < p; }), end(n), [&](int n){ return n == p; });\n return n;\n}\n```\n### 2. 3 passes, 1 array\n**Python 3**\n```python\nclass Solution:\n def pivotArray(self, nums: List[int], p: int) -> List[int]:\n return [n for n in nums if n < p] + [n for n in nums if n == p] + [n for n in nums if n > p]\n```\n\n**C++**\n```cpp\nvector<int> pivotArray(vector<int>& n, int p) {\n vector<int> res;\n copy_if(begin(n), end(n), back_inserter(res), [&](int n){ return n < p; });\n copy_if(begin(n), end(n), back_inserter(res), [&](int n){ return n == p; });\n copy_if(begin(n), end(n), back_inserter(res), [&](int n){ return n > p; });\n return res;\n}\n```\n\n### 3. 1.5 pass, 3 arrays\nFirst pass is to populate 3 arrays. We also need another pass (0.5 elements in average) to merge those arrays.\n**C++**\n```cpp\nvector<int> pivotArray(vector<int>& n, int p) {\n vector<int> res[3] = {};\n for (int n : n)\n res[n < p ? 0 : n == p ? 1 : 2].push_back(n);\n res[0].insert(end(res[0]), begin(res[1]), end(res[1]));\n res[0].insert(end(res[0]), begin(res[2]), end(res[2]));\n return res[0];\n}\n```\n### 4. 2 passes, 1 array\nCount numbers less than, and equal to the pivot. \n\nThose counts define positions where we insert numbers equal to the pivot (`eq`) and greater than the pivot (`hi`). The numbers smaller than the pivot (`lo`) are filled starting from `0`, obviously :)\n**C++**\n```cpp\nvector<int> pivotArray(vector<int> &n, int p) {\n\tvector<int> res(n.size());\n\t int lo = 0, eq = count_if(begin(n), end(n), [&](int n) { return n < p; }),\n\t\t hi = eq + count(begin(n), end(n), p);\n\t for (int n : n)\n\t\tres[n < p ? lo++ : n == p ? eq++ : hi++] = n;\n\treturn res;\n}\n```
106,543
Minimum Cost to Set Cooking Time
minimum-cost-to-set-cooking-time
A generic microwave supports cooking times for: To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time. Remember that one minute consists of 60 seconds.
Math,Enumeration
Medium
Define a separate function Cost(mm, ss) where 0 <= mm <= 99 and 0 <= ss <= 99. This function should calculate the cost of setting the cocking time to mm minutes and ss seconds The range of the minutes is small (i.e., [0, 99]), how can you use that? For every mm in [0, 99], calculate the needed ss to make mm:ss equal to targetSeconds and minimize the cost of setting the cocking time to mm:ss Be careful in some cases when ss is not in the valid range [0, 99].
5,566
108
**Explanation**: \n* The maximum possible minutes are: `targetSeconds` / 60\n* Check for all possible minutes from 0 to `maxmins` and the corresponding seconds\n* `cost` function returns the cost for given minutes and seconds\n* `moveCost` is added to current cost if the finger position is not at the correct number\n* `pushCost` is added for each character that is pushed\n* Maintain the minimum cost and return it\n\n*Note*: We are multiplying `mins` by 100 to get it into the format of the microwave\nLet\'s say `mins` = 50,`secs` = 20\nOn the microwave we want 5020\nFor that we can do: 50 * 100 + 20 = 5020\n<iframe src="" frameBorder="0" width="780" height="420"></iframe>\n\nOn further inspection we can deduce that we only really have 2 cases:\n`maxmins`, `secs`\n`maxmins - 1`, `secs + 60`\n<iframe src="" frameBorder="0" width="780" height="370"></iframe>\n\nSince maximum length of characters displayed on microwave = 4, `Time Complexity = O(1)`
106,560
Minimum Cost to Set Cooking Time
minimum-cost-to-set-cooking-time
A generic microwave supports cooking times for: To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example, You are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue. There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost. Return the minimum cost to set targetSeconds seconds of cooking time. Remember that one minute consists of 60 seconds.
Math,Enumeration
Medium
Define a separate function Cost(mm, ss) where 0 <= mm <= 99 and 0 <= ss <= 99. This function should calculate the cost of setting the cocking time to mm minutes and ss seconds The range of the minutes is small (i.e., [0, 99]), how can you use that? For every mm in [0, 99], calculate the needed ss to make mm:ss equal to targetSeconds and minimize the cost of setting the cocking time to mm:ss Be careful in some cases when ss is not in the valid range [0, 99].
853
10
```\nclass Solution:\n def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:\n def count_cost(minutes, seconds): # Calculates cost for certain configuration of minutes and seconds\n time = f\'{minutes // 10}{minutes % 10}{seconds // 10}{seconds % 10}\' # mm:ss\n time = time.lstrip(\'0\') # since 0\'s are prepended we remove the 0\'s to the left to minimize cost\n t = [int(i) for i in time]\n current = startAt\n cost = 0\n for i in t:\n if i != current:\n current = i\n cost += moveCost\n cost += pushCost\n return cost\n ans = float(\'inf\')\n for m in range(100): # Check which [mm:ss] configuration works out\n for s in range(100):\n if m * 60 + s == targetSeconds: \n ans = min(ans, count_cost(m, s))\n return ans\n```
106,565
Count Elements With Strictly Smaller and Greater Elements
count-elements-with-strictly-smaller-and-greater-elements
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Array,Sorting
Easy
All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why?
1,558
22
Understanding: \nElements that are both smaller than max and greater than min will be included in the count.\n\nAlgorithm:\n- Find minimum and maximum element\n- Loop through the array and increase count every time the element lies between the min and max of the array\n- Return count\n\nPython code :\n```\nclass Solution:\n def countElements(self, nums: List[int]) -> int:\n M = max(nums)\n m = min(nums)\n return sum(1 for i in nums if m<i<M)\n```
106,677
Count Elements With Strictly Smaller and Greater Elements
count-elements-with-strictly-smaller-and-greater-elements
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Array,Sorting
Easy
All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why?
387
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n## Code\n```\nclass Solution:\n def countElements(self, nums: List[int]) -> int:\n maxval=max(nums)\n minval=min(nums)\n while maxval in nums:\n nums.remove(maxval)\n while minval in nums:\n nums.remove(minval)\n return len(nums)\n #please do upvote it would be encouraging to post more solutions.\n\n```\n## Consider upvoting if found helpful\n \n![4m44lc.jpg]()\n\n
106,686
Count Elements With Strictly Smaller and Greater Elements
count-elements-with-strictly-smaller-and-greater-elements
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Array,Sorting
Easy
All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why?
716
13
```\nclass Solution:\n def countElements(self, nums: List[int]) -> int:\n res = 0\n mn = min(nums)\n mx = max(nums)\n for i in nums:\n if i > mn and i < mx:\n res += 1\n return res\n```
106,687
Count Elements With Strictly Smaller and Greater Elements
count-elements-with-strictly-smaller-and-greater-elements
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Array,Sorting
Easy
All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why?
575
8
**Python :**\n\n```\ndef countElements(self, nums: List[int]) -> int:\n\tmin_ = min(nums)\n\tmax_ = max(nums)\n\n\treturn sum(1 for i in nums if min_ < i < max_)\n```\n\n**Like it ? please upvote !**
106,693
Count Elements With Strictly Smaller and Greater Elements
count-elements-with-strictly-smaller-and-greater-elements
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Array,Sorting
Easy
All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why?
445
5
find the max and min values in the nums, and count the value that strictly in the range (min, max).\n\n```python\nclass Solution:\n def countElements(self, nums: List[int]) -> int:\n lo, hi = min(nums), max(nums)\n return sum(1 for x in nums if lo<x<hi)\n```
106,699
Find All Lonely Numbers in the Array
find-all-lonely-numbers-in-the-array
You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array. Return all lonely numbers in nums. You may return the answer in any order.
Array,Hash Table,Counting
Medium
For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map.
4,822
49
**Python 3**\n```python\nclass Solution:\n def findLonely(self, nums: List[int]) -> List[int]:\n m = Counter(nums)\n return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0]\n```\n\n**C++**\n```cpp\nvector<int> findLonely(vector<int>& nums) {\n unordered_map<int, int> m;\n vector<int> res;\n for (int n : nums)\n ++m[n];\n for (const auto [n, cnt] : m)\n if (cnt == 1 && m.count(n + 1) == 0 && m.count(n - 1) == 0)\n res.push_back(n);\n return res;\n}\n```
106,719
Maximum Good People Based on Statements
maximum-good-people-based-on-statements
There are two types of persons: You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n. Return the maximum number of people who can be good based on the statements made by the n people.
Array,Backtracking,Bit Manipulation,Enumeration
Hard
You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum.
3,387
77
I recommend checking this problem first: \nLook for *Approach 3: Lexicographic (Binary Sorted) Subsets*\n\n* We are going to generate every possible permutation of good and bad people\n* Then we check if this permutation satisfies the given constraints\n\nPermutation representation in binary:\n\n>111 : 0 -> good, 1 -> good, 2 -> good\n110 : 0 -> good, 1 -> good, 2 -> bad\n101 : 0 -> good, 1 -> bad, 2 -> good\n011 : 0 -> bad, 1 -> good, 2 -> good\n100 : 0 -> good, 1 -> bad, 2 -> bad\n... and so on.\n\nWith 3 people we will have 8 permutations(2<sup>n</sup>)\nWith 4 people we will have 16 permutations\n\n>For n = 3:\nLower limit: 1 << n = 2<sup>n</sup> = 8 = 1000\nUpper limit: 1 << (n + 1) - 1 = 2<sup>n+1</sup> - 1 = 16 - 1 = 15 = 1111\nInteger.toBinaryString(8).substring(1): 000\nInteger.toBinaryString(9).substring(1): 001\n...\nInteger.toBinaryString(15).substring(1): 111\n\nTo check if our permutation satisfies the constraints, we check if the statements of good people in our permutation are making any contradictions. If they are, this permutation will not hold and we can return false.\n\nIf our `permutation` satisfies the given constraints, count the number of ones in our `permutation`.\nPermutation with maximum ones is the answer. \n\n<iframe src="" frameBorder="0" width="700" height="460"></iframe>\n\n*Time Complexity*: O(n<sup>2</sup> * 2<sup>n</sup>)\n
106,813
Maximum Good People Based on Statements
maximum-good-people-based-on-statements
There are two types of persons: You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n. Return the maximum number of people who can be good based on the statements made by the n people.
Array,Backtracking,Bit Manipulation,Enumeration
Hard
You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum.
540
7
```\nclass Solution:\n def maximumGood(self, statements: List[List[int]]) -> int:\n good = set()\n def backTracking(i):\n if i == len(statements):\n return 0\n good.add(i) #Cosider i as good\n mxmGood = float(\'-inf\')\n found = 0\n for j in range(i):\n if (statements[i][j] == 1 and j not in good) or (statements[i][j] == 0 and j in good) or (j in good and statements[j][i] == 0):\n found = 1\n break\n if not found:\n mxmGood= max(mxmGood, 1 + backTracking(i+1))\n good.remove(i) #Consider i as bad\n found = 0\n for j in range(i):\n if (j in good and statements[j][i] == 1):\n found = 1\n break\n if not found:\n mxmGood= max(mxmGood, backTracking(i+1))\n return mxmGood\n return backTracking(0)\n \n```
106,819
Maximum Good People Based on Statements
maximum-good-people-based-on-statements
There are two types of persons: You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following: Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n. Return the maximum number of people who can be good based on the statements made by the n people.
Array,Backtracking,Bit Manipulation,Enumeration
Hard
You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum.
378
5
# Algorithm\nWe have a `statements` matrix of size n by n made up of elements 0,1,2 where \n- `statements[i][j]=1` means `person i` thinks `person j` is good.\n- `statements[i][j]=0` means `person i` thinks `person j` is bad.\n- `statements[i][j]=2` means `person i` doesnt comment on `person j`.\n\nWe also have these conditions:\n- Good person speaks truth always\n- Bad person can say truth or lie\n\nWe want to assign either 1 (for good) and 0 (for bad) to all persons in `0,1,..n-1` such that the `statements` matrix is feasible.\n\n## Pseudocode\nNow let us write our pseudocode to validate an assignment:\n```\nFOR i in 0,..,n-1\n\tFOR j in 0,..,n-1\n\t\t\tIF person i is good AND person j \u2260 statement of person i on person j\n\t\t\t\tRETURN False\nRETURN True\n```\nWe simply need to run this for all possible assignments and if the assignment is valid we count the number of ones. At the end we return the maximum number of ones out of all valid assignments.\n\n## Bitmask\nNow, to use bitmask, let us have some notation:\nWe have `2^n` ways of doing the assignment (each person can be either good or bad). Let us denote an assignment as a variable caleld `number` which is in the range `[0,2^n-1]`. If ith digit from left is 1 then in our assignment person i is assigned good and if ith digit from left is 0 then in our assignment person i is assigned bad.\nFor example say n is 3. The we can have 0,1,2,3,4,5,6,7 as possible assignments.\n0 in binary is `000` so means all bad\n1 in binary is `001` so means (0,1) are bad and 2 is good\n5 in binary is `101` so means (0,2) are good, 1 is bad\nand so on.\n\nNow let us write some logic we are gonna use later:\n#### How do we find if in our assignment ith person is assigned good or bad?\nFor exampel say our assignment is 5 ie `101`. Then\n- `5 & 4 > 0` means person 0 is assigned 1 ie good\n- `5 & 2 == 0` means person 1 is assigned 0 ie bad\n- `5 & 1 > 0` means person 2 is assigned 1 ie good\n\nBasically it is just a way of iterating over the binary representation of the number.\n\nNow that we have all the pieces let us write the code:\n\n<iframe src="" frameBorder="0" width="800" height="500"></iframe>\n\nTime complexity: O((n^2 )* (2^n))\nSpace complexity: O(1)\n\nThis solution beats 80% of the solutions in terms of runtime and beats 95% of solutions in terms of memory. Please upvote if you found this helpful.
106,826
Find Substring With Given Hash Value
find-substring-with-given-hash-value
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string.
String,Sliding Window,Rolling Hash,Hash Function
Hard
How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method.
9,230
180
# **Intuition**\nGood time to learn rolling hash.\nwhat\'s hash?\nThe definition `hash(s, p, m)` in the description is the hash of string `s` based on `p`.\n\nwhat\'s rolling hash?\nThe hash of substring is a sliding window.\nSo the basis of rolling hash is sliding window.\n\n\n# **Explanation**\nCalculate the rolling hash backward.\nIn this process, we slide a window of size `k` from the end to the begin.\n\nFirstly calculate the substring hash of the last `k` characters,\nthen we add one previous backward and drop the last characters.\n\nWhy traverse from end instead of front?\nBecause `cur` is reminder by mod `m`,\n`cur = cur * p` works easier.\n`cur = cur / p` doesn\'r work easily.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public String subStrHash(String s, int p, int m, int k, int hashValue) {\n long cur = 0, pk = 1;\n int res = 0, n = s.length();\n for (int i = n - 1; i >= 0; --i) {\n cur = (cur * p + s.charAt(i) - \'a\' + 1) % m;\n if (i + k >= n)\n pk = pk * p % m;\n else\n cur = (cur - (s.charAt(i + k) - \'a\' + 1) * pk % m + m) % m;\n if (cur == hashValue)\n res = i;\n }\n return s.substring(res, res + k);\n }\n```\n**C++**\n```cpp\n string subStrHash(string s, int p, int m, int k, int hashValue) {\n long long cur = 0, res = 0, pk = 1, n = s.size();\n for (int i = n - 1; i >= 0; --i) {\n cur = (cur * p + s[i] - \'a\' + 1) % m;\n if (i + k >= n)\n pk = pk * p % m;\n else\n cur = (cur - (s[i + k] - \'a\' + 1) * pk % m + m) % m;\n if (cur == hashValue)\n res = i;\n }\n return s.substr(res, k);\n }\n```\n**Python**\n```py\n def subStrHash(self, s, p, m, k, hashValue):\n def val(c):\n return ord(c) - ord(\'a\') + 1\n \n res = n = len(s)\n pk = pow(p,k,m)\n cur = 0\n\n for i in xrange(n - 1, -1, -1):\n cur = (cur * p + val(s[i])) % m\n if i + k < n:\n cur = (cur - val(s[i + k]) * pk) % m\n if cur == hashValue:\n res = i\n return s[res: res + k]\n```\n
106,909
Find Substring With Given Hash Value
find-substring-with-given-hash-value
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string.
String,Sliding Window,Rolling Hash,Hash Function
Hard
How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method.
4,284
76
Computing hash for each substring will result in O(nk) complexity - too slow.\n\nRolling hash (Rabin-Karp algorithm) works for sub-strings of the same size, and computes `hash` for the next string in O(1):\n- Add `i + 1` character: multiply `hash` by `power` and add `val(s[i + 1])`.\n\t- This is because \n\t\t- `s[1] * p^k + s[2] * p^(k-1) + s[3] * p^(k-2) ... + s[k - 1] * p + s[k]` \n\t- can be written as \n\t\t- `(...((s[1] * p + s[2]) * p + s[3]) * p ... + s[k - 1]) * p + s[k]`\n- Remove `i + 1 - k` character: subtract `val(s[i + 1 - k]) * power ^ k` from `hash`.\n\nGotchas:\n1. The value of `a` is `1`, not `0`.\n2. The `hashValue` is computed by rolling the hash right-to-left, so we need to do the same.\n3. We need to roll all the way to zero because we need to return the first matching string from the left.\n4. Make sure we do not go negative when subtracting (add `mod` and make sure the subtracted value is less than `mod`).\n\n> Why can\'t we go left-to-right, and use inverse modulo to do the division? The reason is that inverse modulo may not exist for a given power and modulo. See approach 2 below.\n\n**C++**\n```cpp\nstring subStrHash(string s, int power, int mod, int k, int hashValue) {\n long long hash = 0, res = 0, power_k = 1;\n auto val = [&](int i){ return s[i] - \'`\'; };\n for (int i = s.size() - 1; i >= 0; --i) {\n hash = (hash * power + val(i)) % mod;\n if (i < s.size() - k)\n hash = (mod + hash - power_k * val(i + k) % mod) % mod;\n else\n power_k = power_k * power % mod;\n if (hash == hashValue)\n res = i; \n }\n return s.substr(res, k);\n}\n```\n**Python 3**\n```python\nclass Solution:\n def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str:\n val = lambda ch : ord(ch) - ord("a") + 1\n hash, res, power_k = 0, 0, pow(power, k, mod)\n for i in reversed(range(len(s))):\n hash = (hash * power + val(s[i])) % mod\n if i < len(s) - k:\n hash = (mod + hash - power_k * val(s[i + k]) % mod) % mod\n res = i if hash == hashValue else res\n return s[res:res + k]\n```\n\n#### Approach 2: Inverse Modulo\nBecause inverse modulo only exists if `gcd(power, mod) == 1`, we need to fall back to the right-to-left solution for some test cases.\n\nEven with this fallback, the solution below is 50% faster than the one above. Perhaps there are many test cases where the first substring is close to the left.\n\n**Python 3**\n```python\nclass Solution:\n def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str:\n val = lambda ch : ord(ch) - ord("a") + 1\n hash, res, pow_k, pow_k_1 = 0, 0, pow(power, k, mod), pow(power, k - 1, mod)\n if gcd(power, mod) == 1:\n inverse = pow(power, -1, mod)\n for i in range(len(s)):\n if (i >= k):\n hash = (mod + hash - val(s[i - k])) % mod\n hash = (hash * inverse + val(s[i]) * pow_k_1) % mod\n if i + 1 >= k and hash == hashValue:\n return s[i + 1 - k : i + 1] \n else:\n for i in reversed(range(len(s))):\n hash = (hash * power + val(s[i])) % mod\n if i < len(s) - k:\n hash = (mod + hash - pow_k * val(s[i + k]) % mod) % mod\n res = i if hash == hashValue else res\n return s[res:res + k]\n```
106,911
Find Substring With Given Hash Value
find-substring-with-given-hash-value
The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string.
String,Sliding Window,Rolling Hash,Hash Function
Hard
How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method.
455
6
```\nclass Solution:\n def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:\n \'\'\'\n Use Sliding window and rolling hash to find the first substring \n that has same hash value as provided `hashValue`.\n \n Time: O(n)\n Space: O(n)\n \'\'\'\n \n # generate val list for each letter\n vals = [ord(c) - ord(\'a\') + 1 for c in s]\n \n # gradually build `powers` by multiply `power` instead of using `**`\n # which is very slow and will cause TLE.\n # Or use pow(x, y, z). Ref: \n \n # powers = [1] * k\n # for i in range(1, k):\n # powers[i] = (powers[i-1] * power) % modulo\n powers = [pow(power, i, modulo) for i in range(k)]\n \n n = len(s)\n # initial hash_value for the last substring with length n\n hash_value = sum(vals[n - k + i] * powers[i] for i in range(k))\n # set idx with the beginning of the last substring with length n\n idx = n - k\n # moving backwards to calculate new hash value\n # because moving backwards you can just `* power`\n # moving forward will involve `//`, which is difficult for modulo\n for i in range(n-k-1, -1, -1):\n # update hash_value by removing the last index (i+k), \n # and multiply the rest by power since each remaining characters\' indices increase by 1 for new substring\n # and add the newcoming vals[i] * powers[0] (which is 1 and could be omitted)\n hash_value = ((hash_value - vals[i+k] * powers[k-1]) * power + vals[i] ) % modulo\n # keep updating idx since we are moving to the left\n # and trying to find the first substring that has the same hash value as `hashValue`\n if hash_value == hashValue:\n idx = i\n return s[idx:idx+k]\n```
106,922
Groups of Strings
groups-of-strings
You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words. Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true: Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where:
String,Bit Manipulation,Union Find
Hard
Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to node i?
2,668
14
# **Explanation**\nFor each word `w = words[i]`, calculate it\'s characters bitmask `x`.\nSet the mapping `m.setdefault(x, i)`, so we can find the index of first word with bitmask `x`.\n`f[i]` is the "father" of `i`, which we will use for union find.\n\nNow for word `w` with bitmask `x`,\nwe will find all its `connected` bitmask `y`,\nwhere the helper function `connected` generates all connected bitmasks.\n\nIf `y` already in the mapping `m`, \nwe union their root parents.\n\nIn the end, we count the number of union and the size of biggest union.\n<br>\n\n# **Complexity**\nTime `O(n * 26 * 26)`\nSpace `O(n * 26)`\nTime can be improved to `O(n * 26)`.\nSeems python hardly pass with `O(n * 26 * 26)`.\n<br>\n\n**Python**\n```py\n def groupStrings(self, words):\n n = len(words)\n m = {}\n f = []\n \n def find(x):\n if x != f[x]:\n f[x] = find(f[x])\n return f[x]\n \n def connected(x):\n for i in xrange(26):\n yield x ^ (1 << i)\n if (x & (1 << i)) > 0:\n for j in xrange(26):\n if x & (1 << j) == 0:\n yield x ^ (1 << i) ^ (1 << j)\n\n for i,w in enumerate(words):\n x = sum(1 << (ord(c) - ord(\'a\')) for c in w)\n f.append(m.setdefault(x, i))\n for y in connected(x):\n if y in m:\n i, j = find(m[x]), find(m[y])\n if i != j:\n f[i] = j\n\n count = collections.Counter(find(i) for i in range(n))\n return [len(count), max(count.values())]\n```\n
106,963
Groups of Strings
groups-of-strings
You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words. Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true: Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where:
String,Bit Manipulation,Union Find
Hard
Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to node i?
692
14
Use Union-Find to connect two words, if they are connected based on these three operations.\n\nFor example, \n- by operation **add**, string **a** can be transformed to **ab**, **ac**, ... , **az**.\n- by operation **delete**, string **abc** can be transformed to **ab**, **ac**, **bc**.\n- by operation **replace**, string **abc** can be transformed to **bce**, **bcf**, ... , **acz**.\n![image]()\n\nMore specifically, **replace** equals **delete** + **add**.\n\n![image]()\n\nTherefore, a current word **abc** can be potentially connected to all those words (As shown below). \nImagine we also have **acz** in the string list, thus **abc** and **acz** are connected! \n\n![image]()\n\n\nTherefore, we can count the number of groups and the group size. However, I \n\n>For example, given the input:\n **["web","a","te","hsx","v","k","a","roh"]**\n we group them like below.\n\n![image]()\n\nNotice that there might be duplicated words, thus we can use a counter for the number of occurrence of each word, and calculate the group size based on the frequency of each word.\n\nFor example: The size of green group is: 1 + 1 + 2 = 4\n\n![image]()\n\n\n\n\n**Python**\n```\nclass DSU:\n def __init__(self, n):\n self.root = list(range(n))\n def find(self, x):\n if self.root[x] != x:\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n def union(self, x, y):\n self.root[self.find(x)] = self.find(y)\n\nclass Solution:\n def groupStrings(self, A: List[str]) -> List[int]: \n c = collections.defaultdict(int)\n for a in A: \n\t\t\tc["".join(sorted(a))] += 1\n \n A = list(set(["".join(sorted(a)) for a in A]))\n n = len(A)\n \n idx = collections.defaultdict(int) # (binary representation -> index)\n\t\tdsu = DSU(n) # dsu \n\n def add(base):\n for i in range(26):\n if not base & 1 << i:\n yield base ^ 1 << i\n def dele(base):\n for i in range(26):\n if base & 1 << i:\n if base - (1 << i) != 0:\n yield base - (1 << i) \n def rep(base):\n pre, new = [], []\n for i in range(26):\n if base & 1 << i: pre.append(i)\n else: new.append(i)\n for p in pre:\n for n in new:\n yield base - (1 << p) + (1 << n) \n \n for i, a in enumerate(A):\n base = 0\n for ch in a:\n base += 1 << ord(ch) - ord(\'a\')\n idx[base] = i\n\n for base in idx.keys():\n for new in add(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n for new in dele(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n for new in rep(base):\n if new in idx:\n dsu.union(idx[base], idx[new])\n \n group = collections.defaultdict(int)\n for a in A:\n base = 0\n for ch in a:\n base += 1 << ord(ch) - ord(\'a\')\n cnum = c[a]\n group[dsu.find(idx[base])] += cnum\n \n return [len(group), max(group.values())]\n \n```
106,968
Groups of Strings
groups-of-strings
You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words. Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations: The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true: Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array ans of size 2 where:
String,Bit Manipulation,Union Find
Hard
Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to node i?
439
6
Please pull this [commit]() for solutions of weekly 278. \n\n```\nclass UnionFind: \n def __init__(self, n): \n self.parent = list(range(n))\n self.rank = [1] * n \n \n def find(self, p): \n if p != self.parent[p]: \n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n \n def union(self, p, q): \n prt, qrt = self.find(p), self.find(q)\n if prt == qrt: return False \n if self.rank[prt] > self.rank[qrt]: prt, qrt = qrt, prt\n self.parent[prt] = self.parent[qrt]\n self.rank[qrt] += self.rank[prt]\n return True \n\n\nclass Solution:\n def groupStrings(self, words: List[str]) -> List[int]:\n n = len(words)\n uf = UnionFind(n)\n seen = {}\n for i, word in enumerate(words): \n m = reduce(or_, (1<<ord(ch)-97 for ch in word))\n if m in seen: uf.union(i, seen[m])\n for k in range(26): \n if m ^ 1<<k in seen: uf.union(i, seen[m ^ 1<<k])\n if m & 1<<k: \n mm = m ^ 1<<k ^ 1<<26\n if mm in seen: uf.union(i, seen[mm])\n seen[mm] = i\n seen[m] = i \n freq = Counter(uf.find(i) for i in range(n))\n return [len(freq), max(freq.values())]\n```
106,973
Count Equal and Divisible Pairs in an Array
count-equal-and-divisible-pairs-in-an-array
null
Array
Easy
For every possible pair of indices (i, j) where i < j, check if it satisfies the given conditions.
4,048
21
```java\n public int countPairs(int[] nums, int k) {\n Map<Integer, List<Integer>> indices = new HashMap<>();\n for (int i = 0; i < nums.length; ++i) {\n indices.computeIfAbsent(nums[i], l -> new ArrayList<>()).add(i);\n } \n int cnt = 0;\n for (List<Integer> ind : indices.values()) {\n for (int i = 0; i < ind.size(); ++i) {\n for (int j = 0; j < i; ++j) {\n if (ind.get(i) * ind.get(j) % k == 0) {\n ++cnt;\n }\n }\n }\n }\n return cnt;\n }\n```\n```python\n def countPairs(self, nums: List[int], k: int) -> int:\n cnt, d = 0, defaultdict(list)\n for i, n in enumerate(nums):\n d[n].append(i)\n for indices in d.values(): \n for i, a in enumerate(indices):\n for b in indices[: i]:\n if a * b % k == 0:\n cnt += 1\n return cnt\n```
107,030
Count Equal and Divisible Pairs in an Array
count-equal-and-divisible-pairs-in-an-array
null
Array
Easy
For every possible pair of indices (i, j) where i < j, check if it satisfies the given conditions.
1,698
5
```\nclass Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n n=len(nums)\n c=0\n for i in range(0,n):\n for j in range(i+1,n):\n if nums[i]==nums[j] and ((i*j)%k==0):\n c+=1\n return c \n```
107,041
Find Three Consecutive Integers That Sum to a Given Number
find-three-consecutive-integers-that-sum-to-a-given-number
Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array.
Math,Simulation
Medium
Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x?
1,870
16
```java\n public long[] sumOfThree(long num) {\n if (num % 3 != 0) {\n return new long[0];\n }\n num /= 3;\n return new long[]{num - 1, num, num + 1};\n }\n```\n```python\n def sumOfThree(self, num: int) -> List[int]:\n if num % 3 == 0:\n num //= 3\n return [num - 1, num, num + 1]\n return []\n```\n**Analysis:**\n\nTime & space: `O(1)`.
107,083
Find Three Consecutive Integers That Sum to a Given Number
find-three-consecutive-integers-that-sum-to-a-given-number
Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array.
Math,Simulation
Medium
Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x?
543
5
Please pull this [commit]() for solutions of weekly 72. \n\n```\nclass Solution:\n def sumOfThree(self, num: int) -> List[int]:\n return [] if num % 3 else [num//3-1, num//3, num//3+1]\n```
107,088
Maximum Split of Positive Even Integers
maximum-split-of-positive-even-integers
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.
Math,Greedy
Medium
First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.
9,670
121
**Note:** For the rigorous proof of greedy algorithm correctness you can refer to \n\nsimilar problem: [881. Boats to Save People]() \n\nto prove it similarly.\n\n----\n\n1. Starting from smallest positive even, `2`, each iteration deduct it from the `finalSum` and increase by 2, till reach or go beyond `final sum`; \n2. Add the remaining part of the `finalSum` to the largest positive to make sure all are distinct.\n**Note:** if the remaining part is `0`, then adding it to the largest positive will NOT influence anything; if NOT, then the remaining part must be less than or equal to the largest one, if NOT adding it to the largest one, there will be a **duplicate** number since we have traversed all positive even numbers that are less than or equal to the largest one. e.g., \n\n\t`finalSum = 32`, and we have increased `i` from `2` to `10` and get `2 + 4 + 6 + 8 + 10 = 30`. Now `finalSum` has deducted `30` and now is `2`, which is less than the next value of `i = 12`. Since we must used up `finalSum`, but putting `finalSum = 2` back into the even number sequence will result duplicates of `2`; In addition, if we add `2` to any number other than the biggest `10`, there will be duplicates also. The only option is adding `2` to the largest one, `10`, to avoid duplicates.\n\n```java\n public List<Long> maximumEvenSplit(long f) {\n LinkedList<Long> ans = new LinkedList<>();\n if (f % 2 == 0) {\n long i = 2;\n while (i <= f) {\n ans.offer(i);\n f -= i;\n i += 2;\n } \n ans.offer(f + ans.pollLast());\n }\n return ans;\n }\n```\n```python\n def maximumEvenSplit(self, f: int) -> List[int]:\n ans, i = [], 2\n if f % 2 == 0:\n while i <= f:\n ans.append(i)\n f -= i\n i += 2\n ans[-1] += f\n return ans\n```\n\n**Analysis:**\n\nAssume there are totally `i` iterations, so `2 + 4 + ... + 2 * i = (2 + 2 * i) * i / 2 = i * (i + 1) = i + i`<sup>2</sup> `~ finalSum`, get rid of the minor term `i`, we have `i`<sup>2</sup> `~ finalSum`, which means `i ~ finalSum`<sup>0.5</sup>; therefore\n\nTime: `O(n`<sup>0.5</sup>`)`, where `n = finalSum`, space: `O(1)`- excluding return space.
107,110
Maximum Split of Positive Even Integers
maximum-split-of-positive-even-integers
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.
Math,Greedy
Medium
First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.
2,957
58
```\n\'\'\'VOTE UP, if you like and understand the solution\'\'\'\n\'\'\'You are free to correct my time complexity if you feel it is incorrect.\'\'\' \n```\n```\n**If finalSum is odd then their is no possible way**\n1. If finalSum is even then take s=0 and pointer i=2.\n2. add i in sum till s < finalSum and add i in the set l.\n3. If s == finalSum then return l\n4. else delete s from the l and return l.\n```\n![image]()\n\n```\nclass Solution:\n def maximumEvenSplit(self, finalSum: int) -> List[int]:\n l=set()\n if finalSum%2!=0:\n return l\n else:\n s=0\n i=2 # even pointer 2, 4, 6, 8, 10, 12...........\n while(s<finalSum):\n s+=i #sum \n l.add(i) # append the i in list\n i+=2\n if s==finalSum: #if sum s is equal to finalSum then no modidfication required\n return l\n else:\n l.discard(s-finalSum) #Deleting the element which makes s greater than finalSum\n\t\t\t\treturn l\n```\n![image]()\n
107,114
Maximum Split of Positive Even Integers
maximum-split-of-positive-even-integers
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.
Math,Greedy
Medium
First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.
1,459
10
Basically divide the numbers into sum of 2\'s and then join the 2\'s to make different even sized numbers by first taking one 2, then two 2\'s, then three 2\'s and so on. If we do not have the required number of 2\'s left, then just add the remaining 2\'s into the last integer in the array. We add them to the last element of arr and not in middle to avoid clashing of values since we need unique values.\n```\nclass Solution:\n def maximumEvenSplit(self, finalSum: int) -> List[int]:\n arr = []\n if finalSum % 2 == 0: # If finalSum is odd then we cannot ever divide it with the given conditions\n a, i = finalSum // 2, 1 # a is the number of 2\'s and i is the number of 2\'s that we will use to form a even number in the current iteration\n while i <= a: # Till we have sufficient number of 2\'s available\n arr.append(2*i) # Join the i number of 2\'s to form a even number\n a -= i # Number of 2\'s remaining reduces by i\n i += 1 # Number of 2\'s required in next itertation increases by 1\n s = sum(arr)\n arr[-1] += finalSum - s # This is done if their were still some 2\'s remaining that could not form a number due to insufficient count, then we add the remaining 2\'s into the last number.\n return arr\n```
107,121
Maximum Split of Positive Even Integers
maximum-split-of-positive-even-integers
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.
Math,Greedy
Medium
First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.
513
7
If finalSum is divisible by 2, we can divide it by 2 and try to find list of unique positive integers that sum to finalSum. We can multiply everything by 2 at the end to return result. Take the smallest consecutive sequence i.e. 1,2,3,...,n -> this will have a sum of n*(n+1)/2. If this sum == finalSum, we are done. This is trivial case.\n\nThe non-trivial case:\nIf we observe that 1+2+...+n < finalSum but 1+2+...+(n+1) > finalSum. Then, it is impossible to have a solution of size \'n+1\'. The smallest sequence of size n+1 exceeds finalSum. But, we can create a sequence of size \'n\' and this is a valid output. \n\nLet S = sum(1,2,...,n+1) and S-finalSum be the extra amount we don\'t need. So we can remove the number "S-finalSum" from the seq [1,2,...,n+1]. Observe, 1 <= S-finalSum <= n. Therefore, from the sequence [1,2,...,n+1] if we remove S-finalSum, we have the solution that is of size \'n\'. \n\nTime Complexity:\nWe are looking at the sequence of numbers [1,2,...,n] with the smallest \'n\' such that it\'s sum exceeds finalSum. This sequence will have sum = O(n^2). This sum should match finalSum, i.e. O(n^2) = finalSum. Therefore, n = O(finalSum^0.5). For example, if finalSum = 10^10, then the sequence [1,2,...,n] will be of size 10^5 and the loop in this algorithm will run for 10^5 iterations.\n\nPS: There are other ways to solve this too but they all revolve around the fact that if the smallest sequence of size \'n+1\' exceeds finalSum, you can always generate a sequence of size \'n\' whose sum equals finalSum.\n\n```\nclass Solution:\n def maximumEvenSplit(self, finalSum: int) -> List[int]:\n if(finalSum%2 != 0):\n return []\n \n finalSum = finalSum//2\n result = []\n total = 0\n remove = None\n for i in range(1, finalSum+1):\n result.append(i)\n total += i\n if(total == finalSum):\n break\n elif(total > finalSum):\n remove = total-finalSum\n break\n \n output = []\n for num in result:\n if(remove==None):\n output.append(2*num)\n else:\n if(num!=remove):\n output.append(2*num)\n \n return output\n```
107,127
Maximum Split of Positive Even Integers
maximum-split-of-positive-even-integers
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.
Math,Greedy
Medium
First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.
433
7
if n is odd we will return empty list base case. if n is even we will do following:\nlet take n=30 list=```[2,4,6,8,10]```. for suppose we you need n=28 you just need to delete difference of 30,28 from above list.**our logic stars here.** we wiil add all even number into the list until the sum is greater than the target and remove the difference of exceeded from the list and return.\n```\ndef maximumEvenSplit(self, finalSum: int) -> List[int]:\n l=[]\n i=2\n k=0\n\t\t#base case\n if finalSum%2!=0:\n return []\n else:\n while k<finalSum:\n l.append(i)\n k+=i\n i+=2 \n if k==finalSum:\n return l\n l.remove(k-finalSum)\n return l\n```\n**PLEASE UPVOTE. I NEED YOUR ENCOURAGEMENT.**
107,128
Maximum Split of Positive Even Integers
maximum-split-of-positive-even-integers
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.
Math,Greedy
Medium
First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.
294
6
Innitially got TLE but eventually figured out an acceptable backtracking solution.\n\n1. Since we start the backtracking process from the minmum even integer 2 and building the path upwords, **the first acceptable path whose values sum up to target is gureenteed to be the longest one**\n2. Hence once we have found that path we return back immediately\n\nHopefully this is helpful for folks who got TLE on backtracking\n\n```\nclass Solution:\n def maximumEvenSplit(self, finalSum: int) -> List[int]:\n \n if finalSum % 2:\n return []\n \n self.res = []\n self.backtrack(finalSum, 0, [], 2)\n \n return self.res\n \n def backtrack(self, target, currSum, path, start):\n\n if currSum == target:\n if len(path) > len(self.res):\n self.res = path[:]\n return True\n \n for i in range(start, target+1, 2):\n if currSum + i > target:\n break\n path.append(i)\n if self.backtrack(target, currSum + i, path, i+2):\n return True\n path.pop()\n```
107,149
Maximum Split of Positive Even Integers
maximum-split-of-positive-even-integers
You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers. Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.
Math,Greedy
Medium
First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the first k - 1 even elements which is less than finalSum. We then add the difference over to the kth element.
526
7
```\nclass Solution:\n def maximumEvenSplit(self, finalSum: int) -> List[int]:\n ans = set() \n \n if finalSum % 2 == 1:\n return ans\n \n i = 2\n while finalSum > 0:\n ans.add(i)\n finalSum -= i\n i += 2\n if finalSum < 0:\n ans.remove(-finalSum)\n \n return list(ans)\n```
107,157
Count Good Triplets in an Array
count-good-triplets-in-an-array
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets.
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
For every value y, how can you find the number of values x (0 ≤ x, y ≤ n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 ≤ y, z ≤ n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good triplets that can be formed if y is considered as the middle element.
1,008
15
According to the question, first we obtain an index array `indices`, where `indices[i]` is the index of `nums1[i]` in `num2`, this can be done using a hashmap in `O(N)` time. For example, given `nums1 = [2,0,1,3], nums2 = [0,1,2,3]`, then `indices = [2,0,1,3]`; given `nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]`, then `indices = [0,2,1,4,3]`.\n\nThen, the problem is essentially asking - find the total number of triplets `(x, y, z)` as a subsequence in `indices`, where `x < y < z`. To do this, we can scan through `indices` and locate the middle number `y`. Then, we count (1) how many numbers on the left of `y` in `indices` that are less than `y`; and (2) how many numbers on the right of `y` in `indices` that are greater than `y`. This can done using SortedList in Python or other data structures in `O(NlogN)` time.\n\nThe final step is to count the total number of **good triplets** as asked in the problem. This can be done by a linear scan in `O(N)` time.\n\nBelow is my in-contest solution, though I could have made it a bit neater. Please upvote if you find this solution helpful.\n```\nclass Solution:\n def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n hashmap2 = {}\n for i in range(n):\n hashmap2[nums2[i]] = i\n indices = []\n for num in nums1:\n indices.append(hashmap2[num])\n from sortedcontainers import SortedList\n left, right = SortedList(), SortedList()\n leftCount, rightCount = [], []\n for i in range(n):\n leftCount.append(left.bisect_left(indices[i]))\n left.add(indices[i])\n for i in range(n - 1, -1, -1):\n rightCount.append(len(right) - right.bisect_right(indices[i]))\n right.add(indices[i])\n count = 0\n for i in range(n):\n count += leftCount[i] * rightCount[n - 1 - i]\n return count\n```
107,172
Count Good Triplets in an Array
count-good-triplets-in-an-array
You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1]. A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z. Return the total number of good triplets.
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
For every value y, how can you find the number of values x (0 ≤ x, y ≤ n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 ≤ y, z ≤ n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good triplets that can be formed if y is considered as the middle element.
352
7
# Intuition & Approach\nAll the numbers in both arrays are unique and in the range of `0 to n-1`. The objective is to find triplets `(x, y, z)` that satisfy the conditions `posAx < posAy < posAz` and `posBx < posBy < posBz`, where `posAx` indicates the index of `x` in `A`, and `posBz` indicates the index of `z` in `B`.\n\nIf we fix a middle element, say `y`, we can find all the common elements in both arrays before and after `y`. All these common elements are valid candidates for `x` and `z`, respectively. Therefore, `(commonLeft * commonRight)` gives the total number of good triplets for that `y`. We repeat this process for all possible values of `y` to find the count of good triplets.\n\nFor each element in `A`, we find its corresponding index in `B` and update the segment tree at that index. An element\'s index in `B` is only updated in the segment tree if it has already been visited in `A`. In other words, if an element has not been visited in `A`, its corresponding index in `B` will not be updated in the segment tree.\n\nSo, when we pick up an element in `A`, we obtain its index in `B`, say `indexB`. Now, `segmentTree[0..indexB]` will only contain indexes in the range `0 to indexB`, since we only update the segment tree when we visit the element in `A`. Updated values in the segment tree indicate that those specific updated indexes have been visited in `A`. Thus, by considering `segmentTree[0..indexB]`, we can obtain all the elements common to both `A` and `B` before a specific element.\n\nNow, to calculate the common elements after a specific element, we can use mathematics. Let\'s say there are `k` common elements before a specific element `y`. Then, there are `posAy-k` unique elements in `A` before `y` that are not present in `B`. If `By` is present at index `j` in `B`, then there are `(n-1-j)` elements after `y` in `B`. To get the count of common elements after `y`, we need to subtract the count of unique elements before `Ay`, i.e., `posAy-k`, from the count of elements in `B` after `By`.\n\n# Algorithm\n```\n1. Create a hash map to store the mapping of elements in nums2 to their indices.\nInitialize a segment tree of size n * 4 + 1, where n is the length of nums1.\n3. Initialize ans = 0.\n4. Loop through nums2 and add their indices to the hash map.\n5. Update the segment tree with the index of the first element in nums1.\n6. Loop through nums1 starting from the second element.\n a. Get the index of the current element in nums1 from the hash map.\n b. Query the segment tree to get the number of common elements on the left of the current element in nums1 and nums2.\n c. Calculate the number of unique elements on the left of the current element in nums1 and the number of elements on the right of the current element in nums2.\n d. Calculate the number of common elements on the right of the current element in nums1 and nums2.\n e. Add the product of the number of common elements on the left and right to ans.\n f. Update the segment tree with the index of the current element in nums1.\n7. Return ans.\n```\n\n# Complexity\n- **Time complexity:**\nThe loop over `nums2` to create `elemToIndexMappingInB` takes `O(n)` time. The segment tree construction takes `O(n)` time. The loop over `nums1` takes `O(n log n)` time due to the segment tree query and update operations. Therefore, the overall time complexity is `O(n log n + n)` i.e `O(n log n)`.\n\n- **Space complexity:**\nThe `elemToIndexMappingInB` map takes `O(n)` space. The segment tree takes `O(n)` space. Therefore, the overall space complexity is `O(2n)` = `O(n)`.\n\n# Code\n```java []\nclass Solution {\n\n public long goodTriplets(int[] nums1, int[] nums2) {\n Map<Integer, Integer> elemToIndexMappingInB = new HashMap<>();\n int n = nums1.length;\n long[] segmentTree = new long[n * 4 + 1];\n long ans = 0;\n for (int i = 0; i < nums2.length; i++) {\n elemToIndexMappingInB.put(nums2[i], i);\n }\n update(segmentTree, 1, 0, n - 1, elemToIndexMappingInB.get(nums1[0]));\n for (int i = 1; i < n; i++) {\n int indexInB = elemToIndexMappingInB.get(nums1[i]);\n long commonElementsOnLeft = query(segmentTree, 1, 0, n - 1, 0, indexInB);\n long uniqueElementsOnLeftInA = i - commonElementsOnLeft;\n long elementsAfterIndexInB = n - 1 - indexInB;\n long commonElementsOnRight = elementsAfterIndexInB - uniqueElementsOnLeftInA;\n ans += commonElementsOnLeft * commonElementsOnRight;\n update(segmentTree, 1, 0, n - 1, indexInB);\n }\n return ans;\n }\n\n private void update(long[] st, int index, int start, int end, int updateIndex) {\n if (start == end) {\n st[index] += 1;\n return;\n }\n int mid = start + (end - start) / 2;\n if (updateIndex <= mid) update(st, index * 2, start, mid, updateIndex);\n else update(st, index * 2 + 1, mid + 1, end, updateIndex);\n st[index] = st[index * 2] + st[index * 2 + 1];\n }\n\n private long query(long[] st, int index, int start, int end, int queryStart, int queryEnd) {\n if (end < queryStart || start > queryEnd) return 0;\n if (start >= queryStart && end <= queryEnd) return st[index];\n int mid = start + (end - start) / 2;\n long left = query(st, index * 2, start, mid, queryStart, queryEnd);\n long right = query(st, index * 2 + 1, mid + 1, end, queryStart, queryEnd);\n return left + right;\n }\n}\n```\n```cpp []\n#include <unordered_map>\n#include <vector>\n\nclass Solution {\npublic:\n long long goodTriplets(std::vector<int>& nums1, std::vector<int>& nums2) {\n std::unordered_map<int, int> elemToIndexMappingInB;\n int n = nums1.size();\n std::vector<long long> segmentTree(n * 4 + 1);\n long long ans = 0;\n for (int i = 0; i < nums2.size(); i++) {\n elemToIndexMappingInB[nums2[i]] = i;\n }\n update(segmentTree, 1, 0, n - 1, elemToIndexMappingInB[nums1[0]]);\n for (int i = 1; i < n; i++) {\n int indexInB = elemToIndexMappingInB[nums1[i]];\n long long commonElementsOnLeft = query(segmentTree, 1, 0, n - 1, 0, indexInB);\n long long uniqueElementsOnLeftInA = i - commonElementsOnLeft;\n long long elementsAfterIndexInB = n - 1 - indexInB;\n long long commonElementsOnRight = elementsAfterIndexInB - uniqueElementsOnLeftInA;\n ans += commonElementsOnLeft * commonElementsOnRight;\n update(segmentTree, 1, 0, n - 1, indexInB);\n }\n return ans;\n }\n\nprivate:\n void update(std::vector<long long>& st, int index, int start, int end, int updateIndex) {\n if (start == end) {\n st[index] += 1;\n return;\n }\n int mid = start + (end - start) / 2;\n if (updateIndex <= mid) update(st, index * 2, start, mid, updateIndex);\n else update(st, index * 2 + 1, mid + 1, end, updateIndex);\n st[index] = st[index * 2] + st[index * 2 + 1];\n }\n\n long long query(std::vector<long long>& st, int index, int start, int end, int queryStart, int queryEnd) {\n if (end < queryStart || start > queryEnd) return 0;\n if (start >= queryStart && end <= queryEnd) return st[index];\n int mid = start + (end - start) / 2;\n long long left = query(st, index * 2, start, mid, queryStart, queryEnd);\n long long right = query(st, index * 2 + 1, mid + 1, end, queryStart, queryEnd);\n return left + right;\n }\n};\n```\n```python []\nclass Solution:\n def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n elemToIndexMappingInB = {}\n n = len(nums1)\n segmentTree = [0] * (n * 4 + 1)\n ans = 0\n for i in range(len(nums2)):\n elemToIndexMappingInB[nums2[i]] = i\n self.update(segmentTree, 1, 0, n - 1, elemToIndexMappingInB[nums1[0]])\n for i in range(1, n):\n indexInB = elemToIndexMappingInB[nums1[i]]\n commonElementsOnLeft = self.query(segmentTree, 1, 0, n - 1, 0, indexInB)\n uniqueElementsOnLeftInA = i - commonElementsOnLeft\n elementsAfterIndexInB = n - 1 - indexInB\n commonElementsOnRight = elementsAfterIndexInB - uniqueElementsOnLeftInA\n ans += commonElementsOnLeft * commonElementsOnRight\n self.update(segmentTree, 1, 0, n - 1, indexInB)\n return ans\n\n def update(self, st, index, start, end, updateIndex):\n if start == end:\n st[index] += 1\n return\n mid = start + (end - start) // 2\n if updateIndex <= mid:\n self.update(st, index * 2, start, mid, updateIndex)\n else:\n self.update(st, index * 2 + 1, mid + 1, end, updateIndex)\n st[index] = st[index * 2] + st[index * 2 + 1]\n\n def query(self, st, index, start, end, queryStart, queryEnd):\n if end < queryStart or start > queryEnd:\n return 0\n if start >= queryStart and end <= queryEnd:\n return st[index]\n mid = start + (end - start) // 2\n left = self.query(st, index * 2, start, mid, queryStart, queryEnd)\n right = self.query(st, index * 2 + 1, mid + 1, end, queryStart, queryEnd)\n return left + right\n```\n```javascript []\nfunction goodTriplets(nums1, nums2) {\n const elemToIndexMappingInB = new Map();\n const n = nums1.length;\n const segmentTree = new Array(n * 4 + 1).fill(0);\n let ans = 0;\n for (let i = 0; i < nums2.length; i++) {\n elemToIndexMappingInB.set(nums2[i], i);\n }\n update(segmentTree, 1, 0, n - 1, elemToIndexMappingInB.get(nums1[0]));\n for (let i = 1; i < n; i++) {\n const indexInB = elemToIndexMappingInB.get(nums1[i]);\n const commonElementsOnLeft = query(segmentTree, 1, 0, n - 1, 0, indexInB);\n const uniqueElementsOnLeftInA = i - commonElementsOnLeft;\n const elementsAfterIndexInB = n - 1 - indexInB;\n const commonElementsOnRight = elementsAfterIndexInB - uniqueElementsOnLeftInA;\n ans += commonElementsOnLeft * commonElementsOnRight;\n update(segmentTree, 1, 0, n - 1, indexInB);\n }\n return ans;\n}\n\nfunction update(st, index, start, end, updateIndex) {\n if (start == end) {\n st[index] += 1;\n return;\n }\n const mid = start + Math.floor((end - start) / 2);\n if (updateIndex <= mid) update(st, index * 2, start, mid, updateIndex);\n else update(st, index * 2 + 1, mid + 1, end, updateIndex);\n st[index] = st[index * 2] + st[index * 2 + 1];\n}\n\nfunction query(st, index, start, end, queryStart, queryEnd) {\n if (end < queryStart || start > queryEnd) return 0;\n if (start >= queryStart && end <= queryEnd) return st[index];\n const mid = start + Math.floor((end - start) / 2);\n const left = query(st, index * 2, start, mid, queryStart, queryEnd);\n const right = query(st, index * 2 + 1, mid + 1, end, queryStart, queryEnd);\n return left + right;\n}\n```
107,173
Sort Even and Odd Indices Independently
sort-even-and-odd-indices-independently
You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: Return the array formed after rearranging the values of nums.
Array,Sorting
Easy
Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array.
1,277
17
```\nclass Solution(object):\n def sortEvenOdd(self, nums):\n """\n :type nums: List[int]\n :rtype: List[int]\n """\n nums[::2], nums[1::2] = sorted(nums[::2]), sorted(nums[1::2], reverse=True)\n return nums\n```
107,227
Sort Even and Odd Indices Independently
sort-even-and-odd-indices-independently
You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: Return the array formed after rearranging the values of nums.
Array,Sorting
Easy
Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array.
1,374
9
```\nclass Solution:\n def sortEvenOdd(self, nums: List[int]) -> List[int]:\n if len(nums) == 2:\n return nums\n else:\n evensorted = []\n oddsorted = []\n for i in range(len(nums)):\n if i%2 == 0:\n evensorted.append(nums[i])\n else:\n oddsorted.append(nums[i])\n evensorted.sort()\n oddsorted.sort(reverse=True)\n \n evenindex = 0\n oddindex = 0\n for i in range(len(nums)):\n if i%2==0:\n nums[i] = evensorted[evenindex]\n evenindex += 1\n else:\n nums[i] = oddsorted[oddindex]\n oddindex += 1\n return nums\n```
107,232
Smallest Value of the Rearranged Number
smallest-value-of-the-rearranged-number
You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros. Return the rearranged number with minimal value. Note that the sign of the number does not change after rearranging the digits.
Math,Sorting
Medium
For positive numbers, the leading digit should be the smallest nonzero digit. Then the remaining digits follow in ascending order. For negative numbers, the digits should be arranged in descending order.
3,588
47
# **Explanation**\nIf it\'s negative, simple sort reversely all digits.\nIf it\'s positive, swap the fisrt digit and the first non-zero digit.\n\nNote that `0` is neither positive nor negative,\ntake care of it.\n<br>\n\n**C++**\nall by @blackspinner\n```cpp\n long long smallestNumber(long long num) {\n string s = to_string(abs(num));\n sort(s.begin(), s.end());\n if (num <= 0) {\n return -1 * stoll(string(s.rbegin(), s.rend()));\n }\n int i = s.find_first_not_of(\'0\');\n swap(s[0], s[i]);\n return stoll(s);\n }\n```\n**Python**\n```py\n def smallestNumber(self, a):\n s = sorted(str(abs(a)))\n if a <= 0:\n return -int(\'\'.join(s[::-1]))\n i = next(i for i,a in enumerate(s) if a > \'0\')\n s[i], s[0] = s[0], s[i]\n return int(\'\'.join(s))\n```\n
107,264
Design Bitset
design-bitset
A Bitset is a data structure that compactly stores bits. Implement the Bitset class:
Array,Hash Table,Design
Medium
Note that flipping a bit twice does nothing. In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update.
3,698
92
\n* Flipping can be done using a flipped string that contains the flipped version of the current bitset. C++ and Java solutions have been done using this method. All operations are O(1) in C++ at the cost of an extra string of length `size`\n* Python solution has been done using a flip flag. Flip flag stores whether the current bitset has to be flipped. `toString` is O(n)\n* Keep a count variable `ones` that counts the number of ones in the bitset. This has to be updated in `fix`, `unfix`, and `flip` functions.\n<iframe src="" frameBorder="0" width="900" height="590"></iframe>
107,312
Design Bitset
design-bitset
A Bitset is a data structure that compactly stores bits. Implement the Bitset class:
Array,Hash Table,Design
Medium
Note that flipping a bit twice does nothing. In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update.
4,349
43
**C++**\nImplement with a string.\nAll operation is `O(1)`, \nexcept `toString()`\n\nWe record if we flip it with `isFlip`, \nwe don\'t need to really flip it.\n```cpp\n int a = 0, sz = 0, cnt = 0, isFlip = 0;\n string s;\n Bitset(int size) {\n sz = size;\n s = string(sz, \'0\');\n }\n \n void fix(int idx) {\n if (s[idx] == \'0\' + isFlip) {\n s[idx] = \'1\' + \'0\' - s[idx];\n cnt++;\n }\n }\n \n void unfix(int idx) {\n if (s[idx] == \'1\' - isFlip) {\n s[idx] = \'1\' + \'0\' - s[idx];\n cnt--;\n }\n }\n \n void flip() {\n isFlip ^= 1;\n cnt = sz - cnt;\n }\n \n bool all() {\n return cnt == sz;\n }\n \n bool one() {\n return cnt > 0;\n }\n \n int count() {\n return cnt;\n }\n \n string toString() {\n if (isFlip) {\n string s2 = s;\n for (auto& c: s2)\n c = \'0\' + \'1\' - c;\n return s2;\n }\n return s;\n }\n```\n\n**Python**\nImplement with an integer, \nall operation is `O(1) * O(bit operation)`, \nexcept `toString()`.\n\n```py\nclass Bitset(object):\n\n def __init__(self, size):\n self.a = 0\n self.size = size\n self.cnt = 0\n\n def fix(self, idx):\n if self.a & (1 << idx) == 0:\n self.a |= 1 << idx\n self.cnt += 1\n\n def unfix(self, idx):\n if self.a & (1 << idx):\n self.a ^= 1 << idx\n self.cnt -= 1\n\n def flip(self):\n self.a ^= (1 << self.size) - 1\n self.cnt = self.size - self.cnt\n\n def all(self):\n return self.cnt == self.size\n\n def one(self):\n return self.a > 0\n\n def count(self):\n return self.cnt\n\n def toString(self):\n a = bin(self.a)[2:]\n return a[::-1] + \'0\' * (self.size - len(a))\n```\n
107,314
Design Bitset
design-bitset
A Bitset is a data structure that compactly stores bits. Implement the Bitset class:
Array,Hash Table,Design
Medium
Note that flipping a bit twice does nothing. In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update.
928
15
Use 2 boolean arrays to record current state and the corresponding flipped one.\n\n```java\n private boolean[] bits;\n private boolean[] flipped;\n private int sz, cnt;\n \n public BooleanArray2(int size) {\n sz = size;\n bits = new boolean[size];\n flipped = new boolean[size];\n Arrays.fill(flipped, true);\n }\n \n public void fix(int idx) {\n if (!bits[idx]) {\n bits[idx] ^= true;\n flipped[idx] ^= true;\n cnt += 1;\n }\n }\n \n public void unfix(int idx) {\n if (bits[idx]) {\n bits[idx] ^= true;\n flipped[idx] ^= true;\n cnt -= 1;\n }\n }\n \n public void flip() {\n boolean[] tmp = bits;\n bits = flipped;\n flipped = tmp;\n cnt = sz - cnt;\n }\n \n public boolean all() {\n return cnt == sz;\n }\n \n public boolean one() {\n return cnt > 0;\n }\n \n public int count() {\n return cnt;\n }\n \n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (boolean b : bits) {\n sb.append(b ? \'1\' : \'0\');\n }\n return sb.toString();\n }\n```\n```python\n def __init__(self, size: int):\n self.sz = size\n self.bits = [False] * size\n self.flipped = [True] * size\n self.bitCount = 0\n \n def fix(self, idx: int) -> None:\n if not self.bits[idx]:\n self.bits[idx] ^= True\n self.flipped[idx] ^= True\n self.bitCount += 1\n\n def unfix(self, idx: int) -> None:\n if self.bits[idx]:\n self.bits[idx] ^= True\n self.flipped[idx] ^= True\n self.bitCount -= 1\n\n def flip(self) -> None:\n self.bits, self.flipped = self.flipped, self.bits\n self.bitCount = self.sz - self.bitCount \n\n def all(self) -> bool:\n return self.sz == self.bitCount\n\n def one(self) -> bool:\n return self.bitCount > 0\n\n def count(self) -> int:\n return self.bitCount\n\n def toString(self) -> str:\n return \'\'.join([\'1\' if b else \'0\' for b in self.bits])\n```\n\n----\n\nMinor optimization of the space: using only **one** boolean array and a boolean variable `flipAll` to indicate the flip.\n\n```java\n private boolean[] arr;\n private int sz, cnt;\n private boolean flipAll;\n \n public Bitset(int size) {\n sz = size;\n arr = new boolean[size];\n }\n \n public void fix(int idx) {\n if (!(arr[idx] ^ flipAll)) {\n arr[idx] ^= true;\n cnt += 1;\n }\n }\n \n public void unfix(int idx) {\n if (arr[idx] ^ flipAll) {\n arr[idx] ^= true;\n cnt -= 1;\n }\n }\n \n public void flip() {\n flipAll ^= true;\n cnt = sz - cnt;\n }\n \n public boolean all() {\n return cnt == sz;\n }\n \n public boolean one() {\n return cnt > 0;\n }\n \n public int count() {\n return cnt;\n }\n \n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (boolean b : arr) {\n sb.append(b ^ flipAll ? \'1\' : \'0\');\n }\n return sb.toString();\n }\n```\n\n```python\n def __init__(self, size: int):\n self.sz = size\n self.arr = [False] * size\n self.cnt = 0\n self.flipAll = False\n \n def fix(self, idx: int) -> None:\n if not (self.arr[idx] ^ self.flipAll):\n self.cnt += 1\n self.arr[idx] ^= True\n\n def unfix(self, idx: int) -> None:\n if self.arr[idx] ^ self.flipAll:\n self.arr[idx] ^= True\n self.cnt -= 1\n\n def flip(self) -> None:\n self.flipAll ^= True\n self.cnt = self.sz - self.cnt \n\n def all(self) -> bool:\n return self.sz == self.cnt\n\n def one(self) -> bool:\n return self.cnt > 0\n\n def count(self) -> int:\n return self.cnt\n\n def toString(self) -> str:\n return \'\'.join([\'1\' if (v ^ self.flipAll) else \'0\' for v in self.arr])\n```\n\n**Analysis:**\n\nTime & space:\nInitialization and `toString()` are both `O(size)`; others are all `O(1)`;
107,322
Design Bitset
design-bitset
A Bitset is a data structure that compactly stores bits. Implement the Bitset class:
Array,Hash Table,Design
Medium
Note that flipping a bit twice does nothing. In order to determine the value of a bit, consider how you can efficiently count the number of flips made on the bit since its latest update.
425
9
**UPVOTE IF HELPFuuL**\n\n* Make an array for storing bits. *Initializing all the values to 0*\n* Keep a variable ```on``` to keep the count of number of ones.\n* Create another ```bool``` variable ```flipped = False``` to store condition of array. **[ If array is fliiped, variable is changed to ```True```, if flipped again change to ```False``` and keeping doing this ]** Hence we can perform flip operation in O ( 1 ). Also remember to change number of one ```on```\n* Other conditons can be derived and understood from the code below.\n\n**UPVOTE IF HELPFuuL**\n\n```\nclass Bitset:\n\n def __init__(self, size: int):\n self.a=[0]*size\n self.on=0;\n self.n = size;\n self.flipped=False\n\n \n def fix(self, idx: int) -> None:\n if self.flipped:\n if self.a[idx]==1:\n self.on+=1\n self.a[idx]=0\n else:\n if self.a[idx]==0:\n self.on+=1\n self.a[idx]=1\n\n \n def unfix(self, idx: int) -> None:\n if self.flipped:\n if self.a[idx]==0:\n self.on-=1\n self.a[idx]=1\n else:\n if self.a[idx]==1:\n self.on-=1\n self.a[idx]=0\n\n \n def flip(self) -> None:\n if self.flipped:\n self.flipped=False\n else:\n self.flipped=True\n self.on = self.n-self.on\n \n \n def all(self) -> bool:\n if self.n==self.on:\n return True\n return False\n\n \n def one(self) -> bool:\n if self.on>0:\n return True\n return False\n\n \n def count(self) -> int:\n return self.on\n \n \n def toString(self) -> str:\n s=""\n if self.flipped:\n for i in self.a:\n if i:\n s+="0"\n else:\n s+="1"\n return s\n for i in self.a:\n if i:\n s+="1"\n else:\n s+="0"\n return s\n```\n![image]()\n\n
107,336
Minimum Time to Remove All Cars Containing Illegal Goods
minimum-time-to-remove-all-cars-containing-illegal-goods
You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times: Return the minimum time to remove all the cars containing illegal goods. Note that an empty sequence of cars is considered to have no cars containing illegal goods.
String,Dynamic Programming
Hard
Build an array withoutFirst where withoutFirst[i] stores the minimum time to remove all the cars containing illegal goods from the ‘suffix’ of the sequence starting from the ith car without using any type 1 operations. Next, build an array onlyFirst where onlyFirst[i] stores the minimum time to remove all the cars containing illegal goods from the ‘prefix’ of the sequence ending on the ith car using only type 1 operations. Finally, we can compare the best way to split the operations amongst these two types by finding the minimum time across all onlyFirst[i] + withoutFirst[i + 1].
8,164
237
# **Explanation**\nOne pass from left to right.\n`left` counts the cost to clear all illegal goods from `s[0]` to `s[i]`\n`right` counts the cost to clear all illegal goods from `s[i+1]` to `s[n-1]`\n\nIf `s[i] == 1`, then update `left` value,\nwe take the minimum of these 2 options:\n1) `i + 1`, by removing all left cars, `i + 1`\n2) `left + 2`, previously remove cose + removing the current `s[i]`\n\n`right = n - 1 - i`, be removing all right cars.\n<br>\n\n# **Q&A**\nQuestion:\n- Right is not the minimum, it can be less than that `n - 1 - i`\nAnswer:\n- Yes, that\'s true.\nImagine in best case, `s[i+1]` to `s[n-1]` is removed as the right part.\nThe cost for this case can be calculated when we iterate `s[i]`.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public int minimumTime(String s) {\n int n = s.length(), left = 0, res = n;\n for (int i = 0; i < n; ++i) { \n left = Math.min(left + (s.charAt(i) - \'0\') * 2, i + 1);\n res = Math.min(res, left + n - 1 - i);\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n int minimumTime(string s) {\n int n = s.size(), left = 0, res = n;\n for (int i = 0; i < n; ++i) { \n left = min(left + (s[i] - \'0\') * 2, i + 1);\n res = min(res, left + n - 1 - i);\n }\n return res;\n }\n```\n\n**Python**\n```py\n def minimumTime(self, s):\n left, res, n = 0, len(s), len(s)\n for i,c in enumerate(s):\n left = min(left + (c == \'1\') * 2, i + 1)\n res = min(res, left + n - 1 - i)\n return res\n```\n\n
107,360
Count Operations to Obtain Zero
count-operations-to-obtain-zero
You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. Return the number of operations required to make either num1 = 0 or num2 = 0.
Math,Simulation
Easy
Try simulating the process until either of the two integers is zero. Count the number of operations done.
729
7
# Code\u2705\n```\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n count = 0\n while num1 != 0 and num2 != 0:\n if num1 >= num2:\n num1 -= num2\n else:\n num2 -= num1\n count +=1\n return count\n```
107,426
Count Operations to Obtain Zero
count-operations-to-obtain-zero
You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. Return the number of operations required to make either num1 = 0 or num2 = 0.
Math,Simulation
Easy
Try simulating the process until either of the two integers is zero. Count the number of operations done.
946
6
**Python :**\n\n```\ndef countOperations(self, num1: int, num2: int) -> int:\n\toperations = 0\n\n\twhile num1 and num2:\n\t\tif num2 > num1:\n\t\t\tnum2 -= num1\n\t\t\toperations += 1\n\n\t\tif num1 > num2:\n\t\t\tnum1 -= num2\n\t\t\toperations += 1\n\n\t\tif num1 == num2:\n\t\t\treturn operations + 1\n\n\treturn operations\n```\n\n**Like it ? please upvote !**
107,441
Count Operations to Obtain Zero
count-operations-to-obtain-zero
You are given two non-negative integers num1 and num2. In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2. Return the number of operations required to make either num1 = 0 or num2 = 0.
Math,Simulation
Easy
Try simulating the process until either of the two integers is zero. Count the number of operations done.
599
6
Please pull this [commit]() for solutions of weekly 280. \n\n```\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n ans = 0 \n while num1 and num2: \n ans += num1//num2\n num1, num2 = num2, num1%num2\n return ans \n```
107,453
Minimum Operations to Make the Array Alternating
minimum-operations-to-make-the-array-alternating
You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: In one operation, you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating.
Array,Hash Table,Greedy,Counting
Medium
Count the frequency of each element in odd positions in the array. Do the same for elements in even positions. To minimize the number of operations we need to maximize the number of elements we keep from the original array. What are the possible combinations of elements we can choose from odd indices and even indices so that the number of unchanged elements is maximized?
1,217
12
Key implementation step:\n* Create two hashmaps to count the frequencies of num with odd and even indices, respectively;\n* Search for the `num` in each hashmap with the maximum and second maximum frequencies:\n\t* If the two `num`\'s with the maximum frequencies are not equal, then return `len(nums) - (maxFreqOdd + maxFreqEven)`;\n\t* Otherwise return `len(nums) - max(maxFreqOdd + secondMaxFreqEven, maxFreqEven + secondMaxFreqOdd)`.\n\nOne thing to note in step 2 is that after getting the two hashmaps for odd and even indices, we **don\'t** need to sort the hashmap keys based on their values or using heaps, but only need to write a subroutine by scanning through all `num`\'s in the hashmap, so the overall time complexity is `O(N)` instead of `O(NlogN)`.\n\nBelow is my in-contest solution, though I could have made it a bit neater. Please upvote if you find this solution helpful.\n\n```\nclass Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n n = len(nums)\n odd, even = defaultdict(int), defaultdict(int)\n for i in range(n):\n if i % 2 == 0:\n even[nums[i]] += 1\n else:\n odd[nums[i]] += 1\n topEven, secondEven = (None, 0), (None, 0)\n for num in even:\n if even[num] > topEven[1]:\n topEven, secondEven = (num, even[num]), topEven\n elif even[num] > secondEven[1]:\n secondEven = (num, even[num])\n topOdd, secondOdd = (None, 0), (None, 0)\n for num in odd:\n if odd[num] > topOdd[1]:\n topOdd, secondOdd = (num, odd[num]), topOdd\n elif odd[num] > secondOdd[1]:\n secondOdd = (num, odd[num])\n if topOdd[0] != topEven[0]:\n return n - topOdd[1] - topEven[1]\n else:\n return n - max(secondOdd[1] + topEven[1], secondEven[1] + topOdd[1])\n```
107,467
Minimum Operations to Make the Array Alternating
minimum-operations-to-make-the-array-alternating
You are given a 0-indexed array nums consisting of n positive integers. The array nums is called alternating if: In one operation, you can choose an index i and change nums[i] into any positive integer. Return the minimum number of operations required to make the array alternating.
Array,Hash Table,Greedy,Counting
Medium
Count the frequency of each element in odd positions in the array. Do the same for elements in even positions. To minimize the number of operations we need to maximize the number of elements we keep from the original array. What are the possible combinations of elements we can choose from odd indices and even indices so that the number of unchanged elements is maximized?
2,377
22
Please pull this [commit]() for solutions of weekly 280. \n\nUpdated implementation using `most_common()`\n```\nclass Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n pad = lambda x: x + [(None, 0)]*(2-len(x))\n even = pad(Counter(nums[::2]).most_common(2))\n odd = pad(Counter(nums[1::2]).most_common(2))\n return len(nums) - (max(even[0][1] + odd[1][1], even[1][1] + odd[0][1]) if even[0][0] == odd[0][0] else even[0][1] + odd[0][1])\n```\n\n```\nclass Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n odd, even = Counter(), Counter()\n for i, x in enumerate(nums): \n if i&1: odd[x] += 1\n else: even[x] += 1\n \n def fn(freq): \n key = None\n m0 = m1 = 0\n for k, v in freq.items(): \n if v > m0: key, m0, m1 = k, v, m0\n elif v > m1: m1 = v\n return key, m0, m1\n \n k0, m00, m01 = fn(even)\n k1, m10, m11 = fn(odd)\n return len(nums) - max(m00 + m11, m01 + m10) if k0 == k1 else len(nums) - m00 - m10\n```
107,471
Removing Minimum Number of Magic Beans
removing-minimum-number-of-magic-beans
You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove.
Array,Sorting,Prefix Sum
Medium
Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many bags we should remove and choose the one that minimizes the total amount of beans to remove? Sort the bags of beans first.
2,352
67
**Intuition**\nThe problem asks us to get the minimum beans by removing part or all from any individual bean bag(s), in order to make remaining bean bags homogeneous in terms of the number of beans. \n\nTherefore, we can sort input first, then remove smallest bags by whole and largest bags by part, in order to get the biggest rectangle. After computing the area of biggest rectangle, we can subtract it from the total number of beans to get the required minimum beans.\n\n----\n\nAfter sorting the input, what we need is to find the largest rectangle from the histogram formed by the `beans`. Please refer to different rectangles (not show all of them, just several ones for illustration purpose) in the 2nd picture.\n![image]()\n\n![image]()\n\n\n**Java**\n\n```java\n public long minimumRemoval(int[] beans) {\n long mx = 0, sum = 0;\n Arrays.sort(beans)\n for (int i = 0, n = beans.length; i < n; ++i) {\n sum += beans[i];\n mx = Math.max(mx, (long)beans[i] * (n - i));\n }\n return sum - mx;\n }\n```\nAnother style of Java code:\n```java\n public long minimumRemoval(int[] beans) {\n long mx = 0, sum = 0, i = 0;\n Arrays.sort(beans);\n for (int bean : beans) {\n sum += bean;\n mx = Math.max(mx, bean * (beans.length - i++));\n }\n return sum - mx;\n }\n```\n\n----\n\n**Python 3**\n```python\n def minimumRemoval(self, beans: List[int]) -> int:\n mx, n = 0, len(beans)\n for i, bean in enumerate(sorted(beans)):\n mx = max(mx, bean * (n - i))\n return sum(beans) - mx\n```\n\n**Analysis:**\n\nTime: `O(nlogn)`, space: `O(n)` - including sorting space.\n\n----\n\n**Q & A**\n*Q1:* Why we have to find the "largest rectangle" from the histogram?\n*A1:* We are required to remove minimum # of beans to make the remaining bags having same #, and those remaining bags can form a "rectangle". There are `n` options to form rectangles, which one should we choose? The largest one, which need to remove only minimum # of beans.\n\n*Q2*: Which categories or tags does such a problem come from? Greedy or Math?\n*A2*: The purpose of sorting is to remove the whole of smallest bags and remove part of biggest bags. Hence the part of the sorting can be regarded as **Greedy**; The computing and finding the largest rectangle part can be regarded as **Math**.\n\n*Q3*: Is [453. Minimum Moves to Equal Array Elements]() similar to this problem?\n*A3*: It is a bit similar.\n\n1. For 453, after a brain teaser we only need to compute the area of the shortest (or lowest) and widest rectangle of dimension `min(nums) * n`;\n2. For this problem, we need to go one step further: compute the areas of all possible rectangles, `beans[i] * (number of beans[k] >= beans[i])`, where `n = beans.length, 0 <= i, k < n`, then find the max area out of them.\n\n**End of Q**
107,512
Removing Minimum Number of Magic Beans
removing-minimum-number-of-magic-beans
You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove.
Array,Sorting,Prefix Sum
Medium
Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many bags we should remove and choose the one that minimizes the total amount of beans to remove? Sort the bags of beans first.
970
21
If you want to make all the numbers the same inside an array (only decreasing is allowed)\nyou need to make `sum(arr) - len(arr) * min(arr)` operations overall as you need to decrease all elements by `arr[i] - min(arr)` where `0<=i<len(arr)`\n\nAs described in problem statement we can decrease number of beans in the bag and when it becomes `0` we dont need to make all other bags `0` to make them equal (We just ignore `0` bags, which simply means length of array also decreases).\n\n\nApproach:\n-\n- Sort beans\n- Calculate number of operations for every element in beans\n\n```\ndef minimumRemoval(self, beans: List[int]) -> int:\n\tbeans.sort()\n\ts = sum(beans)\n\tl = len(beans)\n\tres = float(\'inf\')\n\n\tfor i in range(len(beans)):\n\t\tres = min(res, s - l * beans[i])\n\t\tl -= 1\n\t\t\n\treturn res\n```
107,517
Removing Minimum Number of Magic Beans
removing-minimum-number-of-magic-beans
You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag. Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags. Return the minimum number of magic beans that you have to remove.
Array,Sorting,Prefix Sum
Medium
Notice that if we choose to make x bags of beans empty, we should choose the x bags with the least amount of beans. Notice that if the minimum number of beans in a non-empty bag is m, then the best way to make all bags have an equal amount of beans is to reduce all the bags to have m beans. Can we iterate over how many bags we should remove and choose the one that minimizes the total amount of beans to remove? Sort the bags of beans first.
490
7
**Thought Process:**\nAt any given point of number, for number less than current number should be => 0. For number greater than current number should be current number. So **sorting will make easier** so that at any given point, number less than current will be on left-side, and number greater than current will be on right-side\n\nSo with more detailed explains under the drawing, I came up with the equation\n**prevSum + [ totalSum - prevSum - [ (arrLen - currIdx) * currNum ] ]**\nWhich simplifies to **totalSum - [ (arrLen - currIdx) * currNum ]**\nAnd we want the minimum results of the calculation for every position\n\nNote: Duplicated number doesn\'t affect the result as we already have calculated minimum value at first visit for the number\n\n![image]()\n\nprevSum => beans on the left => meaning beans we want to remove\n\ntotalSum - prevSum => sum of number on the right side include itself\n20 - 1 = 19\n\n(arrLen - currIdx) * currNum => the number of integers on the right side include itself multiplied by current number => meaning that the **number of beans we want to keep**\n(5 - 1) * 4 = 16\n\nso the first equation ...\nprevSum + [ totalSum - prevSum - [ (arrLen - currIdx) * currNum ] ]\n**# of every beans on leftside(to be removed) + # of every beans on the right side - # of beans we want to keep**\n\nThis simplifies to ...\n**totalSum - [ (arrLen - currIdx) * currNum ]** which is just\n 20 - [ ( 5 - 1 ) * 4 ] = 4\n\t \n**Steps:**\n1. find totalSum, length\n2. sort the beans array\n3. iterate over every position and keep the minimum value from the equation\n\n**TimeComplexity** - O(nlogn) sorting, O(n) for sum(beans), O(n) for iteration =>**O(nlogn)**\n**SpaceComplexity** - O(1)\n\n\n```\nclass Solution:\n def minimumRemoval(self, beans: List[int]) -> int:\n totalSum = sum(beans)\n beanLen = len(beans)\n beans.sort()\n minRm = float(\'inf\')\n for i, bean in enumerate(beans):\n minRm = min(minRm, totalSum - (beanLen - i) * bean)\n return minRm\n```\n\nPlease correct me if I am wrong !\nPlease **UPVOTE** if you find this solution helpful !\nHappy algo!
107,521