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 Ways To Reconstruct A Tree
number-of-ways-to-reconstruct-a-tree
You are given an array pairs, where pairs[i] = [xi, yi], and: Let ways be the number of rooted trees that satisfy the following conditions: Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.
Tree,Graph,Topological Sort
Hard
Think inductively. The first step is to get the root. Obviously, the root should be in pairs with all the nodes. If there isn't exactly one such node, then there are 0 ways. The number of pairs involving a node must be less than or equal to that number of its parent. Actually, if it's equal, then there is not exactly 1 way, because they can be swapped. Recursively, given a set of nodes, get the node with the most pairs, then this must be a root and have no parents in the current set of nodes.
882
17
Inspired by [jdshen](), we can iterate each node and check their validity by their degree. As node with larger degree more tends to be an ancestor.\n\nFor each node `x`, we find out its parent `p`. `p` is the node that has been visited (in the set `ancestor`) and has the lowest degree in `g[x]` (connected with `x` in `pairs`). Then `g[x]` must be a subset of `g[p] | {p}` since `x`\'s ancestors are `p` + `p`\'s ancestors and `x` +`x`\'s descendants are all `p`\'s descendants.\nIf `x` has no parent, it\'s the root whose degree should be `n-1`.\n\nWe only need to check `p` for `x` as if all `p-x` relations are solid, the entire tree is well founded.\n\nAnother reason we check `p` is that `p` could be exchanged with `x`. If it is (`len(g[p]) == len(g[x])` and remember, we have checked `g[x].issubset(g[p]|{p})`), we have more than one way to contruct the tree.\n\n```\ndef checkWays(pairs):\n g = collections.defaultdict(set)\n for x, y in pairs:\n g[x].add(y)\n g[y].add(x)\n n, mul = len(g), False\n ancestor = set()\n for x in sorted(g.keys(), key=lambda i: -len(g[i])):\n p = min((g[x] & ancestor), key=lambda i: len(g[i]), default=0) # find x\'s parent p\n ancestor.add(x)\n if p:\n if not g[x].issubset(g[p]|{p}):\n return 0\n mul |= len(g[p]) == len(g[x])\n elif len(g[x]) != n-1:\n return 0\n return 1 + mul\n```\nNote: `g[x].issubset(g[p]|{p})` is low efficient. Given value scale (`[1,500]`) is small it can still pass the test cases.
89,753
Number Of Ways To Reconstruct A Tree
number-of-ways-to-reconstruct-a-tree
You are given an array pairs, where pairs[i] = [xi, yi], and: Let ways be the number of rooted trees that satisfy the following conditions: Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.
Tree,Graph,Topological Sort
Hard
Think inductively. The first step is to get the root. Obviously, the root should be in pairs with all the nodes. If there isn't exactly one such node, then there are 0 ways. The number of pairs involving a node must be less than or equal to that number of its parent. Actually, if it's equal, then there is not exactly 1 way, because they can be swapped. Recursively, given a set of nodes, get the node with the most pairs, then this must be a root and have no parents in the current set of nodes.
604
5
\n```\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n graph = {}\n for x, y in pairs: \n graph.setdefault(x, set()).add(y)\n graph.setdefault(y, set()).add(x)\n \n ans = 1 \n ancestors = set()\n for n in sorted(graph, key=lambda x: len(graph[x]), reverse=True): \n p = min(ancestors & graph[n], key=lambda x: len(graph[x]), default=None) # immediate ancestor \n ancestors.add(n)\n if p: \n if graph[n] - (graph[p] | {p}): return 0 # impossible to have more than ancestor\n if len(graph[n]) == len(graph[p]): ans = 2\n elif len(graph[n]) != len(graph)-1: return 0\n return ans \n```\n\n```\nclass Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n nodes = set()\n graph = {}\n degree = {}\n for x, y in pairs: \n nodes |= {x, y}\n graph.setdefault(x, set()).add(y)\n graph.setdefault(y, set()).add(x)\n degree[x] = 1 + degree.get(x, 0)\n degree[y] = 1 + degree.get(y, 0)\n \n if max(degree.values()) < len(nodes) - 1: return 0 # no root\n for n in nodes: \n if degree[n] < len(nodes)-1: \n nei = set()\n for nn in graph[n]: \n if degree[n] >= degree[nn]: nei |= graph[nn] # brothers & childrens\n if nei - {n} - graph[n]: return 0 # impossible\n \n for n in nodes: \n if any(degree[n] == degree[nn] for nn in graph[n]): return 2 # brothers \n return 1 \n```
89,759
Maximum Number of Eaten Apples
maximum-number-of-eaten-apples
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.
Array,Greedy,Heap (Priority Queue)
Medium
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
4,896
40
\n\n**Explanation**\nFirstly, we create an empty heap. Then go through each pair, add them into a heap, compare and pop unnecessary pairs.\n**Complexity**\n\nTime ```O(N*logN)```\nSpace ```O(N)```\n\n**Python:**\n```\nimport heapq\ndef eatenApples(self, A, D) -> int:\n fin, i = 0, 0\n q = []\n while i<len(A) or q:\n if i<len(A) and A[i]>0:\n heapq.heappush(q, [i+D[i],A[i]])\n while q and (q[0][0]<=i or q[0][1]==0):\n heapq.heappop(q)\n if q:\n q[0][1] -= 1\n fin += 1\n i += 1\n return fin\n```
89,843
Maximum Number of Eaten Apples
maximum-number-of-eaten-apples
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.
Array,Greedy,Heap (Priority Queue)
Medium
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
2,250
15
Explanation:\nYou should keep track of the available apples on daily basis and consume ones which will rot earlier. We can use a heap ```h``` which will store lists. Each list in the heap will contain the data related to the batch of apples of a day. The first element in the list will tell us till how many days the apple in that batch will stay fresh. The second element will tell how many apples are left in the same batch which can be consumed.\n\nComplexity:\nTime ```O(NlogN)``` Each batch will be inserted and popped from the heap once.\nSpace ```O(N)``` Maximum size of the heap.\n\nCode:\n```\nfrom heapq import heappush, heappop\nclass Solution:\n def eatenApples(self, A: List[int], D: List[int]) -> int:\n ans, i, N = 0, 0, len(A)\n h = []\n while i < N or h:\n # only push to heap when you have a valid i, and the apple has atleast one day to stay fresh.\n if i<N and A[i] > 0:\n heappush(h, [i+D[i], A[i]])\n # remove the rotten apples batches and the batches with no apples left (which might have got consumed).\n while h and (h[0][0] <= i or h[0][1] <= 0):\n heappop(h)\n # only if there is batch in heap after removing all the rotten ones, you can eat. else wait for the subsequent days for new apple batch by incrementing i.\n if h:\n h[0][1]-=1\n ans+=1\n i+=1\n return ans \n```\n\n\n\n
89,847
Maximum Number of Eaten Apples
maximum-number-of-eaten-apples
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.
Array,Greedy,Heap (Priority Queue)
Medium
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
1,483
9
Honestly, when I worked on this one, I spent a lot of time to determine some minor details and jumped between the code and description frequently to make sure I am on the right track.. \n\n**To reach the max result, we need to choose the earliest rotten apples to eat.** So We will use a Priority Queue to simulate this selection. \n\nJava:\n\n```\n public int eatenApples(int[] apples, int[] days) {\n int res = 0;\n PriorityQueue<int[]> pq = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);\n int length = apples.length;\n for(int day = 0; day < 40001; day++){\n if (day < length){\n pq.add(new int[]{day + days[day]-1, apples[day]});\n }\n while (!pq.isEmpty()){\n int[] cur = pq.peek();\n if(cur[0] < day){\n pq.poll();\n }else{\n break;\n }\n }\n if (!pq.isEmpty()) {\n int[] cur = pq.poll();\n cur[1]--;\n res += 1;\n if(cur[1] > 0){\n pq.add(cur);\n }\n }\n }\n return res;\n }\n```\n\nPython3:\n\n```\n def eatenApples(self, apples: List[int], expire: List[int]) -> int:\n q=[]\n idx=ans=0\n while q or idx<len(apples):\n if idx<len(apples):\n heapq.heappush(q,[expire[idx]+idx,apples[idx]])\n while q and (q[0][0]<=idx or q[0][1]==0):\n heappop(q)\n if q:\n ans+=1\n q[0][1]-=1\n idx+=1\n return ans\n```
89,852
Maximum Number of Eaten Apples
maximum-number-of-eaten-apples
There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days. Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.
Array,Greedy,Heap (Priority Queue)
Medium
It's optimal to finish the apples that will rot first before those that will rot last You need a structure to keep the apples sorted by their finish time
611
6
If this is given to you personally, what would you do?\nI would eat the apples that are going to rot first.\n\nSo let\'s do that. We need to know how many apples have rotten today so that we throw them away and if we have some apples left, eat one from the lot which is going to rot the earliest. \n\nThis means we need to store all this data in a data structure using which we can know which apples have the shortest life span on this day. This means that if 5 apples were produced on day 1 which will rot in 5 days, then on day 3, their validity is 2 days.\n\nA min-heap seems to be the best data structure to store this. We will always have the fastest rotting apple-lot on the top of the heap that we can consume first.\n\n```python\nfrom heapq import heappush as push\nfrom heapq import heappop as pop\nclass Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n heap = []\n res = 0\n i=0\n N = len(apples)\n while i<N or heap:\n if i<N and apples[i]>0:\n push(heap, [days[i]+i, apples[i]])\n while heap and (heap[0][0]<=i or heap[0][1]<=0):\n pop(heap)\n if heap:\n heap[0][1]-=1\n res+=1\n i+=1\n return res\n```
89,857
Find Minimum Time to Finish All Jobs
find-minimum-time-to-finish-all-jobs
You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job. There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized. Return the minimum possible maximum working time of any assignment.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks
1,517
6
**Algo**\nHere, we simply try out all possibilities but eliminate those that are apparently a waste of time. \n\n**Implementation**\n```\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n jobs.sort(reverse=True)\n \n def fn(i):\n """Assign jobs to worker and find minimum time."""\n nonlocal ans \n if i == len(jobs): ans = max(time)\n else: \n for kk in range(k): \n if not kk or time[kk-1] > time[kk]: \n time[kk] += jobs[i]\n if max(time) < ans: fn(i+1)\n time[kk] -= jobs[i]\n \n ans = inf\n time = [0]*k\n fn(0)\n return ans \n```\n\n**Updated** \nI was previously using `time[kk-1] > time[kk]` as the criterion to prune the backtracking tree which turns out to be incorrect. The condition is updated to `time[kk-1] != time[kk]`. In the meantime, the initial sorting was removed as it is useless. \n```\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n \n def fn(i):\n """Assign jobs to worker and find minimum time."""\n nonlocal ans \n if i == len(jobs): ans = max(time)\n else: \n for kk in range(k): \n if not kk or time[kk-1] != time[kk]: \n time[kk] += jobs[i]\n if max(time) < ans: fn(i+1)\n time[kk] -= jobs[i]\n \n ans = inf\n time = [0]*k\n fn(0)\n return ans \n```
89,922
Maximum XOR With an Element From Array
maximum-xor-with-an-element-from-array
You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.
Array,Bit Manipulation,Trie
Hard
In problems involving bitwise operations, we often think on the bits level. In this problem, we can think that to maximize the result of an xor operation, we need to maximize the most significant bit, then the next one, and so on. If there's some number in the array that is less than m and whose the most significant bit is different than that of x, then xoring with this number maximizes the most significant bit, so I know this bit in the answer is 1. To check the existence of such numbers and narrow your scope for further bits based on your choice, you can use trie. You can sort the array and the queries, and maintain the trie such that in each query the trie consists exactly of the valid elements.
1,619
19
**Algo**\nThis problem is similar to [421. Maximum XOR of Two Numbers in an Array]() which can be solved efficiently via a trie. \n\n**Implementation** (100%)\n```\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted((m, x, i) for i, (x, m) in enumerate(queries))\n ans = [-1]*len(queries)\n \n trie = {}\n k = 0\n for m, x, i in queries: \n while k < len(nums) and nums[k] <= m: \n node = trie\n val = bin(nums[k])[2:].zfill(32)\n for c in val: node = node.setdefault(int(c), {})\n node["#"] = nums[k]\n k += 1\n if trie: \n node = trie\n val = bin(x)[2:].zfill(32)\n for c in val: node = node.get(1-int(c)) or node.get(int(c))\n ans[i] = x ^ node["#"]\n return ans \n```\n\n**Analysis**\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`\n\nEdited on 12/27/2020\nAdding a refactored version below for clarity \n```\nclass Trie: \n def __init__(self):\n self.root = {}\n \n def __bool__(self):\n return bool(self.root)\n \n def insert(self, num):\n node = self.root \n for x in bin(num)[2:].zfill(32): \n node = node.setdefault(int(x), {})\n node["#"] = num\n \n def query(self, num): \n node = self.root\n for x in bin(num)[2:].zfill(32):\n node = node.get(1 - int(x)) or node.get(int(x))\n return num ^ node["#"]\n\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted((m, x, i) for i, (x, m) in enumerate(queries))\n \n ans = [-1]*len(queries)\n k = 0\n trie = Trie()\n for m, x, i in queries: \n while k < len(nums) and nums[k] <= m: \n trie.insert(nums[k])\n k += 1\n if trie: ans[i] = trie.query(x)\n return ans \n```
89,947
Invalid Tweets
invalid-tweets
null
Database
Easy
null
2,425
16
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef invalid_tweets(tweets: pd.DataFrame) -> pd.DataFrame:\n return tweets[\n tweets[\'content\'].str.len() > 15\n ][[\'tweet_id\']]\n```\n```SQL []\nSELECT tweet_id\n FROM Tweets\n WHERE length(content) >= 16;\n```\n\n# Important!\n###### If you like the solution or find it useful, feel free to upvote for it, it will support me in creating high quality solutions)\n\n# 30 Days of Pandas solutions\n\n### Data Filtering \u2705\n- [Big Countries]()\n- [Recyclable and Low Fat Products]()\n- [Customers Who Never Order]()\n- [Article Views I]()\n\n\n### String Methods \u2705\n- [Invalid Tweets]()\n- [Calculate Special Bonus]()\n- [Fix Names in a Table]()\n- [Find Users With Valid E-Mails]()\n- [Patients With a Condition]()\n\n\n### Data Manipulation \u2705\n- [Nth Highest Salary]()\n- [Second Highest Salary]()\n- [Department Highest Salary]()\n- [Rank Scores]()\n- [Delete Duplicate Emails]()\n- [Rearrange Products Table]()\n\n\n### Statistics \u2705\n- [The Number of Rich Customers]()\n- [Immediate Food Delivery I]()\n- [Count Salary Categories]()\n\n\n### Data Aggregation \u2705\n- [Find Total Time Spent by Each Employee]()\n- [Game Play Analysis I]()\n- [Number of Unique Subjects Taught by Each Teacher]()\n- [Classes More Than 5 Students]()\n- [Customer Placing the Largest Number of Orders]()\n- [Group Sold Products By The Date]()\n- [Daily Leads and Partners]()\n\n\n### Data Aggregation \u2705\n- [Actors and Directors Who Cooperated At Least Three Times]()\n- [Replace Employee ID With The Unique Identifier]()\n- [Students and Examinations]()\n- [Managers with at Least 5 Direct Reports]()\n- [Sales Person]()\n
90,002
Maximum Units on a Truck
maximum-units-on-a-truck
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck.
Array,Greedy,Sorting
Easy
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
7,279
85
\u2714\uFE0F ***Solution (Sort & Choose Greedily)***\n\nWe can easiliy observe that it will **always be better to choose the box with maximum number of units** in it so that the overall number of units that can be put on truck is maximized.\n\nThus, we will sort the given *`boxTypes`* array based on number of units in each box. Then we greedily keep choosing the boxes starting from the first one from the sorted array till we fill the whole truck.\n\n**C++**\n```\nint maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {\n\tsort(begin(boxTypes), end(boxTypes), [](auto& a, auto& b){ return a[1] > b[1];}); // sort by number of units / box\n\tint maxUnits = 0;\n\tfor(auto& box : boxTypes) {\n\t\tif(truckSize <= 0) break; // keep choosing greedily till you run out of truckSize \n\t\tmaxUnits += min(truckSize, box[0]) * box[1]; // add (no of box * units) in that box\n\t\ttruckSize -= box[0];\n\t}\n\treturn maxUnits;\n}\n```\n\n---\n\n**Python**\n```\ndef maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n\tboxTypes.sort(key=lambda a:-a[1])\n\tmax_units = 0\n\tfor box in boxTypes:\n\t\tif truckSize < 0 : break\n\t\tmax_units += min(truckSize, box[0]) * box[1]\n\t\ttruckSize -= box[0]\n\treturn max_units\n```\n\n***Time Complexity :*** **`O(NlogN)`**, where *`N`* is the number of elements in *`boxTypes`*\n***Space Complexity :*** **`O(1)`**, we are always using constant amount of space (ignoring the space required by the sort algorithm)\n\n\n---\n\n\u2714\uFE0F ***Solution - II (Similar to Counting sort)***\n\nThe given constraints for `numberOfUnitsPerBox` are small enough that we can use an approach similar to counting sort to reduce the time complexity to `O(N)`.\n\nHere, we can declare an array *`freq`* of size=1000 (which is maximum number of units per box) where *`freq[i]`* will denote the number of boxes that can hold *`i`* number of units. We can iterate through the given *`boxTypes`* array and populate the `freq` array. Then we can iterate over the `freq` array and greedily choose starting from `i=1000 ` till we run out of *`truckSize`* or pick all available boxes.\n\n**C++**\n```\nint maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {\n\tint freq[1001]{0}, maxUnits = 0; // freq[i] = number of boxes that can hold i units\n\tfor(auto& box : boxTypes) freq[box[1]] += box[0];\n\t// greedily choose starting from max units till either truckSize runs out or you choose all boxes\n\tfor(int units = 1000; truckSize > 0 && ~units; --units) { \n\t\tmaxUnits += min(truckSize, freq[units]) * units;\n\t\ttruckSize -= freq[units];\n\t}\n\treturn maxUnits;\n}\n```\n\n---\n\n**Python**\n```\ndef maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n freq, max_units = [0]*1001, 0\n for box in boxTypes:\n freq[box[1]] += box[0]\n for units in range(1000,0,-1):\n if truckSize < 0: break\n max_units += min(truckSize, freq[units]) * units\n truckSize -= freq[units]\n return max_units\n```\n\n***Time Complexity :*** **`O(N)`**\n***Space Complexity :*** **`O(1)`**\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n---
90,050
Maximum Units on a Truck
maximum-units-on-a-truck
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck.
Array,Greedy,Sorting
Easy
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
6,797
46
Be sure to upvote if you thought this solution was helpful!\n\nJoin our discord to ask questions and be part of an interview prep community!\n****\n\n**Intuition**\nEach box takes the same amount of space on the truck. To maximize the total units on the truck, we want to prioritize boxes with more units in them. Let\'s put the boxes with the most units first. This suggests a greedy solution.\n\n**Implementation**\n1. Sort `boxTypes` so that boxes with the most units appear first.\n2. Iterate through the boxes in sorted order.\n3. Instead of counting down one by one how many boxes to take, we can calculate how many boxes of the current type to take by taking `min(truckSize, numberOfBoxes)`. This is because the truck can fit at most `truckSize` more boxes, but we have `numberOfBoxes` left.\n4. Decrease the remaining `truckSize` by subtracting the number of boxes we included.\n\n**Python**\n```python\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n # Sort boxes so that boxes with the most units appear first\n boxTypes.sort(key=lambda box: box[1], reverse=True)\n \n totalUnits = 0\n for numberOfBoxes, unitsPerBox in boxTypes:\n # Take as many boxes until we\'re out of space on the truck\n # or we\'re out of boxes of this type\n numBoxes = min(truckSize, numberOfBoxes)\n totalUnits += numBoxes * unitsPerBox\n truckSize -= numBoxes\n return totalUnits\n \n```\n\n**C++**\n```c++\nclass Solution {\npublic:\n int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {\n // Sort boxes so that boxes with the most units appear first\n sort(boxTypes.begin(), boxTypes.end(), [](auto& box1, auto& box2) {\n return box1[1] > box2[1];\n });\n \n int totalUnits = 0;\n for (auto& box : boxTypes) {\n // Take as many boxes until we\'re out of space on the truck\n // or we\'re out of boxes of this type\n int numBoxes = min(truckSize, box[0]);\n totalUnits += numBoxes * box[1];\n truckSize -= numBoxes;\n }\n return totalUnits;\n }\n};\n```\n\n**Time Complexity**: O(nlogn) - Sorting takes O(nlogn). Iterating through the array takes O(n). The time complexity is dominated by sorting.\n**Space Complexity**: O(1) - No extra space used besides variables.\n**Note**: In some implementations of sort (e.g. Python\'s builtin sort), O(n) space is used during the sort.\n\nThere is an alternative solution to this problem using heap. Join our discord to discuss how to ideas for the heap solution!\n****
90,053
Maximum Units on a Truck
maximum-units-on-a-truck
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck.
Array,Greedy,Sorting
Easy
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
8,394
59
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nFor this problem, we simply need to prioritize the more valuable boxes first. To do this, we should **sort** the boxtypes array (**B**) in descending order by the number of units per box (**B[i][1]**).\n\nThen we can iterate through **B** and at each step, we should add as many of the **boxes** as we can, until we reach the truck size (**T**). We should add the number of **boxes** added multiplied by the units per box to our answer (**ans**), and decrease **T** by the same number of **boxes**.\n\nOnce the truck is full (**T == 0**), or once the iteration is done, we should **return ans**.\n\n - _**Time Complexity: O(N log N)** where **N** is the length of **B**, for the sort_\n - _**Space Complexity: O(1)** to **O(N)** depending on the sort algorithm used_\n\n---\n\n#### ***Javascript Code:***\n```javascript\nvar maximumUnits = function(B, T) {\n B.sort((a,b) => b[1] - a[1])\n let ans = 0\n for (let i = 0; T && i < B.length; i++) {\n let count = Math.min(B[i][0], T)\n ans += count * B[i][1], T -= count\n }\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n```python\nclass Solution:\n def maximumUnits(self, B: List[List[int]], T: int) -> int:\n B.sort(key=lambda x: x[1], reverse=True)\n ans = 0\n for b,n in B:\n boxes = min(b, T)\n ans += boxes * n\n T -= boxes\n if T == 0: return ans\n return ans\n```\n\n---\n\n#### ***Java Code:***\n```java\nclass Solution {\n public int maximumUnits(int[][] B, int T) {\n Arrays.sort(B, (a,b) -> b[1] - a[1]);\n int ans = 0;\n for (int[] b : B) {\n int count = Math.min(b[0], T);\n ans += count * b[1];\n T -= count;\n\t\t\tif (T == 0) return ans;\n }\n return ans;\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n```c++\nclass Solution {\npublic:\n int maximumUnits(vector<vector<int>>& B, int T) {\n sort(B.begin(), B.end(), [](auto& a, auto& b) { return b[1] < a[1];});\n int ans = 0;\n for (auto& b : B) {\n int count = min(b[0], T);\n ans += count * b[1], T -= count;\n\t\t\tif (!T) return ans;\n }\n return ans;\n }\n};\n```
90,057
Maximum Units on a Truck
maximum-units-on-a-truck
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck.
Array,Greedy,Sorting
Easy
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
5,660
31
```\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x:x[1],reverse=1)\n s=0\n for i,j in boxTypes:\n i=min(i,truckSize)\n s+=i*j\n truckSize-=i\n if truckSize==0:\n break\n return s\n```
90,072
Maximum Units on a Truck
maximum-units-on-a-truck
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize. Return the maximum total number of units that can be put on the truck.
Array,Greedy,Sorting
Easy
If we have space for at least one box, it's always optimal to put the box with the most units. Sort the box types with the number of units per box non-increasingly. Iterate on the box types and take from each type as many as you can.
1,094
9
\tclass Solution:\n\t\tdef maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n\t\t\tboxTypes = sorted(boxTypes, key = lambda x : x[1], reverse = True)\n\t\t\toutput = 0\n\t\t\tfor no, units in boxTypes:\n\t\t\t\tif truckSize > no:\n\t\t\t\t\ttruckSize -= no\n\t\t\t\t\toutput += (no * units)\n\t\t\t\telse:\n\t\t\t\t\toutput += (truckSize * units)\n\t\t\t\t\tbreak\n\t\t\treturn output\n\n**If You Like The Solution Upvote.**
90,087
Count Good Meals
count-good-meals
A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7. Note that items with different indices are considered different even if they have the same deliciousness value.
Array,Hash Table
Medium
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
5,528
44
**Algo**\nCompute frequency table of `deliciousness` from which you can check for complement of each `2**k` given a number (since there are only < 30 such power of 2 to consider).\n\n**Implementation**\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n ans = 0\n freq = defaultdict(int)\n for x in deliciousness: \n for k in range(22): ans += freq[2**k - x]\n freq[x] += 1\n return ans % 1_000_000_007\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`\n\nEdited on 1/3/2021\nAdding a 2-pass version\n```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n freq = defaultdict(int)\n for x in deliciousness: freq[x] += 1\n \n ans = 0\n for x in freq: \n for k in range(22): \n if 2**k - x <= x and 2**k - x in freq: \n ans += freq[x]*(freq[x]-1)//2 if 2**k - x == x else freq[x]*freq[2**k-x]\n return ans % 1_000_000_007\n```
90,095
Count Good Meals
count-good-meals
A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7. Note that items with different indices are considered different even if they have the same deliciousness value.
Array,Hash Table
Medium
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
725
5
```\nclass Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n pows = [2 ** i for i in range(0,22)] # form our list of powers of 2\n dp_seen = {} # dict to store what we\'ve seen - dynamic programming solution for time requirement\n count = 0 # to store the answer\n\n for j in range(0, len(deliciousness)):\n for i in range(0, len(pows)):\n if pows[i] - deliciousness[j] in dp_seen: # "if we find a previous deliciousness[j] as pows[i] - deliciousness[j], then we will add dp_seen[deliciousness[j]] to count"\n count += dp_seen[pows[i] - deliciousness[j]]\n if deliciousness[j] in dp_seen:\n dp_seen[deliciousness[j]] += 1 \n else:\n dp_seen[deliciousness[j]] = 1\n \n return count % (10**9 + 7) # the arbitrary modulo, presumably to reduce the answer size\n\t\t```
90,112
Count Good Meals
count-good-meals
A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two. You can pick any two different foods to make a good meal. Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7. Note that items with different indices are considered different even if they have the same deliciousness value.
Array,Hash Table
Medium
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
1,658
5
```\nclass Solution:\n """\n dp -> key: i value: amount of deliciousness == i\n for d in 2**0, 2**1, ..., 2**21\n why 2**21: max of deliciousness is 2*20, sum of 2 max is 2**21\n O(22*N)\n """\n def countPairs(self, ds: List[int]) -> int:\n from collections import defaultdict\n dp = defaultdict(int)\n # ds.sort() # no need to sort\n res = 0\n \n for d in ds:\n for i in range(22):\n # if 2**i - d in dp:\n res += dp[2**i - d]\n dp[d] += 1\n return res % (10**9 + 7)\n \n \n \n \n```
90,118
Ways to Split Array Into Three Subarrays
ways-to-split-array-into-three-subarrays
A split of an integer array is good if: Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.
Array,Two Pointers,Binary Search,Prefix Sum
Medium
Create a prefix array to efficiently find the sum of subarrays. As we are dividing the array into three subarrays, there are two "walls". Iterate over the right wall positions and find where the left wall could be for each right wall position. Use binary search to find the left-most position and right-most position the left wall could be.
7,541
76
**Algo**\nCompute prefix array of `nums`. Any at index `i`, you want to find index `j` such at \n`prefix[i] <= prefix[j] - prefix[i] <= prefix[-1] - prefix[j]`\nThe rest comes out naturally. \n\n**Implementation** \n```\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = 0\n for i in range(1, len(nums)): \n j = bisect_left(prefix, 2*prefix[i])\n k = bisect_right(prefix, (prefix[i] + prefix[-1])//2)\n ans += max(0, min(len(nums), k) - max(i+1, j))\n return ans % 1_000_000_007\n```\n\n**Analysis**\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`\n\nEdit\nAdding two pointers approach `O(N)` time\n```\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = j = k = 0 \n for i in range(1, len(nums)): \n j = max(j, i+1)\n while j < len(nums) and 2*prefix[i] > prefix[j]: j += 1\n k = max(k, j)\n while k < len(nums) and 2*prefix[k] <= prefix[i] + prefix[-1]: k += 1\n ans += k - j \n return ans % 1_000_000_007\n```
90,142
Ways to Split Array Into Three Subarrays
ways-to-split-array-into-three-subarrays
A split of an integer array is good if: Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.
Array,Two Pointers,Binary Search,Prefix Sum
Medium
Create a prefix array to efficiently find the sum of subarrays. As we are dividing the array into three subarrays, there are two "walls". Iterate over the right wall positions and find where the left wall could be for each right wall position. Use binary search to find the left-most position and right-most position the left wall could be.
3,446
23
### Explanation\n- Calculate prefix sum and store at `pre_sum`\n- Iterate each index `i` and consider it as the ending index of the 1st segment\n- Do _**binary search**_ on the 2nd segment ending index. This is doable because `pre_sum` is a non-decreasing array\n\t- `[i+1, j]` is the shortest possible segment of the 2nd segment (`bisect_left`)\n\t\t- Condition to find: `pre_sum[i] * 2 <= pre_sum[j]`\n\t\t- Meaning the 2nd segment sum will not be less than the 1st segment sum\n\t- `[i+1, k-1]` is the longest possible segment of the 2nd segment (`bisect_right`)\n\t\t- Condition to find: `pre_sum[k-1] - pre_sum[i] <= pre_sum[-1] - pre_sum[k-1]`\n\t\t- Meaning the 3rd segment sum will not be less than the 2dn segment sum\n\t- For example, all combinations below will be acceptable\n\t```\n\t\t\t# [0, i], [i+1, j], [j+1, n-1]\n\t\t\t# [0, i], [i+1, j+1], [j+2, n-1]\n\t\t\t# [0, i], [i+1, ...], [..., n-1]\n\t\t\t# [0, i], [i+1, k-2], [k-1, n-1]\n\t\t\t# [0, i], [i+1, k-1], [k, n-1]\n\t```\n- Don\'t forget to handle the edge case when `k == n`\n- Time: `O(NlogN)`\n- Space: `O(N)`\n### Implementation\n```\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n mod, pre_sum = int(1e9+7), [nums[0]]\n for num in nums[1:]: # create prefix sum array\n pre_sum.append(pre_sum[-1] + num)\n ans, n = 0, len(nums)\n for i in range(n): # pre_sum[i] is the sum of the 1st segment\n prev = pre_sum[i] # i+1 is the starting index of the 2nd segment\n if prev * 3 > pre_sum[-1]: break # break loop if first segment is larger than the sum of 2 & 3 segments\n \n j = bisect.bisect_left(pre_sum, prev * 2, i+1) # j is the first possible ending index of 2nd segment\n \n middle = (prev + pre_sum[-1]) // 2 # last possible ending value of 2nd segment\n k = bisect.bisect_right(pre_sum, middle, j+1) # k-1 is the last possible ending index of 2nd segment\n if k-1 >= n or pre_sum[k-1] > middle: continue # make sure the value satisfy the condition since we are using bisect_right here\n ans = (ans + min(k, n - 1) - j) % mod # count & handle edge case\n return ans\n```
90,145
Ways to Split Array Into Three Subarrays
ways-to-split-array-into-three-subarrays
A split of an integer array is good if: Given nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.
Array,Two Pointers,Binary Search,Prefix Sum
Medium
Create a prefix array to efficiently find the sum of subarrays. As we are dividing the array into three subarrays, there are two "walls". Iterate over the right wall positions and find where the left wall could be for each right wall position. Use binary search to find the left-most position and right-most position the left wall could be.
1,055
6
Video with clear visualization and explanation:\n\n\nIntuition: Prefix Sum+Binary Search\n\n**Code**\n\nInspired by \n\n```\nfrom bisect import *\n\nclass Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n mod = 10**9+7\n \n pre_sum = [0]\n for num in nums: \n pre_sum.append(pre_sum[-1]+num)\n \n res = 0\n \n for i in range(1, len(nums)): \n l = bisect_left(pre_sum, 2*pre_sum[i])\n r = bisect_right(pre_sum, (pre_sum[i]+pre_sum[-1])//2)\n res += max(0, min(len(nums), r)-max(i+1, l))\n \n return res%mod\n```\n\nTime: O(nlogn) / Space: O(n)\n\nFeel free to subscribe to my channel. More LeetCoding videos coming up!
90,172
Minimum Operations to Make a Subsequence
minimum-operations-to-make-a-subsequence
You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Array,Hash Table,Binary Search,Greedy
Hard
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
230
5
\n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n # Example: target = [6,4,8,1,3,2]\n dct, lst = {t: i for i,t in enumerate(target)}, [-1] # arr = [4,7,6,2,3,8,6,1]\n # \n for a in arr: # dct: {6:0, 4:1, 8:2, 1:3, 3:4, 2:5} \n if a in dct: # \n # a dct[a] lst \n if dct[a] > lst[-1]: lst.append(dct[a]) # \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\n # 4 1 [-1, 1]\n else: lst[bisect_left(lst, dct[a])] = dct[a] # 7 [-1, 1]\n # 6 0 [-1, 0]\n return 1+len(target)-len(lst) # 2 5 [-1, 0, 5]\n # 3 [-1, 0, 4]\n # 8 2 [-1, 0, 2]\n # 6 [-1, 0, 2]\n # 1 3 [-1, 0, 2, 3]\n\n # return 1+(6)-(4) = 3\n\n```\n[](http://)\n\n\nI could be wrong, but I think that time complexity is *O*(*N*log*N*) and space complexity is *O*(*N*).
90,197
Minimum Operations to Make a Subsequence
minimum-operations-to-make-a-subsequence
You are given an array target that consists of distinct integers and another integer array arr that can have duplicates. In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array. Return the minimum number of operations needed to make target a subsequence of arr. A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Array,Hash Table,Binary Search,Greedy
Hard
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
555
5
**Algo**\nMaintain an increasing array of indices of values in `target`. \n\n**Implementation** \n```\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n loc = {x: i for i, x in enumerate(target)}\n stack = []\n for x in arr: \n if x in loc: \n i = bisect_left(stack, loc[x])\n if i < len(stack): stack[i] = loc[x]\n else: stack.append(loc[x])\n return len(target) - len(stack)\n```\n\n**Analysis**\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`
90,203
Minimum Number of People to Teach
minimum-number-of-people-to-teach
On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer n, an array languages, and an array friendships where: You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.
Array,Greedy
Medium
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
4,450
93
First, find those who can\'t communicate with each other.\nThen, find the most popular language among them.\nThen teach that language to the minority who doesn\'t speak it: \n```\ndef minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n\tlanguages = [set(l) for l in languages]\n\n\tdontspeak = set()\n\tfor u, v in friendships:\n\t\tu = u-1\n\t\tv = v-1\n\t\tif languages[u] & languages[v]: continue\n\t\tdontspeak.add(u)\n\t\tdontspeak.add(v)\n\n\tlangcount = Counter()\n\tfor f in dontspeak:\n\t\tfor l in languages[f]:\n\t\t\tlangcount[l] += 1\n\n\treturn 0 if not dontspeak else len(dontspeak) - max(list(langcount.values()))\n```
90,292
Decode XORed Permutation
decode-xored-permutation
There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.
Array,Bit Manipulation
Medium
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
2,051
63
I was stuck in this seemingly easy question in [contest 44](). How could the answer be unique?\n\n**XOR properties and tips**\n\nLet\'s note `xor` as xor instead of ^\n**1) For `a xor b = c` , you can write \n`b = c xor a` \nor `a = c xor b`** . \nYou can use 2) and 3) to demonstrate 1) .\n2) XOR is commutative, `a xor b = b xor a`\n3) XOR to the same number is always zero `a xor a = 0`\n\n\n# **Intuition**\nIf the first element is determined, the whole array can be decoded.\n> `encoded[i] = perm[i] XOR perm[i + 1]` implies\n\n `perm[i+1] = perm[i] XOR encoded[i]` thanks to 1)\n So you can loop to find the next perm element\nSee [1720. Decode XORed Array]()\n\nBut you still need `perm[0]` , the first element in output array.\n\n\n\n# **Find the first element**\nThat\'s where I was stuck in the contest 44. How could the answer be unique?\nIt took a while to understand after reading other solutions.\n\nI missed an important part in the problem descrition\n> integer array `perm` that is a permutation of the **first `n` positive integers**, where `n` is always odd.\n\nYes, perm is an array with values ranging from [1,2,3 .. n]. The order in the array is permuted.\n\nLet\'s XOR all elements in array `perm`. And perms is an array with **first `n` positive integers**\n`perm[0] XOR perm[1] XOR ... perm[n] = 1 XOR 2 XOR 3 .. XOR n` Order doesn\'t matter, XOR is commutative.\nLet\'s call `totalXor`\n`totalXor = 1 XOR 2 XOR 3 .. XOR n` .\n\nXOR all except the first `perm[0]`\n`perm[0] = totalXor XOR perm[1] XOR perm[2] XOR perm[3] XOR perm[4] XOR ... perm[n]`\n\nLet\'s subsitute (replace) by encoded\n> encoded[i] = perm[i] XOR perm[i + 1]\n\nencoded[1] = perm[1] XOR perm[2]\nencoded[3] = perm[3] XOR perm[4]\n...\nencoded[n-2] = perm[n-2] XOR perm[n-1], remember `n` is the size of perm and is always **odd**\n\n**`perm[0] = totalXor XOR encoded[1] XOR encoded[3] ... encoded[n-2] `**\nOnly the odd indexes of `encoded` are taken.\n\n\n\n\n## Solutions big O\nTime complexity: O(n)\nSpace complexity: O(n)\n\n## Java\n```\n public int[] decode(int[] encoded) {\n int first = 0;\n int n = encoded.length+1;\n for(int i=1;i<=n;i++){\n first ^= i; \n }\n for(int i=1;i<n-1;i+=2) first ^= encoded[i];\n \n int[] perm = new int[n];\n perm[0] = first;\n for(int i=0;i<n-1;i++){\n perm[i+1] = perm[i] ^ encoded[i];\n }\n return perm;\n }\n```\n\n## Kotlin\n```\n fun decode(encoded: IntArray): IntArray {\n var first = 0\n val n = encoded.size + 1\n for(i in 1 .. n){\n first = first xor i\n }\n \n for(i in 1 until n step 2){\n first = first xor encoded[i]\n }\n \n val perm = IntArray(n)\n perm[0] = first\n for (i in 0 until n-1) {\n perm[i + 1] = perm[i] xor encoded[i]\n }\n\n return perm\n }\n```\n\n## Python\n```\n def decode(self, encoded: List[int]) -> List[int]:\n first = 0\n n = len(encoded) + 1\n for i in range(1,n+1):\n first = first ^ i\n\n for i in range(1,n,2):\n first = first ^ encoded[i]\n \n \n perm = [0] * n\n perm[0] = first\n for i in range(n-1):\n perm[i+1] = perm[i] ^ encoded[i]\n return perm\n```\nNot a python pro, the code could be much shorter.
90,344
Decode XORed Permutation
decode-xored-permutation
There is an integer array perm that is a permutation of the first n positive integers, where n is always odd. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1]. Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.
Array,Bit Manipulation
Medium
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
339
5
We use a few of nice properties of XOR:\n\n1. It is _associative_. That is, `(a XOR b) XOR c` is the same as `a XOR (b XOR c)`.\n2. It is _commutative_. That is, `a XOR b = b XOR a`.\n2. It _is its own inverse_. That is, if `a XOR b = c` then `a XOR c = b`.\n\nProperties 2 and 3 mean that if we know `a XOR b = c` and we know two of the values, we can find the third value by XORing the two values that we have. So if we can just figure out the _first_ value in the decoded array, then the rest will fall like dominoes:\n\n```text\ndecoded: x[0], x[1], x[2], ..., x[n-2], x[n-1]\n\t\t\t \\ / \\ / \\ /\nencoded: y[0], y[1], ..., y[n-2]\n\nx[1] = x[0] XOR y[0]\nx[2] = x[1] XOR y[1]\nx[3] = x[2] XOR y[2]\n...\n```\n\nHow do we find `x[0]`? We know the XOR of the entire decoded array, as it comprises the first `n` positive numbers: \n```text\na = 1 XOR 2 XOR ... XOR n\n```\nWe can use property 1 to figure out the XOR of all but the first number of the decoded array:\n```text\nb = x[1] XOR x[2] XOR x[3] XOR x[4] XOR ... XOR x[n-2] XOR x[n-1]\n = (x[1] XOR x[2]) XOR (x[3] XOR x[4]) XOR ... XOR (x[n-2] XOR x[n-1])\n = y[1] XOR y[3] XOR ... XOR y[n-2]\n```\nIt works out nicely because we\'re told that `n` is odd.\n\nNow we have `a`, `b`, and `x[0] XOR b = a`, so we can deduce `x[0] = a XOR b`.\n\n# Python Solution\n\n```python\nfrom functools import reduce\nfrom operator import xor\n\nclass Solution:\n \n def decode(self, encoded: List[int]) -> List[int]:\n n = len(encoded) + 1\n a = reduce(xor, range(1, n+1))\n b = reduce(xor, encoded[1::2])\n result = [a ^ b]\n for y in encoded:\n result.append(result[-1] ^ y)\n return result\n```
90,356
Daily Leads and Partners
daily-leads-and-partners
Table: DailySales Write an SQL query that will, for each date_id and make_name, return the number of distinct lead_id's and distinct partner_id's. Return the result table in any order. The query result format is in the following example.
Database
Easy
null
893
20
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef daily_leads_and_partners(daily_sales: pd.DataFrame) -> pd.DataFrame:\n return daily_sales.groupby(\n [\'date_id\', \'make_name\']\n ).nunique().reset_index().rename(columns={\n \'lead_id\': \'unique_leads\',\n \'partner_id\': \'unique_partners\',\n })\n```\n```SQL []\nSELECT date_id,\n make_name,\n count(DISTINCT lead_id) AS unique_leads,\n count(DISTINCT partner_id) AS unique_partners\n FROM DailySales\n GROUP BY date_id,\n make_name;\n```\n\n# Important!\n###### If you like the solution or find it useful, feel free to **upvote** for it, it will support me in creating high quality solutions)\n\n# 30 Days of Pandas solutions\n\n### Data Filtering \u2705\n- [Big Countries]()\n- [Recyclable and Low Fat Products]()\n- [Customers Who Never Order]()\n- [Article Views I]()\n\n\n### String Methods \u2705\n- [Invalid Tweets]()\n- [Calculate Special Bonus]()\n- [Fix Names in a Table]()\n- [Find Users With Valid E-Mails]()\n- [Patients With a Condition]()\n\n\n### Data Manipulation \u2705\n- [Nth Highest Salary]()\n- [Second Highest Salary]()\n- [Department Highest Salary]()\n- [Rank Scores]()\n- [Delete Duplicate Emails]()\n- [Rearrange Products Table]()\n\n\n### Statistics \u2705\n- [The Number of Rich Customers]()\n- [Immediate Food Delivery I]()\n- [Count Salary Categories]()\n\n\n### Data Aggregation \u2705\n- [Find Total Time Spent by Each Employee]()\n- [Game Play Analysis I]()\n- [Number of Unique Subjects Taught by Each Teacher]()\n- [Classes More Than 5 Students]()\n- [Customer Placing the Largest Number of Orders]()\n- [Group Sold Products By The Date]()\n- [Daily Leads and Partners]()\n\n\n### Data Aggregation \u2705\n- [Actors and Directors Who Cooperated At Least Three Times]()\n- [Replace Employee ID With The Unique Identifier]()\n- [Students and Examinations]()\n- [Managers with at Least 5 Direct Reports]()\n- [Sales Person]()\n\n
90,454
Decode XORed Array
decode-xored-array
There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0]. Return the original array arr. It can be proved that the answer exists and is unique.
Array,Bit Manipulation
Easy
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
6,595
41
\n\n**Explanation**\n**a XOR b = c**, we know the values of **a** and **c**. we use the formula to find **b** -> **a XOR c = b** \n**Complexity**\n\nTime ```O(N)```\nSpace ```O(10)```\n\n**Python:**\n```\ndef decode(self, encoded: List[int], first: int) -> List[int]:\n r = [first]\n for i in encoded:\n r.append(r[-1]^i)\n return r\n```\n\n\n**JAVA** \n```\npublic int[] decode(int[] encoded, int first) {\n int[] res = new int[encoded.length+1];\n res[0] = first;\n for(int i = 0; i < encoded.length; i++)\n res[i+1] = res[i] ^ encoded[i];\n return res;\n }\n```\n\n**C++**\n\n```\nvector<int> decode(vector<int>& encoded, int first) {\n vector<int> res;\n res.push_back(first);\n for(int i = 0; i < encoded.size(); i++)\n res.push_back(res[i] ^ encoded[i]);\n return res;\n }\n\n```
90,518
Decode XORed Array
decode-xored-array
There is a hidden integer array arr that consists of n non-negative integers. It was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3]. You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0]. Return the original array arr. It can be proved that the answer exists and is unique.
Array,Bit Manipulation
Easy
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
1,744
18
```\nclass Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n return [first] + [first:= first ^ x for x in encoded]\n```
90,534
Number Of Rectangles That Can Form The Largest Square
number-of-rectangles-that-can-form-the-largest-square
You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi. You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4. Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen.
Array
Easy
What is the length of the largest square the can be cut out of some rectangle? It'll be equal to min(rectangle.length, rectangle.width). Replace each rectangle with this value. Calculate maxSize by iterating over the given rectangles and maximizing the answer with their values denoted in the first hint. Then iterate again on the rectangles and calculate the number whose values = maxSize.
1,657
18
This can be done just by tracking the max length and its count.\n\n```\ndef countGoodRectangles(rectangles):\n\tmax_len = float(\'-inf\')\n\tcount = 0\n\tfor item in rectangles:\n\t\tmin_len = min(item)\n\t\tif min_len == max_len:\n\t\t\tcount += 1\n\t\telif min_len > max_len:\n\t\t\tmax_len = min_len\n\t\t\tcount = 1\n\n\treturn count
90,610
Number Of Rectangles That Can Form The Largest Square
number-of-rectangles-that-can-form-the-largest-square
You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi. You can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4. Let maxLen be the side length of the largest square you can obtain from any of the given rectangles. Return the number of rectangles that can make a square with a side length of maxLen.
Array
Easy
What is the length of the largest square the can be cut out of some rectangle? It'll be equal to min(rectangle.length, rectangle.width). Replace each rectangle with this value. Calculate maxSize by iterating over the given rectangles and maximizing the answer with their values denoted in the first hint. Then iterate again on the rectangles and calculate the number whose values = maxSize.
459
8
```\n######################################################\n\n# Runtime: 168ms - 100.00%\n# Memory: 14.8MB - 73.29%\n\n######################################################\n\nclass Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n # len_arr is a list where len_arr[i] is the max length of the square\n # that can be formed using rectangle[i] which will be min of length\n # and breadth of that rectangle\n len_arr = [min(rectangle) for rectangle in rectangles]\n # To find how many squares have max len, we first have to find the\n # max len. So, max(len_arr). Now, we need to count how many max len\n # are present in len_arr. So, len_arr.count(max(len_arr)) which is \n # the required answer. so we return it\n return len_arr.count(max(len_arr))\n```
90,622
Maximum Number of Balls in a Box
maximum-number-of-balls-in-a-box
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.
Hash Table,Math,Counting
Easy
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
2,174
11
```\n\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n \n # Function which will take integer number as an input and return it\'s sum\n # if input is 123 then it\'ll return 6 (1+2+3)\n \n def numberSum(number:int)->int:\n sum1 = 0\n while number:\n sum1 += number%10\n number = number //10\n return sum1\n \n # create a hashmap having key as box number and value as box count\n hashMap = defaultdict(int)\n \n for i in range(lowLimit, highLimit+1):\n # pass i to numberSum function inorder to find it\'s sum1\n # Once sum1 is found, we\'ll use this sum1 as our hash_val\n # If box has alreary one ball avaiable then increment it by one\n hash_val = numberSum(i)\n hashMap[hash_val] += 1\n \n # Check balls in every box\n # hashMap.values() will create an array of balls count in each box.\n values = hashMap.values()\n \n # return maximum balls in boxes\n return max(values)\n\n```\n\nUpvote this post if you like it.\nShare your solution below, let\'s discuss it and learn \u270C
90,651
Maximum Number of Balls in a Box
maximum-number-of-balls-in-a-box
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.
Hash Table,Math,Counting
Easy
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
2,291
13
**Algo**\nScan through all numbers from `lowLimit` to `highLimit` and calculate their sum of digits. Maintain a frequency table to keep track of their frequency. \n\n**Implementation**\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n freq = defaultdict(int)\n for x in range(lowLimit, highLimit+1):\n freq[sum(int(xx) for xx in str(x))] += 1\n return max(freq.values())\n```\n\n**Analysis**\nTime complexity `O(NlogM)`\nSpace complexity `O(logN)`
90,652
Maximum Number of Balls in a Box
maximum-number-of-balls-in-a-box
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.
Hash Table,Math,Counting
Easy
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
1,125
7
Approach:\n\nIterate through the ```lowLimit``` and ```highLimit```. While doing so, compute the sum of all the elements of the current number and update it\'s count in the frequency table. \nBasically, ```boxes[sum(element)] += 1```, (boxes is my frequency table). Finally, return ```max(boxes)```.\n```\nclass Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n boxes = [0] * 100\n \n for i in range(lowLimit, highLimit + 1):\n\t\t\t\n\t\t\t# For the current number "i", convert it into a list of its digits.\n\t\t\t# Compute its sum and increment the count in the frequency table.\n\t\t\t\n boxes[sum([int(j) for j in str(i)])] += 1\n \n return max(boxes)\n```
90,658
Maximum Number of Balls in a Box
maximum-number-of-balls-in-a-box
You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1. Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.
Hash Table,Math,Counting
Easy
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
755
6
**Python :**\n\n```\ndef countBalls(self, lowLimit: int, highLimit: int) -> int:\n\tballBox = collections.defaultdict(int)\n\n\tfor i in range(lowLimit, highLimit + 1):\n\t\tballSum = sum([int(i) for i in str(i)])\n\t\tballBox[ballSum] += 1\n\n\treturn max(ballBox.values())\n```\n\n**Like it ? please upvote !**
90,671
Largest Submatrix With Rearrangements
largest-submatrix-with-rearrangements
You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.
Array,Greedy,Sorting,Matrix
Medium
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
10,566
82
![Screenshot 2023-11-26 085349.png]()\n\n<!-- # YouTube Video Explanation:\n\n[]()\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: \n\n*Subscribe Goal: 500 Subscribers*\n*Current Subscribers: 429*\n\n--- -->\n# Example Explanation\nLet\'s break down the process step by step using an example matrix:\n\n**Example Matrix:**\n```\n[\n [0, 0, 1],\n [1, 1, 1],\n [1, 0, 1]\n]\n```\n\n**Step 1: Preprocessing**\n```\n[\n [0, 0, 1],\n [1, 1, 2],\n [2, 0, 3]\n]\n```\n- For each cell `matrix[i][j] = 1`, update it with the height of consecutive 1s ending at this cell (`matrix[i][j] += matrix[i-1][j]`).\n\n**Step 2: Sorting Rows**\nSort each row in non-decreasing order.\n```\n[\n [0, 0, 1],\n [1, 1, 2],\n [0, 2, 3]\n]\n```\n\n**Step 3: Calculate Area**\nIterate through each row and calculate the area for each cell.\n```\n[\n [0, 0, 1], Area: row[j]*k = 1*1\n [1, 1, 2], Area: Max(row[j]*k) = Max(2x1,1x2,1x3)\n [0, 2, 3] Area: Max(row[j]*k) = Max(3x1,2x2)\n]\n```\n- For each cell, the area is the height * width. \n- For example in the last row, we are moving from backwards to forward, so j starts with n-1 and k=1.\n- In the first iteration row[j]= 3 but k = 1, so area becomes 3 but in the next iteration, row[j]=2 and k=2 so the area becomes 4, which is the maximum of all the areas of submatrix.\n\n**Step 4: Maximum Area**\nThe maximum area among all cells is 4.\n\n**Explanation:**\nThe maximum area of the submatrix containing only 1s after rearranging the columns optimally is 4, achieved at `matrix[2][2]`.\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks for the area of the largest submatrix containing only 1s after rearranging the columns optimally. The solution involves preprocessing the matrix to store the height of consecutive 1s ending at each cell. Then, for each row, we sort the heights in non-decreasing order and calculate the area for each possible submatrix.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate through the matrix starting from the second row (`i = 1`).\n2. For each cell `matrix[i][j]`:\n - If `matrix[i][j]` is 1, update it to store the height of consecutive 1s ending at this cell by adding the height of the previous row\'s corresponding cell (`matrix[i - 1][j]`).\n3. After preprocessing, for each row, sort the row in non-decreasing order.\n4. For each cell in the sorted row, calculate the area of the submatrix that ends at this cell, considering the consecutive 1s.\n - The area is given by `height * width`, where `height` is the height of consecutive 1s ending at this cell, and `width` is the position of the cell in the sorted row.\n - Update the maximum area accordingly.\n5. Return the maximum area as the result.\n\n# Complexity\n- Time Complexity: O(m * n * log(n)) - Sorting is done for each row.\n- Space Complexity: O(1) - No additional space is used except for variables.\n\n# Code\n\n```java []\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length, n = matrix[0].length;\n for (int i = 1; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (matrix[i][j] == 1) {\n matrix[i][j] = matrix[i - 1][j] + 1;\n }\n }\n }\n int ans = 0;\n for (var row : matrix) {\n Arrays.sort(row);\n for (int j = n - 1, k = 1; j >= 0 && row[j] > 0; --j, ++k) {\n int s = row[j] * k;\n ans = Math.max(ans, s);\n }\n }\n return ans;\n }\n}\n```\n```cpp []\nclass Solution\n{\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix)\n {\n int m = matrix.size(), n = matrix[0].size();\n int ans = 0;\n for(int j = 0; j < n; j++)\n for(int i = 1; i < m; i++)\n if(matrix[i][j] == 1)\n matrix[i][j] += matrix[i-1][j];\n for(int i = 0; i < m; i++)\n {\n sort(matrix[i].begin(), matrix[i].end());\n reverse(matrix[i].begin(), matrix[i].end());\n for(int j = 0; j < n; j++)\n ans = max(ans, matrix[i][j]*(j+1));\n }\n return ans;\n }\n};\n```\n```python []\nclass Solution(object):\n def largestSubmatrix(self, matrix):\n m, n = len(matrix), len(matrix[0])\n \n for i in range(1, m):\n for j in range(n):\n if matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\n \n ans = 0\n \n for row in matrix:\n row.sort(reverse=True)\n for j in range(n):\n ans = max(ans, row[j] * (j + 1))\n \n return ans\n```\n```javascript []\nvar largestSubmatrix = function(matrix) {\n const m = matrix.length;\n const n = matrix[0].length;\n\n for (let i = 1; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n if (matrix[i][j] === 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n \n let ans = 0;\n \n matrix.forEach(row => {\n row.sort((a, b) => b - a);\n for (let j = 0, k = 1; j < n && row[j] > 0; ++j, ++k) {\n const s = row[j] * k;\n ans = Math.max(ans, s);\n }\n });\n \n return ans;\n};\n```\n<!-- ![upvote1.jpeg]() -->\n
90,690
Largest Submatrix With Rearrangements
largest-submatrix-with-rearrangements
You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order. Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.
Array,Greedy,Sorting,Matrix
Medium
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
3,424
77
# Intuition\nUsing sort for width.\n\n---\n\n# Solution Video\n\n\n\nThese days, many people watch my video more than 70% of whole time, which is good to my channel reputation. Thank you!\n\nI\'m creating this video or post with the goal of ensuring that viewers, whether they read the post or watch the video, won\'t waste their time. I\'m confident that if you spend 10 minutes watching the video, you\'ll grasp the understanding of this problem.\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\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,225\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\nWe should return the largest square in the metrix. Simply formula is\n\n```\nheight * width\n```\nLet\'s think about this.\n```\nInput: matrix = [[0,0,1],[1,1,1],[1,0,1]]\n```\nSince we can rearrange the matrix by entire columns, we can consider entire columns as a height.\n\n### How can we rearrange the matrix?\n\nFor example, we can move entire columns at index 2 to left.\n```\n \u2193 \u2193\n[0,0,1] [0,1,0]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [1,1,0]\n```\nWe can\'t move part of columns like this.\n```\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [1,1,0]\u2190\n```\n### Calculate height at each column.\n```\nAt column index 0\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [2,0,1]\n\nmatrix[0][0] is 0 height.\nmatrix[1][0] is 1 height.\nmatrix[2][0] is 2 height.(= from matrix[1][0] to matrix[2][0])\n```\n```\nAt column index 1\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1] \n[2,0,1] [2,0,1]\n\nmatrix[0][1] is 0 height.\nmatrix[1][1] is 1 height.\nmatrix[2][1] is 0 height.\n```\n```\nAt column index 2\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,2] \n[2,0,1] [2,0,3]\n\nmatrix[0][2] is 1 height.\nmatrix[1][2] is 2 height. (= from matrix[0][2] to matrix[1][2])\nmatrix[2][2] is 3 height. (= from matrix[0][2] to matrix[2][2])\n```\nIn the end\n```\nOriginal\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,2]\n[1,0,1]. [2,0,3]\n```\nIn my solution code, we iterate through each row one by one, then calculate heights. It\'s not difficult. When current number is `1`, add height from above row to current place. You can check it later in my solution code.\n\n### Calculate width at each row.\n\nNext, we need to think about width. We know that if each number is greater than `0`, it means that there is at least `1` in each position, so we can consider non zero position as `1` length for width.\n\nSince we can rearrange the matrix by entire columns, we can sort each row to move zero position to small index(left side).\n\nIn the solution code, we sort each row one by one but image of entire matrix after sorting is like this.\n```\n[0,0,1] [0,0,1]\n[1,1,2] \u2192 [1,1,2]\n[2,0,3] [0,2,3]\n```\nAfter sorting, all zeros in each row move to left side, that means we have some numbers on the right side, so we can consider right side as part of width.\n\nCalculation of each postion\nHeight is each number.\nWidth is length of row - current column index\n```\n[0,0,1]\n[1,1,2]\n[0,2,3]\n\n h w a\nmatrix[0][0]: 0 3 0\nmatrix[0][1]: 0 2 0\nmatrix[0][2]: 1 1 1\nmatrix[1][0]: 1 3 3\nmatrix[1][1]: 1 2 3\nmatrix[1][2]: 2 1 3\nmatrix[2][0]: 0 3 3\nmatrix[2][1]: 2 2 4\nmatrix[2][2]: 3 1 4\n\nh: height\nw: width\na: max area so far\n```\n```\nOutput: 4\n```\n### Are you sure sorting works?\n \nSomebody is wondering "Are you sure sorting works?"\n\nLet\'s focus on `[0,2,3]`. This means at `column index 1`, there is `2` heights and at `column index 2`(different column index from `column index 1`), there are `3` heights.\n\nSo we are sure that we can create this matrix.\n```\n[0,0,1] \n[1,1,1]\n[0,1,1]\n \u2191 \u2191\n 2 3\n```\nThat\'s why at `matrix[2][1]`, we calculate `2`(= height from `matrix[1][1]` to `matrix[2][1]`) * `2`(= width from `matrix[2][1]` to `matrix[2][2]`).\n\nSorting enables the creation of heights from right to left in descending order. In other words, we are sure after `column index 1`, we have `at least 2 height or more`(in this case, we have `3 heights`), so definitely we can calculate size of the square(in this case, `2 * 2`).\n\nThank you sorting algorithm!\nLet\'s wrap up the coding part quickly and grab a beer! lol\n\n---\n\n\n\n### Algorithm Overview:\n\n1. Calculate Heights:\n2. Calculate Maximum Area:\n\n### Detailed Explanation:\n\n1. **Calculate Heights:**\n```python\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n row, col = len(matrix), len(matrix[0])\n\n # Calculate Heights for Each Column\n for i in range(1, row):\n for j in range(col):\n if matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\n```\n\n**Explanation:**\n- This part iterates through each row (starting from the second row) and each column.\n- If the current element is 1 (`matrix[i][j] == 1`), it adds the value from the previous row to the current element.\n- This creates a cumulative sum of heights for each column, forming a "height matrix."\n\n\n2. **Calculate Maximum Area:**\n\n```python\n res = 0\n\n # Calculate Maximum Area\n for i in range(row):\n # Sort the heights in ascending order\n matrix[i].sort()\n\n # Iterate through the sorted heights\n for j in range(col):\n height = matrix[i][j]\n width = col - j\n\n # Calculate the area using the current height and remaining width\n res = max(res, height * width)\n```\n\n**Explanation:**\n- This part initializes `res` to 0, which will store the maximum area.\n- It then iterates through each row of the matrix.\n- For each row, it sorts the heights in ascending order. This is crucial for calculating the maximum area.\n- It iterates through the sorted heights and calculates the area for each height and its corresponding width.\n- The maximum area is updated in the variable `res` if a larger area is found.\n\n\n---\n\n\n\n# Complexity\n- Time complexity: $$O(row * col * log(col))$$\nSort each row and each row has length of col.\n\n- Space complexity: $$O(log col)$$ or $$O(col)$$\nExcept matrix. The sort() operation on the heights array utilizes a temporary working space, which can be estimated as $$O(log col)$$ or $$O(col)$$ in the worst case.\n\n```python []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n row, col = len(matrix), len(matrix[0])\n\n # Calculate heights for each column\n for i in range(1, row):\n for j in range(col):\n if matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\n\n res = 0\n for i in range(row):\n # Sort the heights in ascending order\n matrix[i].sort()\n\n # Iterate through the sorted heights\n for j in range(col):\n height = matrix[i][j]\n width = col - j\n res = max(res, height * width)\n\n return res\n```\n```javascript []\nvar largestSubmatrix = function(matrix) {\n const row = matrix.length;\n const col = matrix[0].length;\n\n // Calculate heights for each column\n for (let i = 1; i < row; i++) {\n for (let j = 0; j < col; j++) {\n if (matrix[i][j] === 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n let res = 0;\n for (let i = 0; i < row; i++) {\n // Sort the heights in ascending order\n matrix[i].sort((a, b) => a - b);\n\n // Iterate through the sorted heights\n for (let j = 0; j < col; j++) {\n const height = matrix[i][j];\n const width = col - j;\n res = Math.max(res, height * width);\n }\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int row = matrix.length;\n int col = matrix[0].length;\n\n // Calculate heights for each column\n for (int i = 1; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (matrix[i][j] == 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n int res = 0;\n for (int i = 0; i < row; i++) {\n // Sort the heights in ascending order\n Arrays.sort(matrix[i]);\n\n // Iterate through the sorted heights\n for (int j = 0; j < col; j++) {\n int height = matrix[i][j];\n int width = col - j;\n res = Math.max(res, height * width);\n }\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int row = matrix.size();\n int col = matrix[0].size();\n\n // Calculate heights for each column\n for (int i = 1; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (matrix[i][j] == 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n int res = 0;\n for (int i = 0; i < row; i++) {\n // Sort the heights in ascending order\n sort(matrix[i].begin(), matrix[i].end());\n\n // Iterate through the sorted heights\n for (int j = 0; j < col; j++) {\n int height = matrix[i][j];\n int width = col - j;\n res = max(res, height * width);\n }\n }\n\n return res; \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: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### 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 solve this question\n`1:56` Calculate left total\n`6:32` Calculate right total\n`11:12` Create answers\n`11:51` Coding\n`14:14` Time Complexity and Space Complexity\n`14:39` Summary of the algorithm with my solution code\n\n
90,693
Maximum Absolute Sum of Any Subarray
maximum-absolute-sum-of-any-subarray
You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). Return the maximum absolute sum of any (possibly empty) subarray of nums. Note that abs(x) is defined as follows:
Array,Dynamic Programming
Medium
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
723
14
**Algo**\nExtend Kadane\'s algo by keeping track of max and min of subarray sum respectively. \n\n**Implementation**\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n ans = mx = mn = 0\n for x in nums: \n mx = max(mx + x, 0)\n mn = min(mn + x, 0)\n ans = max(ans, mx, -mn)\n return ans \n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(1)`
90,819
Maximum Absolute Sum of Any Subarray
maximum-absolute-sum-of-any-subarray
You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr). Return the maximum absolute sum of any (possibly empty) subarray of nums. Note that abs(x) is defined as follows:
Array,Dynamic Programming
Medium
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
480
5
Use of one kadane\'s algorithm to compute max absolute sum and anothe kadane\'s to compute min absolute sum, return max comparing both\n\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n min_sum = nums[0]\n curr_min = nums[0]\n \n max_sum = nums[0]\n curr_max = max_sum\n \n for i in range(1, len(nums)):\n curr_max = max(nums[i], curr_max + nums[i])\n max_sum = max(curr_max, max_sum)\n \n for i in range(1, len(nums)):\n curr_min = min(nums[i], curr_min + nums[i])\n min_sum = min(curr_min, min_sum)\n \n return max(abs(max_sum), abs(min_sum))\n```
90,832
Minimum Length of String After Deleting Similar Ends
minimum-length-of-string-after-deleting-similar-ends
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: Return the minimum length of s after performing the above operation any number of times (possibly zero times).
Two Pointers,String
Medium
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
599
9
**C++ :**\n\n```\nint minimumLength(string s) {\n\tif(s.length() <= 1)\n\t\treturn s.length();\n\n\tint l = 0, r = s.length() - 1;\n\n\twhile(l < r && s[l] == s[r])\n\t{\n\t\tchar ch = s[l];\n\n\t\twhile(l <= r && s[l] == ch)\n\t\t\t++l;\n\n\t\twhile(l <= r && s[r] == ch)\n\t\t\t--r;\n\n\t}\n\n\treturn r - l + 1;\n}\n```\n\n**Python :**\n\n```\ndef minimumLength(self, s: str) -> int:\n\tif len(s) <= 1:\n\t\treturn len(s)\n\n\twhile len(s) > 1 and s[0] == s[-1]:\n\t\ti = 0\n\t\twhile i + 1 < len(s) and s[i] == s[i + 1]:\n\t\t\ti += 1\n\n\t\tj = len(s) - 1\n\t\twhile j - 1 > 0 and s[j] == s[j - 1] and j != i:\n\t\t\tj -= 1\n\n\t\ts = s[i + 1:j]\n\n\treturn len(s)\n```\n\n**Like it ? please upvote !**
90,851
Minimum Length of String After Deleting Similar Ends
minimum-length-of-string-after-deleting-similar-ends
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: Return the minimum length of s after performing the above operation any number of times (possibly zero times).
Two Pointers,String
Medium
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
393
5
```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n i,j=0,len(s)-1\n while i<j and s[i]==s[j]:\n t=s[i]\n while i<len(s) and s[i]==t:\n i+=1\n while j>=0 and s[j]==t:\n j-=1\n if j<i:\n return 0\n return j-i+1\n```\n\n**An upvote will be encouraging**
90,853
Latest Time by Replacing Hidden Digits
latest-time-by-replacing-hidden-digits
You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?). The valid times are those inclusively between 00:00 and 23:59. Return the latest valid time you can get from time by replacing the hidden digits.
String,Greedy
Easy
Trying out all possible solutions from biggest to smallest would fit in the time limit. To check if the solution is okay, you need to find out if it's valid and matches every character
2,726
28
**Algo**\nReplace `?` based on its location and value. \n\n**Implementation**\n```\nclass Solution:\n def maximumTime(self, time: str) -> str:\n time = list(time)\n for i in range(len(time)): \n if time[i] == "?": \n if i == 0: time[i] = "2" if time[i+1] in "?0123" else "1"\n elif i == 1: time[i] = "3" if time[0] == "2" else "9"\n elif i == 3: time[i] = "5"\n else: time[i] = "9"\n return "".join(time)\n```\n\n**Analysis**\n`O(1)` for fixed size problem
90,946
Latest Time by Replacing Hidden Digits
latest-time-by-replacing-hidden-digits
You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?). The valid times are those inclusively between 00:00 and 23:59. Return the latest valid time you can get from time by replacing the hidden digits.
String,Greedy
Easy
Trying out all possible solutions from biggest to smallest would fit in the time limit. To check if the solution is okay, you need to find out if it's valid and matches every character
607
5
```\nclass Solution:\n def maximumTime(self, time: str) -> str:\n s=list(time)\n for i in range(len(s)):\n if s[i]==\'?\':\n if i==0:\n if s[i+1] in [\'0\',\'1\',\'2\',\'3\',\'?\']:\n s[i]=\'2\'\n else:\n s[i]=\'1\'\n elif i==1:\n if s[i-1]==\'1\' or s[i-1]==\'0\':\n s[i]=\'9\'\n else:\n s[i]=\'3\'\n elif i==3:\n s[i]=\'5\'\n elif i==4:\n s[i]=\'9\'\n return \'\'.join(s)\n```\n***Please Upvote, if you found my solution helpful***
90,953
Find Kth Largest XOR Coordinate Value
find-kth-largest-xor-coordinate-value
You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find the kth largest value (1-indexed) of all the coordinates of matrix.
Array,Divide and Conquer,Bit Manipulation,Heap (Priority Queue),Matrix,Prefix Sum,Quickselect
Medium
Use a 2D prefix sum to precalculate the xor-sum of the upper left submatrix.
1,486
16
**Algo**\nCompute `xor` of at `(i, j)` as `xor[i][j] = xor[i-1][j] ^ xor[i][j-1] ^ xor[i-1][j-1] ^ matrix[i][j]`. The return the `k`th largest among observed. \n\n**Implementation**\n```\nclass Solution:\n def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:\n m, n = len(matrix), len(matrix[0]) # dimensions \n \n ans = []\n for i in range(m): \n for j in range(n): \n if i: matrix[i][j] ^= matrix[i-1][j]\n if j: matrix[i][j] ^= matrix[i][j-1]\n if i and j: matrix[i][j] ^= matrix[i-1][j-1]\n ans.append(matrix[i][j])\n return sorted(ans)[-k] \n```\n\n**Analysis**\nTime complexity `O(MNlog(MN))` (`O(MN)` is possible via quick select)\nSpace complexity `O(MN)`\n\nEdited on 1/24/2021\nAdding two more implementation for improved time complexity \n`O(MNlogK)` time & `logK` space \n```\nclass Solution:\n def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:\n m, n = len(matrix), len(matrix[0]) # dimensions \n \n pq = []\n for i in range(m): \n for j in range(n): \n if i: matrix[i][j] ^= matrix[i-1][j]\n if j: matrix[i][j] ^= matrix[i][j-1]\n if i and j: matrix[i][j] ^= matrix[i-1][j-1]\n heappush(pq, matrix[i][j])\n if len(pq) > k: heappop(pq)\n return pq[0]\n```\n\n\n`O(MN)` time & `O(MN)` space \n```\nclass Solution:\n def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:\n m, n = len(matrix), len(matrix[0]) # dimensions \n \n vals = []\n for i in range(m): \n for j in range(n): \n if i: matrix[i][j] ^= matrix[i-1][j]\n if j: matrix[i][j] ^= matrix[i][j-1]\n if i and j: matrix[i][j] ^= matrix[i-1][j-1]\n vals.append(matrix[i][j])\n \n def part(lo, hi): \n """Partition vals from lo (inclusive) to hi (exclusive)."""\n i, j = lo+1, hi-1\n while i <= j: \n if vals[i] < vals[lo]: i += 1\n elif vals[lo] < vals[j]: j -= 1\n else: \n vals[i], vals[j] = vals[j], vals[i]\n i += 1\n j -= 1\n vals[lo], vals[j] = vals[j], vals[lo]\n return j \n \n lo, hi = 0, len(vals)\n while lo < hi: \n mid = part(lo, hi)\n if mid + k < len(vals): lo = mid + 1\n else: hi = mid\n return vals[lo]\n```
91,049
Building Boxes
building-boxes
You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: Given an integer n, return the minimum possible number of boxes touching the floor.
Math,Binary Search,Greedy
Hard
Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in? The first box should always start in the corner
732
12
**Algo**\nThe **1st observation** is that the base increases as 1, 1+2, 1+2+3, 1+2+3+4, ... When the bases is of the form 1+2+3+...+x, there can be at most `1*x + 2*(x-1) + 3*(x-2) + ... + x*1 = x*(x+1)*(x+2)//6` blocks. So we find the the largest `x` such that `x*(x+1)*(x+2)//6 <= n` as the starting point for which there will be `x*(x+1)//2` blocks at the bottom. \n\nThe **2nd observation** is that once we add blocks to a well-developed piramid \nnext block add 1 bottom block\nnext 2 blocks add 1 bottom block\nnext 3 blocks add 1 bottom block\nThen we can just count how many bottom blocks to add to obsorb all `n` blocks. \n\n**Implementation**\n```\nclass Solution:\n def minimumBoxes(self, n: int) -> int:\n x = int((6*n)**(1/3))\n if x*(x+1)*(x+2) > 6*n: x -= 1\n \n ans = x*(x+1)//2\n n -= x*(x+1)*(x+2)//6\n k = 1\n while n > 0: \n ans += 1\n n -= k\n k += 1\n return ans \n```\n\n**Analysis**\nTime complexity `O(sqrt(N))`\nSpace complexity `O(1)`\n\n**Edited on 1/24/2021**\nAdding a `O(1)` solution\nThis implementation is to elaborate on the aforementioned algo. Here, we solve two equations. First, we find largest integer `x` such that `x*(x+1)*(x+2) <= 6*n`. This represents a fully-developed piramid with `x*(x+1)*(x+2)//6` blocks and `x*(x+1)//2` bottom blocks. \nThen, we remove `x*(x+1)*(x+2)//6` from `n`. For the remaining blocks (`rem = n - x*(x+1)*(x+2)//6`), suppose we need another `y` bottom blocks. Then, `1 + 2 + ... + y = y*(y+1) >= rem`, where `y` can be calculated by solving the quadratic equation. \n\n```\nclass Solution:\n def minimumBoxes(self, n: int) -> int:\n x = int((6*n)**(1/3))\n if x*(x+1)*(x+2) > 6*n: x -= 1\n n -= x*(x+1)*(x+2)//6\n return x*(x+1)//2 + ceil((sqrt(1+8*n)-1)/2)\n```
91,099
Restore the Array From Adjacent Pairs
restore-the-array-from-adjacent-pairs
There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order. Return the original array nums. If there are multiple solutions, return any of them.
Array,Hash Table
Medium
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
7,699
42
![Screenshot 2023-11-10 080013.png]()\n\n# YouTube Video Explanation:\n\n[]()\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: \n\n*Subscribe Goal: 250 Subscribers*\n*Current Subscribers: 209*\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves reconstructing the original array from the adjacent pairs. We know that each element in the original array is unique, but the order of the elements is not given. To solve this, we can create a mapping of each element to its adjacent elements using a dictionary. We iterate through the adjacent pairs and build this mapping.\n\nNext, we find the starting element that has only one adjacent element (the first element in the original array) and begin building the original array from there. We use a result array to store the elements of the original array as we traverse the adjacent pairs.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a dictionary `pairs` to store the mapping of each element to its adjacent elements. Initialize it with empty arrays.\n2. Iterate through the adjacent pairs, updating the `pairs` dictionary.\n3. Find the starting element (the one with only one adjacent element) and set it as the first element in the result array.\n4. Continue building the result array by choosing the adjacent element of the current element and updating the current element. Repeat this process until we have reconstructed the entire array.\n5. Return the result array as the original array.\n\n\n# Complexity\n- Time complexity:`O(N)`, We iterate through the adjacent pairs once to build the mapping, which takes O(n) time. We then iterate through the adjacent pairs again to reconstruct the original array, which also takes O(n) time. Overall, the time complexity of the algorithm is O(n).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity:`O(N)`, We use extra space to store the `pairs` dictionary and the result array, resulting in O(n) space complexity.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n## Java\n```\nclass Solution {\n public int[] restoreArray(int[][] vals) {\n Map<Integer, int[]> pairs = new HashMap<>();\n for (int i = 0; i < vals.length; i++) {\n if (pairs.containsKey(vals[i][0])) {\n pairs.get(vals[i][0])[1] = vals[i][1];\n } else {\n pairs.put(vals[i][0], new int[] {vals[i][1], -1000000});\n }\n if (pairs.containsKey(vals[i][1])) {\n pairs.get(vals[i][1])[1] = vals[i][0];\n } else {\n pairs.put(vals[i][1], new int[] {vals[i][0], -1000000});\n }\n }\n int[] result = new int[vals.length + 1];\n int start = -1000000;\n for (Map.Entry<Integer, int[]> entry : pairs.entrySet()) {\n if (entry.getValue()[1] == -1000000) {\n start = entry.getKey();\n }\n }\n result[0] = start;\n int left = -1000000;\n for (int i = 1; i < result.length; i++) {\n int[] val = pairs.get(start);\n int newval = (val[0] == left ? val[1] : val[0]);\n result[i] = newval;\n left = start;\n start = newval;\n }\n return result;\n }\n}\n\n```\n## C++\n```\nclass Solution {\npublic:\n std::vector<int> restoreArray(std::vector<std::vector<int>>& vals) {\n std::unordered_map<int, std::vector<int>> pairs;\n \n for (const std::vector<int>& val : vals) {\n pairs[val[0]].push_back(val[1]);\n pairs[val[1]].push_back(val[0]);\n }\n \n std::vector<int> result;\n int start = -1000000;\n \n for (const auto& entry : pairs) {\n if (entry.second.size() == 1) {\n start = entry.first;\n break;\n }\n }\n \n int left = -1000000;\n result.push_back(start);\n \n for (int i = 1; i < vals.size() + 1; ++i) {\n const std::vector<int>& val = pairs[start];\n int newval = (val[0] == left) ? val[1] : val[0];\n result.push_back(newval);\n left = start;\n start = newval;\n }\n \n return result;\n }\n};\n```\n## Python\n```\nclass Solution(object):\n def restoreArray(self, vals):\n pairs = defaultdict(list)\n \n for val in vals:\n pairs[val[0]].append(val[1])\n pairs[val[1]].append(val[0])\n \n result = []\n start = -1000000\n \n for entry in pairs:\n if len(pairs[entry]) == 1:\n start = entry\n break\n \n left = -1000000\n result.append(start)\n \n for i in range(1, len(vals) + 1):\n val = pairs[start]\n newval = val[0] if val[0] != left else val[1]\n result.append(newval)\n left = start\n start = newval\n \n return result\n```\n## JavaScript\n```\nvar restoreArray = function(vals) {\n const pairs = new Map();\n \n for (const val of vals) {\n if (!pairs.has(val[0])) pairs.set(val[0], []);\n if (!pairs.has(val[1])) pairs.set(val[1], []);\n pairs.get(val[0]).push(val[1]);\n pairs.get(val[1]).push(val[0]);\n }\n \n const result = [];\n let start = -1000000;\n \n for (const [entry, values] of pairs) {\n if (values.length === 1) {\n start = entry;\n break;\n }\n }\n \n let left = -1000000;\n result.push(start);\n \n for (let i = 1; i <= vals.length; i++) {\n const val = pairs.get(start);\n const newval = val[0] !== left ? val[0] : val[1];\n result.push(newval);\n left = start;\n start = newval;\n }\n \n return result;\n};\n```\n---\n![upvote1.jpeg]()\n
91,140
Restore the Array From Adjacent Pairs
restore-the-array-from-adjacent-pairs
There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order. Return the original array nums. If there are multiple solutions, return any of them.
Array,Hash Table
Medium
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
8,216
95
# Intuition\nTry to find numbers that have only one adjacent number.\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:04` A key point to solve this question\n`1:09` How do you know adjacent number of each number?\n`2:33` Demonstrate how it works\n`6:07` Coding\n`9:07` Time Complexity and Space Complexity\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,021\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 yesterday. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nLook at this.\n```\n[1,2,3,4]\n```\n\nSimply, edge of numbers(= `1`,`4`) have one adjacent number and inside of the array(= `2`,`3`) have two adjacent numbers.\n\nSo, the numbers that have one adjacent number should be start number or end number. But we don\'t have care about start number or end number because the description says "If there are multiple solutions, return any of them". That means we can return `[1,2,3,4]` or `[4,3,2,1]`.\n\n---\n\n\u2B50\uFE0F Points\n\nTry to find numbers that have only one adjacent number. The numbers should be start number or end number. We can start from one of them.\n\n---\n\n- How do you know adjacent number of each number?\n\nThe next question is how you know adjacent number of each number.\n\nMy answer is simply to create adjacent candidate list.\n\n```\nInput: adjacentPairs = [[2,1],[3,4],[3,2]]\n```\nFrom the input, we can create this. We use `HashMap`. In solution code `graph`.\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\n\n2: [1, 3]\n\u2192 1 from [2:1], 3 from [3,2]\n\n1: [2]\n\u2192 2 from [2,1]\n\n3: [4, 2]\n\u2192 4 from [3,4], 2 from [3,2]\n\n4: [3]\n\u2192 3 from [3,4]\n\nvalues are adjacent candidate numbers of the key number\n```\n\nWhat are the numbers that have only one adjacent number? The answer is `1` or `4`. We can take one of them. I start with `1`.\n\n```\nres = [1, 2]\n```\nWe know that `2` is adjacent number of `1`, so add `2` to `res` after `1`.\n\nThen we check candidates of the last number which is `2` in this case.\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\n```\nThe candidates are `1` or `3`. It\'s obvious that `3` is the next adjacent number right?\n\nIn solution code, we can compare like if candidate number is not `1`, that is the next number because `1` is left adjacent number of `2`. Now we are tyring to find right adjacent number of `2`. That\'s why before we compare the numbers, we take the last two numbers of `res`, so that we can compare them easily.\n\nLet\'s see how it works!\n\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\nres = [1, 2]\n\nlast = 2\nprev = 1\n\nCheck last values\ncandidates = [1, 3] (from 2: [1, 3])\n\ncompare candidates[0] != prev\ntrue \u2192 the next number is candidates[0](= 1)\nfalse \u2192 the next number is candidates[1](= 3)\n\nIn this case, it\'s false. so add 3 to res\n\nIn the end, res = [1, 2, 3]\n```\nLet\'s go next. Take the last two numbers from `res`.\n```\n{2: [1, 3], 1: [2], 3: [4, 2], 4: [3]}\nres = [1, 2, 3]\n\nlast = 3\nprev = 2\n\nCheck last values\ncandidates = [4, 2] (from 3: [4, 2])\n\ncompare candidates[0] != prev\ntrue \u2192 the next number is candidates[0](= 4)\nfalse \u2192 the next number is candidates[1](= 2)\n\nIn this case, it\'s true. so add 4 to res\n\nres = [1, 2, 3, 4]\n```\nThen we stop.\n\n```\nOutput: [1, 2, 3, 4]\n```\n\nEasy\uFF01\uD83D\uDE06\nLet\'s see a real algorithm!\n\nI added comments in Python code. I hope it helps you understand solution code.\n\n---\n\n\n\n### Algorithm Overview:\n\nThe algorithm aims to restore an array given a list of adjacent pairs. It uses a graph representation to model the adjacent relationships and then iteratively builds the array.\n\n### Detailed Explanation:\n\n1. **Create a Graph:**\n - Initialize an empty graph using a `defaultdict` to represent adjacent pairs. Iterate through the given pairs, and for each pair `[u, v]`, add `v` to the list of neighbors of `u` and vice versa.\n\n ```python\n graph = defaultdict(list)\n for u, v in pairs:\n graph[u].append(v)\n graph[v].append(u)\n ```\n\n2. **Initialize Result List:**\n - Initialize an empty list `res` to store the elements of the restored array.\n\n ```python\n res = []\n ```\n\n3. **Find Starting Node:**\n - Iterate through the nodes in the graph and find the starting node with only one neighbor. Set `res` to contain this starting node and its neighbor.\n\n ```python\n for node, neighbors in graph.items():\n if len(neighbors) == 1:\n res = [node, neighbors[0]]\n break\n ```\n\n4. **Build the Array:**\n - Use a `while` loop to continue building the array until its length matches the number of pairs plus one.\n\n ```python\n while len(res) < len(pairs) + 1:\n last, prev = res[-1], res[-2] # Get the last two elements in the result array\n candidates = graph[last] # Find the candidates for the next element\n next_element = candidates[0] if candidates[0] != prev else candidates[1] # Choose the candidate that is not the previous element\n res.append(next_element) # Append the next element to the result array\n ```\n\n5. **Return Result:**\n - Return the final restored array.\n\n ```python\n return res\n ```\n\nIn summary, the algorithm builds the array by selecting adjacent elements based on the graph representation until the array is fully restored. The starting point is identified by finding a node with only one neighbor. The process continues until the array\'s length matches the number of pairs.\n\n# Complexity\n- Time complexity: $$O(n)$$\n`n` is the number of pairs.\n\n- Space complexity: $$O(n)$$\n`n` is the number of pairs.\n\n```python []\nclass Solution:\n def restoreArray(self, pairs: List[List[int]]) -> List[int]:\n # Create a graph to represent adjacent pairs\n graph = defaultdict(list)\n for u, v in pairs:\n graph[u].append(v)\n graph[v].append(u)\n\n # Initialize the result list\n res = []\n\n # Find the starting node with only one neighbor\n for node, neighbors in graph.items():\n if len(neighbors) == 1:\n res = [node, neighbors[0]]\n break\n\n # Continue building the array until its length matches the number of pairs\n while len(res) < len(pairs) + 1:\n # Get the last two elements in the result array\n last, prev = res[-1], res[-2]\n\n # Find the candidates for the next element\n candidates = graph[last]\n\n # Choose the candidate that is not the previous element\n next_element = candidates[0] if candidates[0] != prev else candidates[1]\n\n # Append the next element to the result array\n res.append(next_element)\n\n return res\n```\n```javascript []\n/**\n * @param {number[][]} adjacentPairs\n * @return {number[]}\n */\nvar restoreArray = function(adjacentPairs) {\n const graph = new Map();\n\n for (const [u, v] of adjacentPairs) {\n if (!graph.has(u)) graph.set(u, []);\n if (!graph.has(v)) graph.set(v, []);\n graph.get(u).push(v);\n graph.get(v).push(u);\n }\n\n let result = [];\n\n for (const [node, neighbors] of graph.entries()) {\n if (neighbors.length === 1) {\n result = [node, neighbors[0]];\n break;\n }\n }\n\n while (result.length < adjacentPairs.length + 1) {\n const [last, prev] = [result[result.length - 1], result[result.length - 2]];\n const candidates = graph.get(last);\n const nextElement = candidates[0] !== prev ? candidates[0] : candidates[1];\n result.push(nextElement);\n }\n\n return result; \n};\n```\n```java []\nclass Solution {\n public int[] restoreArray(int[][] adjacentPairs) {\n Map<Integer, List<Integer>> graph = new HashMap<>();\n\n for (int[] pair : adjacentPairs) {\n graph.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);\n graph.computeIfAbsent(pair[1], k -> new ArrayList<>()).add(pair[0]);\n }\n\n List<Integer> result = new ArrayList<>();\n\n for (Map.Entry<Integer, List<Integer>> entry : graph.entrySet()) {\n if (entry.getValue().size() == 1) {\n result.add(entry.getKey());\n result.add(entry.getValue().get(0));\n break;\n }\n }\n\n while (result.size() < adjacentPairs.length + 1) {\n int last = result.get(result.size() - 1);\n int prev = result.get(result.size() - 2);\n List<Integer> candidates = graph.get(last);\n int nextElement = candidates.get(0) != prev ? candidates.get(0) : candidates.get(1);\n result.add(nextElement);\n }\n\n return result.stream().mapToInt(Integer::intValue).toArray(); \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {\n unordered_map<int, vector<int>> graph;\n\n for (const auto& pair : adjacentPairs) {\n graph[pair[0]].push_back(pair[1]);\n graph[pair[1]].push_back(pair[0]);\n }\n\n vector<int> result;\n\n for (const auto& entry : graph) {\n if (entry.second.size() == 1) {\n result = {entry.first, entry.second[0]};\n break;\n }\n }\n\n while (result.size() < adjacentPairs.size() + 1) {\n int last = result[result.size() - 1];\n int prev = result[result.size() - 2];\n const vector<int>& candidates = graph[last];\n int nextElement = (candidates[0] != prev) ? candidates[0] : candidates[1];\n result.push_back(nextElement);\n }\n\n return result; \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:05` Explain constructor and addEdge function\n`1:31` Explain shortestPath\n`3:29` Demonstrate how it works\n`11:47` Coding\n`17:17` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\n\u2B50\uFE0F **Including all posts from yesterday, my post reached the top spot for the first time!**\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:04` Let\'s find a solution pattern\n`1:38` A key point to solve Count Number of Homogenous Substrings\n`2:20` Demonstrate how it works with all the same characters\n`4:55` What if we find different characters\n`7:13` Coding\n`8:21` Time Complexity and Space Complexity
91,146
Restore the Array From Adjacent Pairs
restore-the-array-from-adjacent-pairs
There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums. It is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order. Return the original array nums. If there are multiple solutions, return any of them.
Array,Hash Table
Medium
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
1,676
11
\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n adjs=collections.defaultdict(set)\n for i,j in adjacentPairs:\n adjs[i].add(j)\n adjs[j].add(i)\n\n for node,adj in adjs.items():\n if len(adj)==1:\n break\n ans=[node]\n while adjs[node]:\n new=adjs[node].pop()\n ans.append(new)\n adjs[new].remove(node)\n node=new\n return ans \n```
91,164
Palindrome Partitioning IV
palindrome-partitioning-iv
Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​ A string is said to be palindrome if it the same string when reversed.
String,Dynamic Programming
Hard
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
1,035
11
**Algo**\nDefine `fn(i, k)` to be `True` if `s[i:]` can be split into `k` palindromic substrings. Then, \n\n`fn(i, k) = any(fn(ii+1, k-1) where s[i:ii] == s[i:ii][::-1]`\n\nHere we create a mapping to memoize all palindromic substrings starting from any given `i`. \n\n**Implementation**\n```\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n mp = {}\n for i in range(2*len(s)-1): \n lo, hi = i//2, (i+1)//2\n while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: \n mp.setdefault(lo, set()).add(hi)\n lo -= 1\n hi += 1\n \n @lru_cache(None)\n def fn(i, k): \n """Return True if s[i:] can be split into k palindromic substrings."""\n if k < 0: return False \n if i == len(s): return k == 0\n return any(fn(ii+1, k-1) for ii in mp[i])\n \n return fn(0, 3)\n```\n\n**Analysis**\nTime complexity `O(N^2)`\nSpace complexity `O(N^2)`\n\nEdited on 2/1/2021\nAdding an alternative implementation\n```\nclass Solution:\n def checkPartitioning(self, s: str) -> bool:\n mp = defaultdict(set)\n for i in range(2*len(s)-1): \n lo, hi = i//2, (i+1)//2\n while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: \n mp[lo].add(hi)\n lo, hi = lo-1, hi+1\n \n for i in range(len(s)):\n for j in range(i+1, len(s)):\n if i-1 in mp[0] and j-1 in mp[i] and len(s)-1 in mp[j]: return True\n return False \n```
91,208
Can You Eat Your Favorite Candy on Your Favorite Day?
can-you-eat-your-favorite-candy-on-your-favorite-day
You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. You play a game with the following rules: Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return the constructed array answer.
Array,Prefix Sum
Medium
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
2,778
41
### Explanation:\n\nWe have given count of all candies of a particular type, \nNow as I have to eat all the candies of `type < i` before eating candy of `type i`, so we can have a prefix sum array for candies count\n(int array elements can overflow)\n\nAs for each query, we have\n* **type**\n* **day**\n* **capacity**\n\nNow, \nmax and min day required to eat are \n`maxDay = prefix[type+1]-1;`\n`minDay = prefix[type]/capacity;`\n\nIf, day lies between max and min day then query is `true`\nelse `false`\n\n### Code:\n \n**C++**\n```\nclass Solution {\npublic:\n vector<bool> canEat(vector<int>& candies, vector<vector<int>>& queries) {\n int n = candies.size();\n vector<long long> prefix(n+1, 0);\n for(int i=1; i<n+1; ++i) prefix[i] = prefix[i-1] + candies[i-1];\n \n vector<bool> ans;\n for(auto &query: queries){\n long long type = query[0], day = query[1], capacity = query[2];\n long long maxDay = prefix[type+1]-1;\n long long minDay = prefix[type]/capacity;\n \n if(day <= maxDay && day >= minDay) ans.push_back(true);\n else ans.push_back(false);\n }\n \n return ans;\n }\n};\n```\n \n**Java** `(by @karthiko)`\n```\nclass Solution {\n // T = O(n) S=O(n)\n public boolean[] canEat(int[] candiesCount, int[][] queries) {\n // calculate prefix sum\n long[] prefix = new long[candiesCount.length+1];\n boolean[] res = new boolean[queries.length];\n prefix[0] = 0;\n \n for(int i=1; i< prefix.length; i++)\n prefix[i] = prefix[i-1]+candiesCount[i-1];\n \n for(int i=0; i< res.length; i++) {\n int type = queries[i][0];\n int day = queries[i][1];\n int cap = queries[i][2];\n \n // max and min day required to eat\n // if we eat one candy per day including type candy (prefix[type+1]). we decrement by 1 since we need atleast one candy of type\n long maxDay = prefix[type+1]-1; \n // if we eat upto capacity each day upto previous candy\n long minDay = prefix[type]/cap; \n \n // check if query day is within the limits (minDay and maxDay inclusive)\n res[i] = (minDay <= day && day <= maxDay); \n }\n \n return res;\n }\n}\n```\n \n**Python** `(by @chimao)`\n```\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n result = [False] * len(queries)\n presum = [0] + candiesCount[:]\n for i in range(1, len(presum)):\n presum[i] += presum[i - 1]\n \n for idx, val in enumerate(queries):\n candType, favDate, cap = val\n mx = presum[candType + 1] - 1\n mn = presum[candType]//cap\n if mn <= favDate <= mx:\n result[idx] = True\n \n return result\n```
91,242
Can You Eat Your Favorite Candy on Your Favorite Day?
can-you-eat-your-favorite-candy-on-your-favorite-day
You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. You play a game with the following rules: Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return the constructed array answer.
Array,Prefix Sum
Medium
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
421
6
**Algo**\nCompute the prefix sum of `candiesCount`. For a given query (`t`, `day` and `cap`), the condition for `True` is \n`prefix[t] < (day + 1) * cap and day < prefix[t+1]`\nwhere the first half reflects the fact that if we eat maximum candies every day we can reach the preferred one and the second half means that if we eat minimum candies (i.e. one candy) every day we won\'t pass the preferred one. \n\n**Implementation**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n prefix = [0]\n for x in candiesCount: prefix.append(prefix[-1] + x) # prefix sum \n return [prefix[t] < (day+1)*cap and day < prefix[t+1] for t, day, cap in queries]\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)`
91,247
Can You Eat Your Favorite Candy on Your Favorite Day?
can-you-eat-your-favorite-candy-on-your-favorite-day
You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. You play a game with the following rules: Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return the constructed array answer.
Array,Prefix Sum
Medium
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
588
7
**Explanation:**\n\nLets take the below test case\n```\ncandiesCount = [7, 4, 5, 3, 8]\nqueries = [[0, 2, 2], [4, 2, 4], [2, 13, 1000000000]]\n```\n\nWe need to know the total number of candies available till ```i-1``` for each type ```i``` as we will have to eat all candies before ```i```th type. So we use accumulate.\n\n```accumulate``` will turn ```[7, 4, 5, 3, 8]``` to ```[7, 7 + 4, 7 + 4 + 5, 7 + 4 + 5 + 3, 7 + 4 + 5 + 3 + 8]``` = ```[7, 11, 16, 19, 27]```\n\nWe have two cases - for type 0 and type > 0. It can be generalised if we add a dummy 0 in candiesCount at the beginning.\n\n**Case 1: Type 0**\n* In the first query ```[0, 2, 2]```, you have to be able to eat type 0 candy on day 2 by not eating more than 2 candies on any given day.\n* Since its type 0 candy, there\'s no i-1. \n* So if type is 0, all you need to check is, whether the number of candies of 0th type (here, it\'s 7) is greater than the favourite day.\n* Why? - Because, even if you consider cap as 1, you can eat 1 candy each day and you\'ll have atleast one candy remaining on fav day.\n* Edge case: Number of candies = Number of days\n\t* Since we are starting at day 0, number of candies need to be greater than number of days.\n\t* Say you have 8 candies of type 0 and you fav day is 8. You will eat 1 candy each day from 0, 1,...till 7, so you will run out of candies on day 8.\n\n**Case 2: Type greater than 0**\n* If type is not 0, you need to eat all candies till i-1.\n* In this case, number of candies to eat is accumulated value till i-1 plus 1 candy of type i.\n\n\t```A = list(accumulate(candiesCount)) # equals [7, 11, 16, 19, 27]```\n\n* In the ```[4, 2, 4]``` query, fav type is 4. So you need to eat 19 candies (i-1) plus 1 = 20. This has to be done on day 2.\n* Since you can eat only max of 4 candies per day, 4 (day 0) + 4 (day 1) + 4 (day 2), you can eat only max of 12.\n* Suppose if you were able to eat 8 per day, then 8*3=24 which is greater than 20, so this is possible.\n\n* So, you need to check whether number of candies to be eaten is less than or equal to ```(day + 1) * cap``` --> day + 1 because we start at day 0\n* And you also need to check if number of candies you have is greater than number of days (this is same as case 1)\n* Reason - you may have 48 candies to eat but if day is 48, you won\'t have candy even if its cap is 1.\n\n**Code:**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n A = list(accumulate(candiesCount))\n res = []\n for type, day, cap in queries:\n if type == 0:\n res.append(A[0] > day)\n else:\n to_be_eaten = A[type-1] + 1\n res.append(to_be_eaten <= ((day + 1) * cap) and A[type] > day)\n return res\n```\n\n**Generalised version for both cases by adding 0 in beginning:**\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n A = [0] + list(accumulate(candiesCount))\n res = []\n for type, day, cap in queries:\n to_be_eaten = A[type] + 1\n res.append(to_be_eaten <= ((day + 1) * cap) and A[type + 1] > day)\n return res\n```
91,248
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
744
11
# 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 longestNiceSubstring(self, s: str) -> str:\n\n if len(s)<2:\n return ""\n valid=True\n for i in range(len(s)):\n if ord(s[i])>95 and s[i].upper() in s:\n continue\n elif ord(s[i])<95 and s[i].lower() in s:\n continue\n else:\n valid=False\n break\n if valid:\n return s\n else:\n right=self.longestNiceSubstring(s[:i])\n left=self.longestNiceSubstring(s[i+1:])\n \n if len(left)<=len(right):\n return right\n else:\n return left \n\n```
91,296
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
8,648
79
\n```\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n ans = ""\n for i in range(len(s)):\n for ii in range(i+1, len(s)+1):\n if all(s[k].swapcase() in s[i:ii] for k in range(i, ii)): \n ans = max(ans, s[i:ii], key=len)\n return ans \n```\n\nEdited on 2/23/2021\nApparently, the small size doesn\'t give me enough motivation to seek more efficient algo. Below is the implementation of divide and conquer in Python3 of this [post](). This is indeed a lot faster than the naive solution above. Credit goes to original author. \n```\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n if not s: return "" # boundary condition \n ss = set(s)\n for i, c in enumerate(s):\n if c.swapcase() not in ss: \n s0 = self.longestNiceSubstring(s[:i])\n s1 = self.longestNiceSubstring(s[i+1:])\n return max(s0, s1, key=len)\n return s\n```
91,301
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
3,551
41
This post is inspired by \n\'s-bad-to-use-small-constraint-and-mark-it-as-an-easy-problem\n\nI want to explain to myself how one can optimize step by step from O(N^2) brute force solution to the optimal solution O(N). \n\n## Approach 1: Brute Force\nThe intuition is simple. We basically check every possible substring to see if it\'s a nice string. We also keep record of the current longest nice substring by remembering the start index of the substring as well as the length of it.\n\n```python\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n N = len(s)\n maxlen = 0\n start = 0\n for i in range(N):\n seen = set()\n missing = 0\n for j in range(i, N):\n\t\t\t# if we haven\'t seen this "type", add it into the seen set\n if s[j] not in seen: \n seen.add(s[j])\n\t\t\t\t\t# since this is the first time we see this "type" of character\n\t\t\t\t\t# we check if the other half has already been seen before\n if (s[j].lower() not in seen) or (s[j].upper() not in seen):\n missing += 1 # we haven\'t seen the other half yet, so adding 1 to the missing type\n else: # otherwise we know this character will compensate the other half which we pushed earlier into the set, so we subtract missing "type" by 1\n missing -= 1\n if missing == 0 and (j - i + 1) > maxlen:\n maxlen = j - i + 1\n start = i\n return s[start:(start + maxlen)]\n```\n**Complexity Analysis**\n\nTime Complexity: O(N^2)\nSpace Complexity: O(26) There are only 26 lowercase English characters\n\n## Approach 2: Divide and Conquer\nThe key observation here is that if a character doesn\'t have its other half (different case but same character) in the given string, it can\'t be included into any of the nice substring.\nFor instance, let\'s look at string **"abcBCEAamM"**. We notice that every alphabet has both cases present in the string except character **E**. So any nice string can\'t have **E** in it. In other words, the longest nice substring must be either in **E**\'s left side or its right side, namely **"abcBC"** or **"AamM"**. We notice that we just create 2 subproblems to find the longest nice substring in **"abcBC"** and **"AamM"**. \n\nWhen we get result from solving left subproblem and right subproblem, we simply compare the length of two strings and return the one with longer length. Note that if both strings have the same length, we need to return the left one since the problem statement explicitly mentions: **If there are multiple, return the substring of the earliest occurrence.**\n\nNow what if we don\'t see any un-paired character after we go through the string? That\'s good because that means the original string is a nice string, so we simply return it since it must be the longest one.\n\nWhat\'s the base case? Well, if the length of string is less than 2, it can\'t be a nice string, so we return empty string in that case.\n\n``` python\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n def helper(i: int, j: int):\n\t\t # string length is less than 2 return empty string\n\t\t # we return a tuple to indicate the start and end index of the string to avoid unncessary string copy operation\n if j - i + 1 < 2: return (0, -1)\n hashset = set()\n\t\t\t# scan the string once and save all char into a set\n for k in range(i, j + 1):\n hashset.add(s[k])\n \n for k in range(i, j + 1):\n\t\t\t # if this char pairs with its other half, we are good\n if s[k].upper() in hashset and s[k].lower() in hashset:\n continue\n\t\t\t # we found `E` !\n slt = helper(i, k - 1)\n srt = helper(k + 1, j)\n return slt if (slt[1] - slt[0] + 1) >= (srt[1] - srt[0] + 1) else srt\n return (i, j)\n lt, rt = helper(0, len(s) - 1)\n return s[lt:(rt + 1)]\n```\n\n**Complexity Analysis**\n\nTime Complexity: O(N x Log(N)) Doesn\'t this look similar to quick sort? In each recursion call, we use O(N) to build the hash set and find the position of un-paired character. Then we create two subproblems whose size was reduced. Ideally if we could reduce size of each subproblem to N/2 every time, then O(N x Log(N) will be the answer for all possible input. However, just like quick sort, dividing each subproblem to N/2 every time is not guaranteed. Consider the following input: **"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"**\n\nEvery time we divide our subproblem to **""** and **"aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"**. It only reduces the subproblem size by 1. So time complexity for this input will be **O(N^2)**\n\nSpace Complexity: **O(N)** There are only 26 lowercase English characters, so the space used by hash set is constant. However, we need to take recursion into consideration. In the worst case we mentioned above, the recursion depth can reach **N**. \n\n## Approach 3: Improved Divide and Conquer\nIf we look at string "AbMab**E**cBC**E**Aam**E**MmdDaA", we notice the un-paired character E appears at multiple location in the original string. That means we can divide our original string into subproblems using E as delimeter:\n**"AbMab"\n"cBC"\n"Aam"\n"MmdDaA"**\n\nWe know one of the factors that determine the time complexity of divide and conqure algorithm is the depth of the recursion tree. Why does dividing subproblems in this way help improve the time complexity? Because every time we are removing one alphabet completely from the data set. There are only 26 lowercase English characters, so at most we only need to remove **26** times, which means the depth of recursion tree is bound to **26**\n\n``` python\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n def helper(i: int, j: int):\n if (j - i + 1) < 2: return (0,-1)\n\n hashset = set()\n for k in range(i, j + 1):\n hashset.add(s[k])\n # use parts array to store position (index) of delimeter in sorted order\n parts = [i - 1]\n for k in range(i, j + 1):\n up = s[k].upper()\n lower = s[k].lower()\n if (up not in hashset) or (lower not in hashset): # un-paired character\n parts.append(k)\n parts.append(j+1) \n\t\t\t# why do we have i - 1 and j + 1 in the array?\n\t\t\t# go through this example aAbbcCEdDEfF\n\t\t\t# the subproblems are:\n\t\t\t# [0, 5], [7, 8], [10, 11]\n max_len_pair = (0, -1)\n\t\t\t# if we don\'t find any delimeter, then the original string is a nice string\n if len(parts) == 2:\n return (i, j)\n\t\t\t# call recursively to solve each subproblem\n for i in range(len(parts) - 1):\n ni, nj = helper(parts[i] + 1, parts[i+1] - 1)\n if (nj - ni + 1) > (max_len_pair[1] - max_len_pair[0] + 1):\n max_len_pair = (ni, nj)\n \n return max_len_pair\n \n lt, rt = helper(0, len(s) - 1)\n return s[lt:(rt+1)]\n```\n**Complexity Analysis**\n\nTime Complexity: O(N x 26) = O(N). Recall the recursion depth is bound to 26\nLet\'s look at the worst case in approach 2 this time **"aaaaaaaa"**\nThe first time we call recursion function, we find **a** is un-paired so we created 9 subprolems of size 0. So it takes O(9) = O(N) to solve it\n\nSpace Complexity: O(26) = O(1). The hashset can contain at most 26 unique characters. The recursion depth is bound to 26\n\n\n
91,305
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
253
7
# 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 longestNiceSubstring(self, s: str) -> str:\n def pper(s):\n for i in s:\n if i.lower() in s and i.upper() in s:\n pass\n else:\n return False\n return True \n m=""\n for i in range(len(s)):\n for j in range(i+1,len(s)):\n if pper(s[i:j+1]) and len(m)<len(s[i:j+1]):\n m=s[i:j+1]\n return m\n```
91,311
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
1,695
20
E.g. if we are given "YazaAay"\n\n\nThen if we see, all the characters have their lowercase and uppercase variants except only "z".\n\nThis means that we can never have a valid subarray with "z" in it. \n\nSo, we need to look for a valid subarray before "z" and after "z" only. \n\nIn this string there is only one invalid character but there can be multiple. So, we simply create a set of all the characters and then, while looping over the string, just check if that character has its case variation in the set or not. If not, that means it is an invalid character and we need to find the valid substring before and after this character\'s index. So we will make two recursive calls. One for finding a valid substring from beginning to the invalid character\'s index (excluding it) and the other to find a valid substring from the invalid character\'s index + 1 to the end of the string.\n\nAnd if we get a valid substring out of both or even from just one, that means, just return the one that\'s longer.\n\nIt is also possible that a string is already nice. e.g. "aAa". In this case, the recursive calls won\'t be made since they are only made when we encounter an invalid character. So in such cases, we can return the string itself at the end. \n\n\n```\ndef longestNiceSubstring(self, s: str) -> str:\n \n # If length of string is less than 2, there is no way we can get a nice substring out of it\n if len(s) < 2 : return ""\n \n # A set of all characters in the given string\n ulSet = set(s)\n \n for i,c in enumerate(s):\n # If character is lowercase and the set does not have its uppercase variation or vice versa\n # It means that we need to not consider this character at all and so, find the longest substring till this character and after this character\n # Repeat this till we reach the end\n if c.swapcase() not in ulSet:\n s1 = self.longestNiceSubstring(s[0:i])\n s2 = self.longestNiceSubstring(s[i+1:])\n \n return s2 if len(s2) > len(s1) else s1\n \n \n # If the above recursive calls don\'t happen that means our string has each character in lowercase and uppercase already so we can return it\n return s\n```
91,312
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
714
7
# Intuition\nWe are using recursion here\n\n# Approach\nWe find the first letter in the string which doesn\'t have complementary and divide string into two substrings - and so on until we find the string without single letters\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n sSet = set(s)\n for i in range(len(s)):\n if s[i].lower() not in sSet or s[i].upper() not in sSet:\n lns1 = self.longestNiceSubstring(s[:i])\n lns2 = self.longestNiceSubstring(s[i+1:])\n\n return max(lns1, lns2, key=len)\n\n return s\n\n```
91,319
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
3,516
12
The intuition behind my approach is to check validity for substings starting with the longest one and decreasing our window size.\n\nThe difficult part was determining how to write a function that would determine "niceness." The intuition behind the function I wrote is that if we compare the number of unique characters in a substring and the number of unique characters in the same substring but lowercased, a "nice" substring would have the property that `len(set(substring.lower())) == len(set(substring))`, since each lowercase letter must have a corresponding uppercase letter.\n\n```\nclass Solution:\n def get_nice(self, s: str) -> bool:\n return len(set(s.lower())) == (len(set(s)) // 2)\n \n def longestNiceSubstring(self, s: str) -> str:\n window_size = len(s)\n \n while window_size:\n for i in range(len(s) - window_size + 1):\n substring = s[i:i + window_size]\n \n if self.get_nice(substring):\n return substring\n \n window_size -= 1\n \n return \'\'\n```
91,324
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
2,365
13
```\nclass Solution:\n def longestNiceSubstring(self, s: str) -> str:\n def divcon(s):\n\t\t # string with length 1 or less arent considered nice\n if len(s) < 2:\n return ""\n \n pivot = []\n # get every character that is not nice\n for i, ch in enumerate(s):\n if ch.isupper() and ch.lower() not in s:\n pivot.append(i)\n if ch.islower() and ch.upper() not in s:\n pivot.append(i)\n\t\t\t# if no such character return the string\n if not pivot:\n return s\n\t\t\t# divide the string in half excluding the char that makes the string not nice\n else:\n mid = (len(pivot)) // 2\n return max(divcon(s[:pivot[mid]]),divcon(s[pivot[mid]+1:]),key=len)\n \n return divcon(s)\n```
91,325
Longest Nice Substring
longest-nice-substring
A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not. Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
Hash Table,String,Bit Manipulation,Sliding Window
Easy
Brute force and check each substring to see if it is nice.
1,950
11
**Brute Force**:\n```\nclass Solution:\n def longestNiceSubstring(self, s):\n subs = [s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)]\n nice = [sub for sub in subs if set(sub)==set(sub.swapcase())]\n return max(nice, key=len, default="")\n```\n\n**Divide and Conquer ([Credit]())**:\n```\nclass Solution:\n def longestNiceSubstring(self, s):\n chars = set(s)\n for i, c in enumerate(s):\n if c.swapcase() not in chars:\n return max(map(self.longestNiceSubstring, [s[:i], s[i+1:]]), key=len)\n return s\n```
91,327
Form Array by Concatenating Subarrays of Another Array
form-array-by-concatenating-subarrays-of-another-array
You are given a 2D integer array groups of length n. You are also given an integer array nums. You are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups). Return true if you can do this task, and false otherwise. Note that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.
Array,Greedy,String Matching
Medium
When we use a subarray, the room for the next subarrays will be the suffix after the used subarray. If we can match a group with multiple subarrays, we should choose the first one, as this will just leave the largest room for the next subarrays.
1,847
33
\n```\nclass Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n i = 0\n for grp in groups: \n for ii in range(i, len(nums)):\n if nums[ii:ii+len(grp)] == grp: \n i = ii + len(grp)\n break \n else: return False\n return True\n```
91,348
Tree of Coprimes
tree-of-coprimes
There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0. To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree. Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y. An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself. Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.
Math,Tree,Depth-First Search,Breadth-First Search
Hard
Note that for a node, it's not optimal to consider two nodes with the same value. Note that the values are small enough for you to iterate over them instead of iterating over the parent nodes.
1,051
10
**Algo**\nThis is a typical DFS problem. However, the amont of nodes can be huge `10^5` but the values only vary from `0` to `50`. Due to this reason, we can organize what have been seen in a value to location mapping to reduce the amount of nodes to check. \n\n**Implementation**\n```\nclass Solution:\n def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:\n tree = {} # tree as adjacency list \n for u, v in edges: \n tree.setdefault(u, []).append(v)\n tree.setdefault(v, []).append(u)\n \n ans = [-1]*len(nums)\n path = {} # val -> list of position & depth \n seen = {0}\n \n def fn(k, i): \n """Populate ans via dfs."""\n ii = -1 \n for x in path:\n if gcd(nums[k], x) == 1: # coprime \n if path[x] and path[x][-1][1] > ii: \n ans[k] = path[x][-1][0]\n ii = path[x][-1][1]\n \n path.setdefault(nums[k], []).append((k, i))\n for kk in tree.get(k, []): \n if kk not in seen: \n seen.add(kk)\n fn(kk, i+1)\n path[nums[k]].pop()\n \n \n fn(0, 0)\n return ans \n```\n\n**Analysis**\nTime complexity `O(N)` (`O(50N)` to be more specific)\nSpace complexity `O(N)`
91,397
Map of Highest Peak
map-of-highest-peak
You are given an integer matrix isWater of size m x n that represents a map of land and water cells. You must assign each cell a height in a way that follows these rules: Find an assignment of heights such that the maximum height in the matrix is maximized. Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.
Array,Breadth-First Search,Matrix
Medium
Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources.
549
6
### Explanation\n- Start from *water* nodes and BFS until all heights are found\n- NOTE: You don\'t need to worry about getting a skewed peak (by *skewed*, I mean a height with difference greater than 1 on some neighbors), because it will never be possible\n\t- For example: following situation will never be possible\n\t\t```\n\t\t1 2\n\t\t1 0\n\t\t```\n\t- This is because we are using BFS and increment at 1 for each step, in this case, for any node at `(i, j)`, whenever the value is assigned, it will be the highest possible value\n\t- If the same node is re-visited in later step, it can only be the same or larger (larger will be wrong, since you will get a skewed peak), thus, no need to revisited any assigned node `(i, j)`\n### Implementation\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n arr = collections.deque()\n m, n = len(isWater), len(isWater[0])\n for i in range(m):\n for j in range(n):\n if isWater[i][j] == 1:\n arr.append((0, i, j))\n \n ans = [[-1] * n for _ in range(m)]\n while arr:\n val, x, y = arr.popleft() \n if ans[x][y] != -1: continue\n ans[x][y] = val\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n xx, yy = x+dx, y+dy\n if 0 <= xx < m and 0 <= yy < n and ans[xx][yy] == -1:\n arr.append((val+1, xx, yy))\n return ans\n```
91,454
Map of Highest Peak
map-of-highest-peak
You are given an integer matrix isWater of size m x n that represents a map of land and water cells. You must assign each cell a height in a way that follows these rules: Find an assignment of heights such that the maximum height in the matrix is maximized. Return an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.
Array,Breadth-First Search,Matrix
Medium
Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources.
548
7
\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n m, n = len(isWater), len(isWater[0]) # dimensions \n queue = [(i, j) for i in range(m) for j in range(n) if isWater[i][j]]\n \n ht = 0\n ans = [[0]*n for _ in range(m)]\n seen = set(queue)\n \n while queue: \n newq = []\n for i, j in queue: \n ans[i][j] = ht\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in seen: \n newq.append((ii, jj))\n seen.add((ii, jj))\n queue = newq\n ht += 1\n return ans \n```\n\nAlternative implementation\n```\nclass Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n m, n = len(isWater), len(isWater[0]) # dimensions \n \n ans = [[-1]*n for _ in range(m)]\n queue = deque()\n for i in range(m): \n for j in range(n):\n if isWater[i][j]:\n queue.append((i, j))\n ans[i][j] = 0\n\n while queue: \n i, j = queue.popleft()\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and ans[ii][jj] == -1: \n ans[ii][jj] = 1 + ans[i][j]\n queue.append((ii, jj))\n return ans \n```
91,457
Check if Array Is Sorted and Rotated
check-if-array-is-sorted-and-rotated
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.
Array
Easy
Brute force and check if it is possible for a sorted array to start from each position.
5,363
34
# \uD83D\uDDEF\uFE0FIntuition :-\n<!-- Describe your first thoughts on how to solve this problem. -->\nif array is sorted and rotated then, there is only 1 break point where (nums[x] > nums[x+1]),\nif array is only sorted then, there is 0 break point.\n\n# ***Please do Upvote \u270C\uFE0F***\n\n# \uD83D\uDDEF\uFE0FComplexity :-\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# \uD83D\uDDEF\uFE0FCode :-\n```\nclass Solution {\npublic:\n bool check(vector<int>& nums) {\n int count=0;\n for(int i=0;i<nums.size();i++){\n if(nums[i]>nums[(i+1)%nums.size()])\n count++;\n }\n return (count<=1);\n }\n};\n```\n\n# **-->why am I doing %size??**\n\nConcider this case: nums = [2,1,3,4]\n\nThis case will give you result true without %size but it is not sorted and rotated. So we have to check last and first element also.
91,565
Check if Array Is Sorted and Rotated
check-if-array-is-sorted-and-rotated
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.
Array
Easy
Brute force and check if it is possible for a sorted array to start from each position.
6,760
19
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize two pointers, left and right, to the first and last indices of the array nums, respectively.\n2. While left is less than right, do the following:\na. Compute the middle index mid as the average of left and right, rounded down to an integer.\nb. If nums[mid] > nums[right], then the rotation point must be in the subarray to the right of mid, so update left to mid + 1.\nc. Else if nums[mid] < nums[right], then the rotation point must be in the subarray to the left of mid, so update right to mid.\nd. Else, decrement right by 1, since we can\'t determine which subarray contains the rotation point.\n3. Return true if left is equal to right and nums is sorted in non-decreasing order, otherwise return false.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(logn)\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# ------------------------------------------------------------- Do Not Forget to Upvote-----------------------\n# Code\n```\nclass Solution {\npublic:\n bool check(vector<int>& nums) {\n int count=0;\n int n =nums.size();\n for(int i=1;i<n;i++)\n {\n if(nums[i-1]>nums[i])\n {\n count++;\n }\n }\n if(count>1)\n {\n return false;\n }\n if(nums[n-1]>nums[0] && count!=0)\n {\n return false;\n }\n return true;\n \n }\n};\n```\n# python code\n```\ndef check_rotation(nums):\n left, right = 0, len(nums) - 1\n while left < right:\n mid = (left + right) // 2\n if nums[mid] > nums[right]:\n left = mid + 1\n elif nums[mid] < nums[right]:\n right = mid\n else:\n right -= 1\n return left == right and all(nums[i] <= nums[i+1] for i in range(len(nums)-1))\n```\n# java code\n```\npublic static boolean checkRotation(int[] nums) {\n int left = 0, right = nums.length - 1;\n while (left < right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] > nums[right]) {\n left = mid + 1;\n } else if (nums[mid] < nums[right]) {\n right = mid;\n } else {\n right--;\n }\n }\n return left == right && isNonDecreasing(nums);\n}\n\nprivate static boolean isNonDecreasing(int[] nums) {\n for (int i = 0; i < nums.length - 1; i++) {\n if (nums[i] > nums[i+1]) {\n return false;\n }\n }\n return true;\n}\n```
91,567
Check if Array Is Sorted and Rotated
check-if-array-is-sorted-and-rotated
Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false. There may be duplicates in the original array. Note: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.
Array
Easy
Brute force and check if it is possible for a sorted array to start from each position.
1,836
10
Time Complexity: O(N)\nSpace Complexity: O(1)\n\n# Approach and Implementation\nTo implement a solution for this problem, you should be aware of what happens when you rotate a sorted array.\n\nLook at the image below. We have a sorted and rotated array:\n![Rotated and sorted array]()\nThe array is rotated 2 times.\n![Rotated and sorted array]()\n\n\nNotice how you only have `one break point`, i.e., `arr[i-1] > arr[i]` happens only once between the elements **5** and **1**.\n\nThis ensures that the arrays is rotated properly and we do not have a random array. \n\nSo now, we have `one breaks`:\n1. Between elements 5 and 1\n\n\n`We can generalize this as nums[i-1] > nums[i]`\n\n# Code\n``` Python []\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n # Initialize the break variable to 0\n breaks = 0\n\n # Iterate over the len(nums)\n for i in range(len(nums)):\n # If you find any break case, increment the break variable\n if nums[i] < nums[i-1]:\n breaks += 1\n \n # If there is atmost 1 breaks, return True\n # Else, return False\n return True if breaks <= 1 else False\n\n```\n``` C++ []\nclass Solution {\npublic:\n bool check(vector<int>& nums) {\n // Initialize the break variable to 1\n int breaks = 0;\n\n // Iterate over the len(nums)\n for(int i = 0; i < nums.size(); i++){\n // If you find any break case, increment the break variable\n if(nums[(i+1) % nums.size()] < nums[i])\n breaks++;\n }\n\n // If there is atmost 1 breaks, return True\n // Else, return False\n return breaks <= 1;\n\n }\n};\n\n```\n\n
91,573
Maximum Score From Removing Stones
maximum-score-from-removing-stones
You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.
Math,Greedy,Heap (Priority Queue)
Medium
It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation
443
9
# 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:1\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:1\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n return min((a+b+c)//2,a+b+c-max(a,b,c))\n```
91,612
Maximum Score From Removing Stones
maximum-score-from-removing-stones
You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves). Given three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.
Math,Greedy,Heap (Priority Queue)
Medium
It's optimal to always remove one stone from the biggest 2 piles Note that the limits are small enough for simulation
1,134
18
\n```\nclass Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n a, b, c = sorted((a, b, c))\n if a + b < c: return a + b\n return (a + b + c)//2\n```
91,627
Largest Merge Of Two Strings
largest-merge-of-two-strings
You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options: Return the lexicographically largest merge you can construct. A string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.
Two Pointers,String,Greedy
Medium
Build the result character by character. At each step, you choose a character from one of the two strings. If the next character of the first string is larger than that of the second string, or vice versa, it's optimal to use the larger one. If both are equal, think of a criteria that lets you decide which string to consume the next character from. You should choose the next character from the larger string.
585
6
**Algo**\nDefine two pointers `i1` and `i2` for `word1` and `word2` respectively. Pick word from `word1` iff `word1[i1:] > word2[i2]`.\n\n**Implementation**\n```\nclass Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n ans = []\n i1 = i2 = 0\n while i1 < len(word1) and i2 < len(word2): \n if word1[i1:] > word2[i2:]: \n ans.append(word1[i1])\n i1 += 1\n else: \n ans.append(word2[i2])\n i2 += 1\n return "".join(ans) + word1[i1:] + word2[i2:]\n```\n\n**Analysis**\nTime complexity `O(N^2)`\nSpace complexity `O(N)`
91,656
Closest Subsequence Sum
closest-subsequence-sum
You are given an integer array nums and an integer goal. You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal). Return the minimum possible value of abs(sum - goal). Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
Array,Two Pointers,Dynamic Programming,Bit Manipulation,Bitmask
Hard
The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary search to get the nearest possible value to goal - x in the first part.
2,637
31
**Algo**\nDivide `nums` in half. Collect subsequence subs of the two halves respectively and search for a combined sum that is closest to given `target`. \n\n**Implementation**\n```\nclass Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n \n def fn(nums):\n ans = {0}\n for x in nums: \n ans |= {x + y for y in ans}\n return ans \n \n nums0 = sorted(fn(nums[:len(nums)//2]))\n \n ans = inf\n for x in fn(nums[len(nums)//2:]): \n k = bisect_left(nums0, goal - x)\n if k < len(nums0): ans = min(ans, nums0[k] + x - goal)\n if 0 < k: ans = min(ans, goal - x - nums0[k-1])\n return ans \n```\n\n**Analysis**\nTime complexity `O(2^(N/2))`\nSpace complexity `O(2^(N/2))`
91,695
Minimum Changes To Make Alternating Binary String
minimum-changes-to-make-alternating-binary-string
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the minimum number of operations needed to make s alternating.
String
Easy
Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.
962
15
From an observation we can find that ```s = "0100"``` can have only two solutions which are ``` 0101``` and ```1010```.\n\nIf we find the number of operations to change ```s``` to first solution ```0101```, we can find the number of operations required to change ```s``` to second solution ```1010``` with simple maths.\n```0100 -> 0101``` takes ```1``` operation\n```0100 -> 1010``` takes ```3``` operations, which is nothing but ```len(s) - number of operations for previous solution``` that is ```4 - 1 = 3```\n\nAnother example,\n```s = "100101"``` can have only two solutions which are ```101010``` and ```010101```\n```100101 -> 101010``` takes ```4``` operations\n```100101 -> 010101``` takes ```2``` operations, which is nothing but ```len(s) - number of operations for previous solution``` that is ```6 - 4 = 2```\n\nTime: ```O(n)```\nSpace: ```O(1)```\n```\ndef minOperations(self, s: str) -> int:\n\tstartsWith0 = 0\n\tflag = 0 # here we are first calculating the soln starting with 0, so flag = 0\n\n\tfor c in s:\n\t\tif int(c) != flag:\n\t\t\tstartsWith0 += 1\n\n\t\tflag = not flag # alternates b/w 0 & 1\n\n\tstartsWith1 = len(s) - startsWith0\n\n\treturn min(startsWith0, startsWith1)\n```\n\n![image]()\n\n
91,796
Minimum Changes To Make Alternating Binary String
minimum-changes-to-make-alternating-binary-string
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the minimum number of operations needed to make s alternating.
String
Easy
Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.
1,424
14
\'\'\'\nSimple idea:\nIn this problem there are 2 possible valid binary strings. Let\'s take an example:\ns = "010011" the answer is : either "010101" or "101010", but you wanna pick the one that is easier to transform.\nIn order to that you have to iterate through the string and count 2 times how many changes you have to make: one for the first form and one for the latter.\nThen pick the smallest that is the easiest to get to a valid form.\nIf you like it, please upvote! ^^\n```\nclass Solution:\n def minOperations(self, s: str) -> int:\n count = 0\n count1 = 0\n for i in range(len(s)):\n if i % 2 == 0:\n if s[i] == \'1\':\n count += 1\n if s[i] == \'0\':\n count1 += 1\n else:\n if s[i] == \'0\':\n count += 1\n if s[i] == \'1\':\n count1 += 1\n return min(count, count1)\n```\n\'\'\'
91,801
Minimum Changes To Make Alternating Binary String
minimum-changes-to-make-alternating-binary-string
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not. Return the minimum number of operations needed to make s alternating.
String
Easy
Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.
556
5
```\n# The final string should be either 010101.. or 101010... (depending on the length of string s)\n# Check the number of differences between given string s and the two final strings. \n# Return the one with minimum differences \n\n\tdef minOperations(self, s: str) -> int:\n\t\tstarting_with_01 = \'01\'\n\t\tstarting_with_10 = \'10\'\n\t\tdiff_with_01 = 0\n\t\tdiff_with_10 = 0\n\t\tfor i in range(len(s)):\n\t\t\tif starting_with_01[i%2] != s[i]:\n\t\t\t\tdiff_with_01 += 1\n\t\t\tif starting_with_10[i%2] != s[i]:\n\t\t\t\tdiff_with_10 += 1\n\t\treturn min(diff_with_01, diff_with_10)\n\n```
91,818
Count Number of Homogenous Substrings
count-number-of-homogenous-substrings
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string.
Math,String
Medium
A string of only 'a's of length k contains k choose 2 homogenous substrings. Split the string into substrings where each substring contains only one letter, and apply the formula on each substring's length.
8,841
36
![Screenshot 2023-11-09 060033.png]()\n\n# YouTube Video Explanation:\n\n[]()\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: \n\n*Current Subscribers: 198*\n*Subscribe Goal: 250 Subscribers*\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about counting the number of homogenous substrings within the given string `s`. A substring is homogenous if all its characters are the same. To count these homogenous substrings efficiently, we can iterate through the string, and when we encounter a character different from the previous one, we calculate and add the number of homogenous substrings up to that point. Finally, we return the result modulo 10^9 + 7 to handle large numbers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a variable `res` to store the result.\n2. Convert the input string `s` into a character array for easy access.\n3. Initialize a variable `start` to 0, which marks the start of a potential homogenous substring.\n4. Iterate through the character array.\n5. When a different character is encountered (`c[i] != c[start]`), calculate the number of homogenous substrings and add it to `res`. We do this by subtracting the start index from the current index (`i - start`) and adding the count to `res`. Then, update the `start` to the current index.\n6. Continue this process until you reach the end of the string.\n7. Calculate and add the number of homogenous substrings for the last homogenous substring.\n8. Return the result `res` modulo 10^9 + 7.\n\n# Complexity\n- Time Complexity: O(n), where n is the length of the input string `s`. We iterate through the string once.\n- Space Complexity: O(1), as we use a constant amount of extra space for variables.\n- The result is returned modulo 10^9 + 7 to handle large numbers.\n\nThis code efficiently counts homogenous substrings within the string `s`.\n\n# Code\n### Java\n```\nclass Solution {\n public int countHomogenous(String s) {\n long res = 0;\n char[] c = s.toCharArray();\n int start =0;\n for(int i=0;i<c.length;i++)\n {\n if(c[i]!=c[start])\n {\n int appear = i-start;\n while(appear>0)\n {\n res+=appear;\n appear-=1;\n }\n start=i;\n }\n }\n\n int appear = c.length-start;\n while(appear>0)\n {\n res+=appear;\n appear-=1;\n }\n\n return (int)(res%(Math.pow(10,9)+7));\n }\n}\n```\n### C++\n```\nclass Solution {\npublic:\n int countHomogenous(string s) {\n long long res = 0;\n int start = 0;\n \n for (int i = 0; i < s.size(); i++) {\n if (s[i] != s[start]) {\n int appear = i - start;\n while (appear > 0) {\n res += appear;\n appear--;\n }\n start = i;\n }\n }\n\n int appear = s.size() - start;\n while (appear > 0) {\n res += appear;\n appear--;\n }\n\n return static_cast<int>(res % (1000000007)); // Modulo 10^9+7\n }\n};\n\n```\n### Python\n```\nclass Solution(object):\n def countHomogenous(self, s):\n res = 0\n start = 0\n \n for i in range(len(s)):\n if s[i] != s[start]:\n appear = i - start\n while appear > 0:\n res += appear\n appear -= 1\n start = i\n \n appear = len(s) - start\n while appear > 0:\n res += appear\n appear -= 1\n \n return int(res % (10**9 + 7))\n```\n### JavaScript\n```\nvar countHomogenous = function(s) {\n let res = 0;\n let start = 0;\n \n for (let i = 0; i < s.length; i++) {\n if (s[i] !== s[start]) {\n let appear = i - start;\n while (appear > 0) {\n res += appear;\n appear -= 1;\n }\n start = i;\n }\n }\n\n let appear = s.length - start;\n while (appear > 0) {\n res += appear;\n appear -= 1;\n }\n\n return res % (Math.pow(10, 9) + 7);\n};\n```\n---\n![upvote1.jpeg]()\n
91,840
Count Number of Homogenous Substrings
count-number-of-homogenous-substrings
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string.
Math,String
Medium
A string of only 'a's of length k contains k choose 2 homogenous substrings. Split the string into substrings where each substring contains only one letter, and apply the formula on each substring's length.
9,731
118
# Intuition\nUse two pointers to get length of substring\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:04` Let\'s find a solution pattern\n`1:38` A key point to solve Count Number of Homogenous Substrings\n`2:20` Demonstrate how it works with all the same characters\n`4:55` What if we find different characters\n`7:13` Coding\n`8:21` Time Complexity and Space Complexity\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: 2,984\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n\u3010Updated\u3011\n\nA few minutes ago, I opened youtube studio and my channel reached 3,000 subscribers. Thank you so much for your support!!\n\n![Screen Shot 2023-11-09 at 23.06.18.png]()\n\n\n---\n\n# Approach\n\n## How we think about a solution\n\nSeems like we have a lot of patterns, so when I feel that, I usually think about output with small input.\n\n```\nInput = "a"\n```\n```\nPattern\n"a": 1\n\nOutput = 1\n```\n\n```\nInput = "aa"\n```\n```\nPattern\n"a": 2\n"aa": 1\n\nOutput = 3\n```\n\n```\nInput = "aaa"\n```\n```\nPattern\n"a": 3\n"aa": 2\n"aaa": 1\n\nOutput = 6\n```\n```\nInput = "aaaa"\n```\n```\nPattern\n"a": 4\n"aa": 3\n"aaa": 2\n"aaaa": 1\n\nOutput = 10\n```\n```\nInput = "aaaaa"\n```\n```\nPattern\n"a": 5\n"aa": 4\n"aaa": 3\n"aaaa": 2\n"aaaaa": 1\n\nOutput = 15\n```\n\nSeems like we have a solution pattern.\n\n---\n\n\u2B50\uFE0F Points\n\nEvery time we find the same character, we can accumulate `current length of substring` to `ouput`. We will add the numbers from bottom to top (1 + 2 + 3 + 4 + 5) because when we iterate through the input string, length of substring start from minimum to maximum. We use two pointers for length of subtring. Let\'s say `left` and `right`\n\n```\n"a": 5\n"aa": 4\n"aaa": 3\n"aaaa": 2\n"aaaaa": 1 \n\n5 + 4 + 3 + 2 + 1 = 1 + 2 + 3 + 4 + 5\n\n5 + 4 + 3 + 2 + 1 is coming from pyramid above\n1 + 2 + 3 + 4 + 5 is actual calculation in solution code\n```\nThey are the same output.\n\n- How can you calculate length of substring?\n\nSimply\n```\nright - left + 1\n```\nWhy + 1?\n\nThat\'s because `left` and `right` are index number, when both indices are `0`, they are pointing `a`.\n\n```\n0 - 0 = 0?\n```\nThat\'s wrong. We find single `a`. That\'s why we need to add `+1`.\n\n##### How it works\n\n```\nInput: "aaaaa"\n```\n\n```\nleft = 0\nright = 0\n\nFind "a"\noutput: 1\n\n```\n```\nleft = 0\nright = 1\n\noutput: 3 (1 + 2)\n\n1 is current output\n2 is length of substring (= "aa")\n```\n```\nleft = 0\nright = 2\n\noutput: 6 (3 + 3)\n\n(first)3 is current output\n(second)3 is length of substring (= "aaa")\n```\n```\nleft = 0\nright = 3\n\noutput: 10 (6 + 4)\n\n6 is current output\n4 is length of substring (= "aaaa")\n```\n```\nleft = 0\nright = 4\n\noutput: 15 (10 + 5)\n\n10 is current output\n5 is length of substring (= "aaaaa")\n```\n\n```\noutput: 15\n```\n\n### What if we find a different character?\n\nWhen we find the different character, we know that the differnt character is the first new character.\n\nIn that case, \n\n---\n\n\u2B50\uFE0F Points\n\n- We cannot accumulate previous length of subtring anymore, so update `left` with `right`, then we can make a new start from current place\n\n- Add `+1` to current output before we go to the next iteration, because the character is the first character, we know that when we have only one character, output should be `1`. \n\n---\n\n##### How it works\n\n```\nInput: "aabbb"\n```\n```\nleft = 0\nright = 0\n\noutput = 1\n```\n```\nleft = 0\nright = 1\n\noutput = 3 (1 + 2)\n1 is current output\n2 is length of substring(= "aa")\n```\nThen we find a different character. `a` vs `b`\n```\nleft = 0\nright = 2\n\noutput = 4 (3 + 1)\n3 is current output\n1 is length of substring(= "b")\n```\nWe will make a new start from index `2`, so update `left` with `right`.\n\n```\nleft = 2\nright = 3\n\noutput = 6 (4 + 2)\n4 is current output\n2 is length of substring(= "bb")\n```\n\n```\nleft = 2\nright = 4\n\noutput = 9 (6 + 3)\n6 is current output\n3 is length of substring(= "bbb")\n```\n\n```\noutput: 9\n```\n\nEasy! \uD83D\uDE04\nLet\'s see a real algorithm!\n\n\n---\n\n### Algorithm Overview:\n\nUse two pointers to get length of substring, then we will accumulate the length if we find the same characters. If not, we can make a new start.\n\nLet\'s break it down into more detailed steps:\n\n### Detailed Explanation:\n\n1. Initialize `left` and `res` to 0.\n\n2. Start a loop that iterates through each character in the input string `s`.\n\n3. Check if the character at index `left` is equal to the character at index `right`.\n\n4. If the characters are the same:\n - Increment the result `res` by the length of the current substring, which is `right - left + 1`. This accounts for substrings where all characters are the same.\n\n5. If the characters are different:\n - Increment the result `res` by 1 to account for the single character substring.\n - Update the `left` index to the `right` index to start a new substring.\n\n6. Repeat steps 3 to 5 for all characters in the input string.\n\n7. After the loop is completed, return the result `res` modulo `(10^9 + 7)`.\n\nThis algorithm essentially counts the length of consecutive substrings with the same characters within the input string and returns the result modulo `(10^9 + 7)`.\n\n---\n\n# Complexity\n- Time complexity: $$O(n)$$\nWe iterate through all characters one by one.\n\n- Space complexity: $$O(1)$$\nWe don\'t use extra data structure.\n\n```python []\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n\n left = 0\n res = 0\n\n for right in range(len(s)):\n if s[left] == s[right]:\n res += right - left + 1\n else:\n res += 1\n left = right\n \n return res % (10**9 + 7)\n```\n```javascript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar countHomogenous = function(s) {\n let left = 0;\n let res = 0;\n\n for (let right = 0; right < s.length; right++) {\n if (s[left] === s[right]) {\n res += right - left + 1;\n } else {\n res += 1;\n left = right;\n }\n }\n\n return res % (Math.pow(10, 9) + 7); \n};\n```\n```java []\nclass Solution {\n public int countHomogenous(String s) {\n int left = 0;\n long res = 0;\n \n for (int right = 0; right < s.length(); right++) {\n if (s.charAt(left) == s.charAt(right)) {\n res += right - left + 1;\n } else {\n res += 1;\n left = right;\n }\n }\n\n return (int) (res % (1000000007)); \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int countHomogenous(string s) {\n int left = 0;\n long long res = 0;\n \n for (int right = 0; right < s.length(); right++) {\n if (s[left] == s[right]) {\n res += right - left + 1;\n } else {\n res += 1;\n left = right;\n }\n }\n\n return (int) (res % (1000000007)); \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\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:04` A key point to solve this question\n`1:09` How do you know adjacent number of each number?\n`2:33` Demonstrate how it works\n`6:07` Coding\n`9:07` 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:04` How we can calculate x and y distances\n`0:55` We need to consider 2 cases and explain what if start and finish cell are the same position\n`2:20` Explain case 2, what if start and finish cell are different positions\n`4:53` Coding\n`6:18` Time Complexity and Space Complexity
91,845
Count Number of Homogenous Substrings
count-number-of-homogenous-substrings
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string.
Math,String
Medium
A string of only 'a's of length k contains k choose 2 homogenous substrings. Split the string into substrings where each substring contains only one letter, and apply the formula on each substring's length.
1,434
14
```python3 []\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n res, l = 0, 0\n\n for r, c in enumerate(s):\n if c == s[l]:\n res += r - l + 1\n else:\n l = r\n res += 1\n\n return res % (pow(10, 9) + 7)\n```\n###### For those who are confused why are we adding `r - l + 1`, it adds all the subarrays that ends at r (right) starting at l (left) or later. \n###### Example for list with numbers, not string like in the current problem, but the main idea is the same: `s = [1,1,1,1,1,0,0,1], res = 0`\n- `l = 0, r = 0 => [[1],1,1,1,1,0,0,1] => res = 0 + 1 = 1`\n- `l = 0, r = 1 => [[1,1],1,1,1,0,0,1] => res = 1 + 2 = 3`\n- `l = 0, r = 2 => [[1,1,1],1,1,0,0,1] => res = 3 + 3 = 6`\n- `l = 0, r = 3 => [[1,1,1,1],1,0,0,1] => res = 6 + 4 = 10`\n- `l = 0, r = 4 => [[1,1,1,1,1],0,0,1] => res = 10 + 5 = 15`\n- `l = 5, r = 5 => [1,1,1,1,1,[0],0,1] => res = 15 + 1 = 16`\n- `l = 5, r = 6 => [1,1,1,1,1,[0,0],1] => res = 16 + 2 = 18`\n- `l = 7, r = 7 => [1,1,1,1,1,0,0,[1]] => res = 18 + 1 = 19`\n\n###### If you\'re given an array of length\xA0n, it will produce\xA0`(n*(n+1))//2`\xA0total contiguous subarrays (same as doing the sum step by step above).\n```python3 []\n# [k for k, g in groupby(\'AAAABBBCCDAABBB\')] --> A B C D A B\n# [list(g) for k, g in groupby(\'AAAABBBCCD\')] --> AAAA BBB CC D\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n res = 0\n for _, g in groupby(s):\n n = len(list(g))\n res += n * (n + 1) // 2\n \n return res % (pow(10, 9) + 7)\n```\n\n###### Similar Sliding Window problems:\n- [713. Subarray Product Less Than K]()\n- [2302. Count Subarrays With Score Less Than K]()\n- [1248. Count Number of Nice Subarrays]()\n\n![Screenshot 2023-11-09 at 04.35.53.png]()\n\n
91,860
Count Number of Homogenous Substrings
count-number-of-homogenous-substrings
Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7. A string is homogenous if all the characters of the string are the same. A substring is a contiguous sequence of characters within a string.
Math,String
Medium
A string of only 'a's of length k contains k choose 2 homogenous substrings. Split the string into substrings where each substring contains only one letter, and apply the formula on each substring's length.
4,127
11
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne pass to find out all longest homogenous substrings in `s` , and store the lengths in a container `len_homo`.\n\nC code is rare & implemented & runs in 0 ms & beats 100%\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nA longest homogenous substring in `s` is the substring with all the same alphabets which is not extendible.\n\nLet `h` be a longest homogenous substring in `s` with length `sz`.\nThere are `sz(sz+1)/2` homogeous substrings in `h`.\nsz homogenous substrings of length 1\nsz-1 homogenous substrings of length 2\nsz-2 homogenous substrings of length 3\n....\n1 homogenous substrings of length sz\n\nSumming them up\n$$\nans=\\sum_{h:s, len(h)=sz}\\frac{sz(sz+1)}{2}\\pmod{ 10^9+7}\n$$\n2nd approach does not use the container `len_homo`, and is fast in 12 ms , SC : O(1).\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n+m)$$ where n=len(s) m=len(len_homo)\n$O(n)$ for optimized code\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(m)\\to O(1)$$\n# Code\n```\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n const long long mod=1e9+7;\n int countHomogenous(string s) {\n vector<int> len_homo;\n char prev=\'X\';\n int count=0;\n\n #pragma unroll\n for(char c: s){\n if (c!=prev){\n len_homo.push_back(count);\n count=1;\n }\n else count++;\n prev=c;// update prev\n }\n len_homo.push_back(count);// last one\n\n long long ans=0;\n\n #pragma unroll\n for(int sz: len_homo)\n ans=(ans+(long long)sz*(sz+1)/2)%mod;\n return ans;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# optimized Code runs in 12 ms\n```\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n const long long mod=1e9+7;\n int countHomogenous(string s) {\n char prev=\'X\';\n int count=0;\n long long ans=0;\n for(char c: s){\n if (c!=prev){\n ans=(ans+(long long)count*(count+1)/2%mod);\n count=1;\n }\n else count++;\n prev=c;// update prev\n }\n ans=(ans+(long long)count*(count+1)/2%mod);// last one\n return ans;\n }\n};\n```\n# Python code \n```\nclass Solution:\n def countHomogenous(self, s: str) -> int:\n mod=10**9+7\n prev=\'X\'\n count=0\n ans=0\n for c in s:\n if c!=prev:\n ans=(ans+count*(count+1)//2)% mod\n count=1\n else:\n count+=1\n prev=c\n ans=(ans+count*(count+1)//2)% mod\n return ans\n \n```\n![100.png]()\n\n# C code runs in 0 ms beats 100%\n```\n#pragma GCC optimize("O3")\nconst long long mod=1e9+7;\n\nint countHomogenous(char * s){\n int n=strlen(s);\n char prev=\'X\';\n int count=0;\n long long ans=0;\n for(register i=0; i<n; i++){\n if (s[i]!=prev){\n ans=(ans+(long long)count*(count+1)/2%mod);\n count=1;\n }\n else count++;\n prev=s[i];\n }\n ans=(ans+(long long)count*(count+1)/2%mod);// last one\n return ans;\n}\n```\n
91,875
Minimum Degree of a Connected Trio in a Graph
minimum-degree-of-a-connected-trio-in-a-graph
You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. A connected trio is a set of three nodes where there is an edge between every pair of them. The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not. Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.
Graph
Hard
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
617
7
Algo\nCheck all trios and find minimum degrees. \n\nImplementation\n```\nclass Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n graph = [[False]*n for _ in range(n)]\n degree = [0]*n\n \n for u, v in edges: \n graph[u-1][v-1] = graph[v-1][u-1] = True\n degree[u-1] += 1\n degree[v-1] += 1\n \n ans = inf\n for i in range(n): \n for j in range(i+1, n):\n if graph[i][j]: \n for k in range(j+1, n):\n if graph[j][k] and graph[k][i]: \n ans = min(ans, degree[i] + degree[j] + degree[k] - 6)\n return ans if ans < inf else -1\n```\n\nAnalysis\nTime complexity `O(V^3)`\nSpace complexity `O(V^2)`
91,960
Find Nearest Point That Has the Same X or Y Coordinate
find-nearest-point-that-has-the-same-x-or-y-coordinate
You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1. The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
Array
Easy
Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location.
1,121
8
Upvote if it helped. Thanks\n\n```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n min_dis= 10000 \n ind = -1\n for i in range (len (points)):\n if points[i][0] == x or points [i][1] == y:\n mandist = abs(points[i][0] -x) + abs(points[i][1] - y)\n if mandist < min_dis :\n min_dis = mandist\n ind = i\n return ind\n```
92,011
Find Nearest Point That Has the Same X or Y Coordinate
find-nearest-point-that-has-the-same-x-or-y-coordinate
You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1. The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
Array
Easy
Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location.
764
6
`Find Nearest Point That Has the Same X or Y Coordinate`\n1) Loop through the vector of points.\n2) If x or y coordinate matches, Calculate and record manhatten distance for every point.\n3) Compare every time if manhattan distance is lesser than the previous recorded least distance.\n4) Return the least distance point\'s index no. \n\n# **Pretty ez question ig ! Really good for beginners ! \uD83D\uDD25**\n\n```\nTC: O(n)\nSC: O(1)\n```\n\n```\nclass Solution {\npublic:\n int nearestValidPoint(int x, int y, vector<vector<int>>& points) {\n int manhattan,d=INT_MAX,ans=-1;\n for(int i=0;i<points.size();i++){\n if(points[i][0]==x || points[i][1]==y){\n manhattan=abs(x - points[i][0]) + abs(y - points[i][1]);\n if(manhattan<d){\n d=manhattan;\n ans=i;\n }\n }\n }\n return ans;\n }\n};\n```\n# ***Please upvote if it helps \uD83D\uDE4F.***
92,014
Find Nearest Point That Has the Same X or Y Coordinate
find-nearest-point-that-has-the-same-x-or-y-coordinate
You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1. The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
Array
Easy
Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location.
4,511
29
```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n minDist = math.inf\n ans = -1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n if manDist<minDist:\n ans = i\n minDist = manDist\n return ans\n \n```
92,019
Find Nearest Point That Has the Same X or Y Coordinate
find-nearest-point-that-has-the-same-x-or-y-coordinate
You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location. Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1. The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).
Array
Easy
Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location.
1,120
5
**Solution**:\n```\nclass Solution:\n def nearestValidPoint(self, x1, y1, points):\n minIdx, minDist = -1, inf\n for i,point in enumerate(points):\n x2, y2 = point\n if x1 == x2 or y1 == y2:\n dist = abs(x1-x2) + abs(y1-y2)\n if dist < minDist:\n minIdx = i\n minDist = min(dist,minDist)\n return minIdx\n```
92,026
Sum of Beauty of All Substrings
sum-of-beauty-of-all-substrings
The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. Given a string s, return the sum of beauty of all of its substrings.
Hash Table,String,Counting
Medium
Maintain a prefix sum for the frequencies of characters. You can iterate over all substring then iterate over the alphabet and find which character appears most and which appears least using the prefix sum array
4,996
55
\n```\nclass Solution:\n def beautySum(self, s: str) -> int:\n ans = 0 \n for i in range(len(s)):\n freq = [0]*26\n for j in range(i, len(s)):\n freq[ord(s[j])-97] += 1\n ans += max(freq) - min(x for x in freq if x)\n return ans \n```
92,097
Sum of Beauty of All Substrings
sum-of-beauty-of-all-substrings
The beauty of a string is the difference in frequencies between the most frequent and least frequent characters. Given a string s, return the sum of beauty of all of its substrings.
Hash Table,String,Counting
Medium
Maintain a prefix sum for the frequencies of characters. You can iterate over all substring then iterate over the alphabet and find which character appears most and which appears least using the prefix sum array
912
5
```\nclass Solution:\n def beautySum(self, s: str) -> int:\n beauty=0\n for i in range(len(s)-2):\n Freq={}\n for j in range(i,len(s)):\n Freq.setdefault(s[j],0)\n Freq[s[j]]+=1\n beauty+=max(Freq.values())-min(Freq.values())\n return beauty
92,123
Count Pairs Of Nodes
count-pairs-of-nodes
You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries. Let incident(a, b) be defined as the number of edges that are connected to either node a or b. The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions: Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query. Note that there can be multiple edges between the same two nodes.
Two Pointers,Binary Search,Graph
Hard
We want to count pairs (x,y) such that degree[x] + degree[y] - occurrences(x,y) > k Think about iterating on x, and counting the number of valid y to pair with x. You can consider at first that the (- occurrences(x,y)) isn't there, or it is 0 at first for all y. Count the valid y this way. Then you can iterate on the neighbors of x, let that neighbor be y, and update occurrences(x,y). When you update occurrences(x,y), the left-hand side decreases. Once it reaches k, then y is not valid for x anymore, so you should decrease the answer by 1.
675
19
\n```\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n degree = [0]*n\n freq = defaultdict(int)\n for u, v in edges: \n degree[u-1] += 1\n degree[v-1] += 1\n freq[min(u-1, v-1), max(u-1, v-1)] += 1\n \n vals = sorted(degree)\n \n ans = []\n for query in queries: \n cnt = 0 \n lo, hi = 0, n-1\n while lo < hi: \n if query < vals[lo] + vals[hi]: \n cnt += hi - lo # (lo, hi), (lo+1, hi), ..., (hi-1, hi) all valid\n hi -= 1\n else: lo += 1\n for u, v in freq: \n if degree[u] + degree[v] - freq[u, v] <= query < degree[u] + degree[v]: cnt -= 1\n ans.append(cnt)\n return ans\n```
92,145
Find Total Time Spent by Each Employee
find-total-time-spent-by-each-employee
Table: Employees Write an SQL query to calculate the total time in minutes spent by each employee on each day at the office. Note that within one day, an employee can enter and leave more than once. The time spent in the office for a single entry is out_time - in_time. Return the result table in any order. The query result format is in the following example.
Database
Easy
null
621
14
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef total_time(employees: pd.DataFrame) -> pd.DataFrame:\n return employees.assign(\n total_time=employees[\'out_time\'] - employees[\'in_time\'],\n day=employees[\'event_day\'].dt.strftime(\'%Y-%m-%d\'),\n ).groupby(\n [\'emp_id\', \'day\'], as_index=False\n )[\'total_time\'].sum()[\n [\'day\', \'emp_id\', \'total_time\']\n ]\n```\n```SQL []\nSELECT event_day AS day,\n emp_id,\n sum(out_time - in_time) AS total_time\n FROM Employees\n GROUP BY emp_id, event_day;\n```\n\n# Important!\n###### If you like the solution or find it useful, feel free to **upvote** for it, it will support me in creating high quality solutions)\n\n# 30 Days of Pandas solutions\n\n### Data Filtering \u2705\n- [Big Countries]()\n- [Recyclable and Low Fat Products]()\n- [Customers Who Never Order]()\n- [Article Views I]()\n\n\n### String Methods \u2705\n- [Invalid Tweets]()\n- [Calculate Special Bonus]()\n- [Fix Names in a Table]()\n- [Find Users With Valid E-Mails]()\n- [Patients With a Condition]()\n\n\n### Data Manipulation \u2705\n- [Nth Highest Salary]()\n- [Second Highest Salary]()\n- [Department Highest Salary]()\n- [Rank Scores]()\n- [Delete Duplicate Emails]()\n- [Rearrange Products Table]()\n\n\n### Statistics \u2705\n- [The Number of Rich Customers]()\n- [Immediate Food Delivery I]()\n- [Count Salary Categories]()\n\n\n### Data Aggregation \u2705\n- [Find Total Time Spent by Each Employee]()\n- [Game Play Analysis I]()\n- [Number of Unique Subjects Taught by Each Teacher]()\n- [Classes More Than 5 Students]()\n- [Customer Placing the Largest Number of Orders]()\n- [Group Sold Products By The Date]()\n- [Daily Leads and Partners]()\n\n\n### Data Aggregation \u2705\n- [Actors and Directors Who Cooperated At Least Three Times]()\n- [Replace Employee ID With The Unique Identifier]()\n- [Students and Examinations]()\n- [Managers with at Least 5 Direct Reports]()\n- [Sales Person]()\n\n
92,203
Merge Strings Alternately
merge-strings-alternately
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string.
Two Pointers,String
Easy
Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.
83,761
815
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n>The problem asks to merge two strings alternately. Therefore, we can traverse both strings at the same time and pick each character alternately from both strings.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n>1. Initialize an empty string to store the merged result.\n>2. Traverse both input strings together, picking each character alternately from both strings and appending it to the merged result string.\n>3. Continue the traversal until the end of the longer string is reached.\n>4. Return the merged result string.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n>Since we traverse both strings once and pick each character alternately, the time complexity of this approach is O(n), where n is the length of the longer string.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n>We use a StringBuilder to store the merged string, so the space complexity of this approach is O(n), where n is the length of the longer string.\n\n![image.png]()\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n```\n\n# Code\n```java []\nclass Solution {\n public String mergeAlternately(String word1, String word2) {\n StringBuilder result = new StringBuilder();\n int i = 0;\n while (i < word1.length() || i < word2.length()) {\n if (i < word1.length()) {\n result.append(word1.charAt(i));\n }\n if (i < word2.length()) {\n result.append(word2.charAt(i));\n }\n i++;\n }\n return result.toString();\n }\n}\n```\n```python []\nclass Solution(object):\n def mergeAlternately(self, word1, word2):\n """\n :type word1: str\n :type word2: str\n :rtype: str\n """\n result = []\n i = 0\n while i < len(word1) or i < len(word2):\n if i < len(word1):\n result.append(word1[i])\n if i < len(word2):\n result.append(word2[i])\n i += 1\n return \'\'.join(result)\n```\n```C++ []\nclass Solution {\npublic:\n string mergeAlternately(string word1, string word2) {\n string result = "";\n int i = 0;\n while (i < word1.length() || i < word2.length()) {\n if (i < word1.length()) {\n result += word1[i];\n }\n if (i < word2.length()) {\n result += word2[i];\n }\n i++;\n }\n return result;\n }\n};\n```\n\n```javascript []\n/**\n * @param {string} word1\n * @param {string} word2\n * @return {string}\n */\nvar mergeAlternately = function(word1, word2) {\n let result = \'\';\n for (let i = 0; i < Math.max(word1.length, word2.length); i++) {\n if (i < word1.length) result += word1[i];\n if (i < word2.length) result += word2[i];\n }\n return result;\n};\n```\n\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n```
92,240
Merge Strings Alternately
merge-strings-alternately
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string.
Two Pointers,String
Easy
Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.
997
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> The goal is to merge two strings, word1 and word2, in an alternating fashion, starting with word1. If one of the strings is longer than the other, append the remaining characters to the end of the merged string. The key intuition is to iterate through both strings simultaneously and concatenate characters in an alternating order.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Determine Minimum Length:** Find the minimum length of the two input strings, minLength = min(len(word1), len(word2)). This is important for ensuring that the loop doesn\'t go out of bounds.\n2. **Alternate Merge:** Use a loop to iterate from 0 to minLength - 1 and concatenate characters from both strings alternately. Append the results to a list.\n3. **Append Remaining Characters:** Append any remaining characters from both strings (if one is longer than the other) to the end of the result list.\n4. **Join Result:** Use \'\'.join(result) to convert the list of characters into a single string.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```JAVA []\nclass Solution {\n public String mergeAlternately(String word1, String word2) {\n\n StringBuilder result = new StringBuilder(word1.length() + word2.length());\n\n int minLength = Math.min(word1.length(), word2.length());\n\n for (int i = 0; i < minLength; i++) {\n result.append(word1.charAt(i)).append(word2.charAt(i));\n }\n\n result.append(word1.substring(minLength)).append(word2.substring(minLength));\n\n return result.toString();\n }\n}\n```\n```C++ []\nusing namespace std;\nclass Solution {\npublic:\n string mergeAlternately(string word1, string word2) {\n string result;\n result.reserve(word1.length() + word2.length());\n\n int minLength = min(word1.length(), word2.length());\n\n for (int i = 0; i < minLength; i++) {\n result.push_back(word1[i]);\n result.push_back(word2[i]);\n }\n\n result.append(word1.substr(minLength)).append(word2.substr(minLength));\n\n return result;\n }\n};\n```\n```Python3 []\n\nclass Solution:\n def mergeAlternately(self, word1: str, word2: str) -> str:\n result = []\n minLength = min(len(word1), len(word2))\n\n for i in range(minLength):\n result.append(word1[i])\n result.append(word2[i])\n\n result.extend([word1[minLength:], word2[minLength:]])\n\n return \'\'.join(result)\n```\n
92,258
Minimum Number of Operations to Move All Balls to Each Box
minimum-number-of-operations-to-move-all-balls-to-each-box
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. Each answer[i] is calculated considering the initial state of the boxes.
Array,String
Medium
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
9,519
157
Similar to **238. Product of Array Except Self** and **42. Trapping Rain Water**.\nFor each index, the cost to move all boxes to it is sum of the cost ```leftCost``` to move all left boxes to it, and the cost ```rightCost``` to move all right boxes to it.\n- ```leftCost``` for all indexes can be calculted using a single pass from left to right.\n- ```rightCost``` for all indexes can be calculted using a single pass from right to left.\n```\nExample:\nboxes 11010\nleftCount 01223\nleftCost 01358\nrightCount 21100\nrightCost 42100\nans 43458\n```\n\n```\nclass Solution:\n def minOperations(self, boxes: str) -> List[int]:\n ans = [0]*len(boxes)\n leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)\n for i in range(1, n):\n if boxes[i-1] == \'1\': leftCount += 1\n leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left\n ans[i] = leftCost\n for i in range(n-2, -1, -1):\n if boxes[i+1] == \'1\': rightCount += 1\n rightCost += rightCount\n ans[i] += rightCost\n return ans\n```\n\n![image]()
92,300
Minimum Number of Operations to Move All Balls to Each Box
minimum-number-of-operations-to-move-all-balls-to-each-box
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. Each answer[i] is calculated considering the initial state of the boxes.
Array,String
Medium
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
423
5
Logic is to calculate the sum of indices having balls and store it in ans[0]. We also calculate number of balls that are ahead of index 0 as we iterate once.\n\nAs you iterate forward again, reduce the previous sum (at index - 1 in the ans array) by the number of balls ahead and increase the previous sum by number of balls behind. \n\nSince when you move ahead, **the distance from balls behind increases by 1 for every ball behind current index but the distance from balls ahead decreases by 1 for every ball ahead of current index.**\n\nUpvote if you understood the logic :)\n\n```\nclass Solution:\n def minOperations(self, boxes: str) -> List[int]:\n \n ans = [0] * len(boxes)\n sumAhead = ballsAhead = ballsBehind = 0\n \n for i in range(1, len(boxes)):\n if boxes[i] == \'1\':\n sumAhead += i\n ballsAhead += 1\n \n ans[0] = sumAhead\n \n if boxes[0] == \'1\':\n ballsBehind += 1\n \n for i in range(1, len(ans)):\n ans[i] = ans[i - 1] + ballsBehind - ballsAhead\n \n if boxes[i] == \'1\':\n ballsBehind += 1\n ballsAhead -= 1\n \n return ans \n```\n
92,323
Minimum Number of Operations to Move All Balls to Each Box
minimum-number-of-operations-to-move-all-balls-to-each-box
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. Each answer[i] is calculated considering the initial state of the boxes.
Array,String
Medium
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
706
7
## IDEA :\nHere, we can create prefix and postfix array of size n\\*2 to store the number of ones before (or after) the index and also information of the number of costs required to collect all the ones at previous index.\n**For Example :** \n\'\'\'\n\n\tstring given = " 0 0 1 0 1 1 "\n\tpostfix array = [[3,11], [3,8], [2,5], [2,3], [1,1], [0,0]] # (starting the array from right for computation).\n\tprefix array = [[0,0], [0,0], [0,0], [1,1], [1,2], [2,4]] # (starting the array from left for computation).\n\t\n\tTake prefix array for explaination:\n\t[0,0] -> 0 number of \'1\' is present left to that position and 0 number of cost required to collect all 1\'s left to it.\n\t[0,0] -> 0 number of \'1\' is present left to that position and 0 number of cost required to collect all 1\'s left to it.\n\t[0,0] -> 0 number of \'1\' is present left to that position and 0 number of cost required to collect all 1\'s left to it.\n\t[1,1] -> 1 number of \'1\' is present left to that position and 1 number of cost required to collect all 1\'s left to it.\n\t[1,2] -> 1 number of \'1\' is present left to that position and 2 number of cost required to collect all 1\'s left to it.\n\t[2,4] -> 2 number of \'1\' is present left to that position and 4 number of cost required to collect all 1\'s left to it.\n\t\n\tFormula used to calculate:\n\tpre[i][0] = boxes[i-1] + pre[i-1][0]\n pre[i][1] = boxes[i-1] + pre[i-1][0] + pre[i-1][1]\n\n### CODE :\n\'\'\'\n\n\tclass Solution:\n def minOperations(self, boxes: str) -> List[int]:\n \n n = len(boxes)\n boxes = [int(i) for i in boxes]\n pre = [[0,0] for i in range(n)]\n post= [[0,0] for i in range(n)]\n \n for i in range(1,n):\n pre[i][0] = boxes[i-1] + pre[i-1][0]\n pre[i][1] = boxes[i-1] + pre[i-1][0] + pre[i-1][1]\n \n for i in range(n-2,-1,-1):\n post[i][0] = boxes[i+1] + post[i+1][0]\n post[i][1] = boxes[i+1] + post[i+1][0] + post[i+1][1]\n \n for i in range(n):\n boxes[i] = pre[i][1]+post[i][1]\n \n return boxes\n\n### Thanks & upvote if you like the idea!!\uD83E\uDD1E
92,339
Maximum Score from Performing Multiplication Operations
maximum-score-from-performing-multiplication-operations
You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will: Return the maximum score after performing m operations.
Array,Dynamic Programming
Medium
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence dp is a perfect choice here.
4,354
28
**Please do UPVOTE to motivate me to solve more daily challenges like this !!**\n**Watch this video \uD83E\uDC83 for the better explanation of the code.\n\n\n\n\n**Also you can SUBSCRIBE \uD83E\uDC81 \uD83E\uDC81 \uD83E\uDC81 this channel for the daily leetcode challange solution.**\n \u2B05\u2B05 **Telegram link** to discuss leetcode daily questions and other dsa problems\n\n\n```\n// Here I have index which check the number of multiplier visited, then I have start and end which iterate from the start and end side.\n// we are using dp for optimizing it, you will get TLE without DP, you need to use the cases which are already checked.\n// I am calculating end in 2nd part byend= (nums.size -1)- (index(total num num visited)-start):\n```\n**C++(1st without DP, TLE)**\n```\nclass Solution {\npublic:\n int helper(int index,vector<int>& nums, vector<int>& multi, int start, int end ) \n {\n if(index== multi.size()) return 0;\n return max(multi[index]*nums[start]+ helper(index+1, nums,multi, start+1, end),multi[index]*nums[end]+ helper(index+1, nums, multi, start, end-1) );\n }\nint maximumScore(vector<int>& nums, vector<int>& multipliers) {\n int n= nums.size();\n return helper(0, nums, multipliers, 0,n-1 );\n }\n};\n```\n **C++(2nd with DP, NO TLE) optimized**\n \n \n```\n\n class Solution {\npublic:\n vector<vector<int>> dp;\n int helper(int index,vector<int>& nums, vector<int>& multi, int start) \n { if (dp[index][start] != INT_MIN) return dp[index][start];\n int end= nums.size()-1-(index-start);\n if(index== multi.size()) return 0;\n return dp[index][start]= max(multi[index]*nums[start]+ helper(index+1, nums,multi, start+1),multi[index]*nums[end]+ helper(index+1, nums, multi, start) );\n \n }\n int maximumScore(vector<int>& nums, vector<int>& multipliers) {\n int n= nums.size();\n int m= multipliers.size();\n dp.resize(m + 1, vector<int>(m + 1, INT_MIN));\n return helper(0, nums, multipliers, 0);\n }\n};\n```\n**JAVA**\n```\nclass Solution {\n int n, m;\n Integer[][] dp;\n public int maximumScore(int[] nums, int[] multipliers) {\n n = nums.length;\n m = multipliers.length; \n \n dp = new Integer[1001][1001];\n return helper(0, 0, nums, multipliers);\n }\n \n private int helper(int i, int j, int[] nums, int[] mul) {\n if( i== m )return 0;\n if( dp[i][j] != null ) return dp[i][j]; \n var left= mul[i]*nums[j] + helper(i+1, j+1, nums, mul); \n var right = mul[i]*nums[n-1 -(i-j)] + helper(i+1, j, nums, mul);\n return dp[i][j] = Math.max(left, right);\n }\n}\n```\n**PYTHON**\n \n```\n\nCredit- @Siddharth_singh\n```\n**Please do UPVOTE to motivate me to solve more daily challenges like this !!**
92,341
Maximum Score from Performing Multiplication Operations
maximum-score-from-performing-multiplication-operations
You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will: Return the maximum score after performing m operations.
Array,Dynamic Programming
Medium
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence dp is a perfect choice here.
2,421
19
![image]()\n\n```python\n dp = [0] * (len(mul) + 1)\n for m in range(len(mul) - 1, -1, -1):\n pd = [0] * (m + 1)\n for l in range(m, -1, -1):\n pd[l] = max(dp[l + 1] + mul[m] * nums[l], \n dp[l] + mul[m] * nums[~(m - l)])\n dp = pd\n return dp[0]\n```
92,344
Maximum Score from Performing Multiplication Operations
maximum-score-from-performing-multiplication-operations
You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will: Return the maximum score after performing m operations.
Array,Dynamic Programming
Medium
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence dp is a perfect choice here.
3,596
151
# \uD83D\uDE0B Greedy!\n\n**Let\'s go Greedy!**\n\nWe have to pick integer `x` from **either end** of array `nums`. And, multiply that with `multipliers[i]`. Thus, let\'s pick larger `x` from either end. \n\n**`5` vs `3`, we will pick 5. Is it correct?** \nNo! On checking constraints `-1000 \u2264 nums[i], multipliers[i] \u2264 1000`, both arrays can have negative integers. Thus, if `multipliers[i]` is `-10`, we would prefer adding `-30` instead of `-50`. Thus, we should choose, `x` which when multiplied with `multipliers[i]` gives the larger product.\n\n<details><summary><b>\uD83E\uDD73 Let\'s Dry Run! (Click on Left Triangle to see)</b></summary> \n<pre>\n<b>Input :</b> nums = [1,2,3], multipliers = [3,2,1]\n<b>Taking Decision :</b>\n- From multipliers <b>3</b>, nums is [1, 2, 3], from <b>3</b>x1 vs <b>3</b>x3, choose 3, add <u>9</u>.\n- From multipliers <b>2</b>, nums is [1, 2], from <b>2</b>x1 and <b>2</b>x2, choose 2, add <u>4</u>.\n- From multipliers <b>1</b>, nums is [1], add <u>1</u>.\n\n<br/>\n\nTotal Score is <u>9+4+1</u>=<b>14</b>, which is Correct \u2714\uFE0F</pre></details>\n\n<details><summary><b>\uD83D\uDE0E Another Example! (MUST CLICK on Left Triangle to See)</b></summary><pre>\n<b>Input :</b> nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\n<b>Taking Decision :</b> \n- From multipliers <b>10</b>, nums [-5,-3,-3,-2,7,1], from (<b>-10</b>) (-5) and (<b>-10</b>)(1), choose -5, add <u>50</u>\n- From multipliers <b>-5</b>, nums [-3,-3,-2,7,1], from (<b>-5</b>) (-3) and (<b>-5</b>)(1), choose -3, add <u>15</u>\n- From multipliers <b>3</b>, nums [-3,-2,7,1], from (<b>3</b>) (-3) and (<b>3</b>)(1), choose 1, add <u>3</u>\n- From multipliers <b>4</b>, nums [-3,-2,7], from (<b>4</b>) (-3) and (<b>4</b>)(7), choose 7, add <u>28</u>\n- From multipliers <b>6</b>, nums [-3,-2], from (<b>6</b>) (-3) and (<b>6</b>)(-2), choose -2, add <u>-12</u>\n\n<br/>\n\nTotal Score is <u>50+15+3+28+(-12)</u>=<b>84</b>, which...... \nisn\'t Correct \uD83D\uDE15. 102 is another <u>Optimal Solution</u> \nas given in Problem Example.</pre> </details>\n\nWell, this version of greedy failed! \n\n\n> **How to Prove it?**\n> [\u26A0: Spoiler Alert! Go to these links after reading the complete answer]\n> This was asked on [Computer Science Stack Exchange](), and the [answer]() and [comments]() there suggests that \n>> - "To show that the greedy approach fails, all you have to do is come up with a counterexample. " \n>> - "To prove that the greedy algorithm is not optimal, it suffices to give one counterexample"\n\n> We have given one example, where our version of greedy isn\'t giving <u>Optimal Solution</u>.\n\n*(Another problem where we encounter similar situation is [120. Triangle](). After reading this answer, you can check the problem and one of the [counter example]() for the same)* \n\n> **Still, what\'s the logical intuition behind the failure of greedy?**\n> Greedy is `short-sighted`. In hope of global optimum, we take local optimum. But taking this Local Optimum perhaps <ins>may Restrict Potential Larger Positive Product in Future!</ins> \n> \n> Check this example,\n> <pre> <b>Input :</b> nums = [2,1,1,1,1000,1,1,1,1,42], multipliers = [1,1,1,1,1] </pre>\n> If very myopically, we choose 42 over 2, we would never be able to reach our treasure 1000. Since there are only 5 elements in multipliers, the only way to reach 1000 is by taking the Left route only. But one myopic step, and we lost optimal!\n> \n> Another [Example]() \n> <pre> <b>Input :</b> nums = [5,4], multipliers = [1,2] </pre>\n> Greedy would choose to multiply the 1 by a 5 rather than 4, giving an output of 1\u22C55+2\u22C54=13. But the second multiplier 2 is larger than the first multiplier and so should have been multiplied with the larger number 5 to get the maximum output (which is 1\u22C54+2\u22C55=14).\n\n\n---\n\n\n**What to do now?**\nLook for every possible combination! Try all scenarios \uD83D\uDE29 \n> - Choose one element from either side from `given nums` and then delete the chosen element (multiply and add to the score) to create `remaining nums` \n> - Choose another element from either side from `remaining nums` and then delete the chosen element (multiply and add to the score) to create `another remaining nums` \n> - Choose again ..... \n\n\u2666 Looking for every possible combination, is, in general not very Efficient. \n\u2666 But, this problem has certain properties.\n\n1. **Optimal Substructure:** To get the maximum score for entire `multipliers`, we should ensure we have the maximum score for every subarray from the first index! For `multipliers[0:1]`, for `multipliers[0:2]`, and so on.... <br>\n\n2. **Overlapping Subproblem:** We may need to compute for a particular (`nums`, `multipliers`) pair multiple times. By computing, we mean solving further from this state. **Rough Example:** `nums = [a,b,c,d,e]` and `multipliers = [u,v,w,x,y,z]`\n - **Pattern-1: Two-Left, One Right**\n - From `multipliers`, we have `u`, from nums `a vs e`, choose `a`\n - From `multipliers`, we have `v`, from nums `b vs e`, choose `b` \n - From `multipliers`, we have `w`, from nums `c vs e`, choose `e`\n - From `multipliers`, we have <u>`x`</u>, from nums `c vs d`, choose <u>`c`</u>\n - **Pattern-2: One-Right, Three Left**\n - From `multipliers`, we have `u`, from nums `a vs e`, choose `e`\n - From `multipliers`, we have `v`, from nums `a vs d`, choose `a` \n - From `multipliers`, we have `w`, from nums `b vs d`, choose `b`\n - From `multipliers`, we have <u>`x`</u>, from nums `c vs d`, choose <u>`c`</u> \n<br>Thus, although beginning with different rules, we have reached a situation where we have to proceed with the same sub-problem/state(<u>`x`</u>-<u>`c`</u>). Thus, we can solve this once, and use its result again and again!\n\n\nHence, **Dynamic Programming**. Choose the best from all possible states. And, instead of computing again and again, save what you have already computed. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity.\n\n\n\n----\n\n\n# \uD83D\uDCD1 Dynamic Programming\nAs evident from the above two examples [Posted as Pattern], to determine a **state**, we essentially need 3 things\n- `L`: left pointer in `nums`. Indicates we have used `L` numbers from left in `nums`.\n- `R`: right pointer in `nums`. Indicates we have used `R` numbers from right in `nums`.\n- `W`: number of operations done. Will be one more than the current index of `multipliers`\n\nHence, there are 3 state variables, `L`, `R`, and `W`. Hence, it\'s a 3D Dynamic Programming Problem. And to memoize it, we may need 3D Array.\n> If there are `n` state variables, then we need an array of <u>atmost</u> `n` dimensions.\n\nBut, without much brain-storming, we CAN reduce 3 state variables to 2. \nThe `R` can be calculated as `(n - 1) - (W - L) `. \n> **How?**\n> Well, there are `n` elements in `nums`. If we have done `W` operations, and left is *ahead* by `L`, means there are `W - L` operations from right. Thus, right should be *behind* `n-1` by `W-L`. Thus, the formula.\n\nThus, in our formulation, the state will be defined by two variables `i` and `j`. Let\'s used `X` to denote state, and thus, `X` represents the array where data will be memoized.\n\n> `X[i][j]` stores the **maximum possible score** after we have done `i` total operations and used `j` numbers from the left/start side.\n\nThus, from this state, we have two options\n- **Choose Left:** Then, the number of operations will increase by one. And, so does the left pointer. Thus, we will multiply `mulitpliers[i]` and `nums[j]` (since we have chosen from left), and add this product to the (optimal) result of state `X[i+1][j+1]`.\n- **Choose Right:** Then also the number of operations will increase by one. Thus, we will multiply `mulitpliers[i]` with `nums[n-1-(i-j)]` (since we have chosen from right), and add this product to the (optimal) result of state `X[i+1][j]` (Now, `j` will not increment since the number has not been chosen from left).\n\nChoose **maximum** of results obtained from choosing from left, or right. \n\nIf `i==m`, means we have performed `m` operations, add 0. The base condition of Recursion.\n\nThus, we can formulate\n\n> [![image.png]()]()\n\nAnd, the Code!\n\n----\n\n\n# \uD83D\uDDA5 Code\n\n**Python**\n- Recursive using [@lru_cache(None)]() \n\n```python\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n = len(nums)\n m = len(multipliers)\n \n @lru_cache(None)\n #To Save Computed Result\n \n def X(i, left):\n \n if i==m:\n return 0\n \n return max ( (multipliers[i] * nums[left]) + X(i + 1, left + 1), \n (multipliers[i] * nums[n-1-(i-left)]) + X(i + 1, left) ) \n \n #Start from Zero operations\n return X(0,0)\n```\n\n- Iterative.\n\n```python\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n, m = len(nums), len(multipliers)\n dp = [[0] * (m + 1) for _ in range(m + 1)]\n \n for i in range(m - 1, -1, -1):\n for left in range(i, -1, -1):\n \n dp[i][left] = max ( multipliers[i] * nums[left] + dp[i + 1][left + 1], \n multipliers[i] * nums[n - 1 - (i - left)] + dp[i + 1][left] ) \n \n return dp[0][0]\n```\n\n**Time Complexity :** O(m<sup>2</sup>) as evident from loops\n**Space Complexity :** O(m<sup>2</sup>) as evident from `dp`\n\n\n----\n\n\n# \u23F3 Optimizing\nWe can optimize this in space dimension. On carefully observing the formula in the image and iterative code, we can conclude that for computing present row `i`, we need next row `i+1` only. Moreover, we can fill the column backward, since present column `left` depends on `left+1` and `left` only. Thus, we are not losing any essential information while filling 1D array this way. \n\n```python\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n, m = len(nums), len(multipliers)\n dp = [0] * (m + 1)\n \n for i in range(m - 1, -1, -1):\n nextRow = dp.copy()\n #Present Row is now nextRow, since iterating upwards\n \n for left in range(i,-1,-1):\n \n dp[left] = max ( multipliers[i] * nums[left] + nextRow[left + 1], \n multipliers[i] * nums[n - 1 - (i - left)] + nextRow[left] ) \n \n return dp[0]\n```\n\n**Time Complexity :** O(m<sup>2</sup>) as evident from loops\n**Space Complexity :** O(m) as evident from `dp`\n> [![image.png]()]()\n\n\n---\n\n\n# \uD83D\uDCA1 Conclusion\n\nHence, starting from very intuitive greedy, we realized we were wrong and ultimately we have to check for all possible combinations which isn\'t efficient. Problem has two key properties, thus Dynamic Programming! Here is one of the Final [but not claiming to be most optimized] Code, with O(m<sup>2</sup>) Time Complexity and O(m) Space Complexity.\n\n```c []\nint max(int a, int b) {return a>b ? a : b ;}\n\nint maximumScore(int* nums, int numsSize, int* multipliers, int multipliersSize)\n{\n int n = numsSize, m=multipliersSize;\n register int i, left, k;\n\n int dp[m+1];\n for (k=0; k<=m ; k++) dp[k]=0;\n \n for(i=m-1; i>=0; i--)\n {\n int nextRow[m+1];\n for (register int k=0; k<=m ; k++) nextRow[k]=dp[k];\n \n for (left=i; left>=0; left--)\n {\n dp[left] = max ( multipliers[i] * nums[left] + nextRow[left + 1], \n multipliers[i] * nums[n - 1 - (i - left)] + nextRow[left] ); \n }\n }\n \n return dp[0];\n}\n```\n```python3 []\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n, m = len(nums), len(multipliers)\n dp = [0] * (m + 1)\n \n for i in range(m - 1, -1, -1):\n nextRow = dp.copy()\n #Present Row is now nextRow, since iterating upwards\n \n for left in range(i,-1,-1):\n \n dp[left] = max ( multipliers[i] * nums[left] + nextRow[left + 1], \n multipliers[i] * nums[n - 1 - (i - left)] + nextRow[left] ) \n \n return dp[0]\n```\n\n\n\n<br>\n\n- \u2B06\uFE0F If you have gained some insights, feel free to upvote. Button Below \n- \u2B50 Feel free to add to your Favorite Solutions by clicking on Star.\n- \uD83D\uDE15 If you are confused, or have some doubts, post comments.\n- \uD83D\uDCA1 Any mistake or Have another idea? Share in Comments. \n\n\n----\n\n\n# \uD83E\uDD16 \uD835\uDDD8\uD835\uDDF1\uD835\uDDF6\uD835\uDE01\uD835\uDE00/\uD835\uDDE5\uD835\uDDF2\uD835\uDDFD\uD835\uDDF9\uD835\uDE06\uD835\uDDF6\uD835\uDDFB\uD835\uDDF4 \uD835\uDE01\uD835\uDDFC \uD835\uDDE4\uD835\uDE02\uD835\uDDF2\uD835\uDDFF\uD835\uDDF6\uD835\uDDF2\uD835\uDE00\n\nSpace for your feedback. This Section will take care of Edits and Reply to Comments/Doubts.\n\n**Edit :** Thanks for all the motivating comments. This article was written on Old UI, hence few sections are less readable. Although, I believe content quality isn\'t compromised. \u2764\n\n---------- \n <br>\n
92,351
Maximum Score from Performing Multiplication Operations
maximum-score-from-performing-multiplication-operations
You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will: Return the maximum score after performing m operations.
Array,Dynamic Programming
Medium
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence dp is a perfect choice here.
285
5
Upvote if it helped. thanks\n\n```\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n s=0\n n=len(nums)\n m=len(multipliers)\n dp=[[0]*(m+1) for i in range(m+1)]\n for j in range(m-1, -1, -1):\n for low in range(j, -1, -1):\n first=nums[low]*multipliers[j]+dp[j+1][low+1]\n last=nums[n-1-(j-low)]*multipliers[j]+dp[j+1][low]\n dp[j][low]=max(first, last)\n return dp[0][0]\n```
92,355
Maximum Score from Performing Multiplication Operations
maximum-score-from-performing-multiplication-operations
You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed. You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will: Return the maximum score after performing m operations.
Array,Dynamic Programming
Medium
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence dp is a perfect choice here.
6,330
65
\n```\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n, m = len(nums), len(multipliers)\n dp = [[0]*m for _ in range(m+1)]\n \n for i in reversed(range(m)):\n for j in range(i, m): \n k = i + m - j - 1\n dp[i][j] = max(nums[i] * multipliers[k] + dp[i+1][j], nums[j-m+n] * multipliers[k] + dp[i][j-1])\n \n return dp[0][-1]\n```\n\nThis is the kind of problems that I really hate as it cannot pass for the plain top-down dp without tricks. Problems like this can be really misleading during contest as it causes people to suspect if it is really a dp. \n\n```\nclass Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n \n @lru_cache(2000)\n def fn(lo, hi, k):\n """Return max score from nums[lo:hi+1]."""\n if k == len(multipliers): return 0\n return max(nums[lo] * multipliers[k] + fn(lo+1, hi, k+1), nums[hi] * multipliers[k] + fn(lo, hi-1, k+1))\n \n return fn(0, len(nums)-1, 0)\n```
92,369
Maximize Palindrome Length From Subsequences
maximize-palindrome-length-from-subsequences
You are given two strings, word1 and word2. You want to construct a string in the following manner: Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0. A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward.
String,Dynamic Programming
Hard
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
709
15
**Algo**\nFind common characters in `word1` and `word2` and use the anchor to find longest palindromic subsequence. \n\n**Implementation**\n```\nclass Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n \n @cache\n def fn(lo, hi):\n """Return length of longest palindromic subsequence."""\n if lo >= hi: return int(lo == hi)\n if word[lo] == word[hi]: return 2 + fn(lo+1, hi-1)\n return max(fn(lo+1, hi), fn(lo, hi-1))\n \n ans = 0\n word = word1 + word2\n for x in ascii_lowercase: \n i = word1.find(x) \n j = word2.rfind(x)\n if i != -1 and j != -1: ans = max(ans, fn(i, j + len(word1)))\n return ans \n```\n\n**Analysis**\nTime complexity `O((M+N)^2)`\nSpace complexity `O((M+N)^2)`
92,399
Maximize Palindrome Length From Subsequences
maximize-palindrome-length-from-subsequences
You are given two strings, word1 and word2. You want to construct a string in the following manner: Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0. A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters. A palindrome is a string that reads the same forward as well as backward.
String,Dynamic Programming
Hard
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty.
402
5
```\nclass Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n s1 = word1 + word2\n n = len(s1)\n dp = [[0] * n for i in range(n)]\n ans = 0\n for i in range(n-1,-1,-1):\n\t\t# mark every character as a 1 length palindrome\n dp[i][i] = 1\n for j in range(i+1,n):\n\t\t\t# new palindrome is found\n if s1[i] == s1[j]:\n dp[i][j] = dp[i+1][j-1] + 2\n\t\t\t\t\t# if the palindrome includes both string consider it as a valid\n if i < len(word1) and j >= len(word1):\n ans = max(ans,dp[i][j])\n else:\n dp[i][j] = max(dp[i][j-1],dp[i+1][j])\n \n return ans\n```
92,403
Count Items Matching a Rule
count-items-matching-a-rule
You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue. The ith item is said to match the rule if one of the following is true: Return the number of items that match the given rule.
Array,String
Easy
Iterate on each item, and check if each one matches the rule according to the statement.
5,898
64
### Explanation\n- Create a dict `{ruleKey: index_of_rulekey}`\n- Filter out items that satisfy the condition\n\n### Implementation\n```\nclass Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n d = {\'type\': 0, \'color\': 1, \'name\': 2}\n return sum(1 for item in items if item[d[ruleKey]] == ruleValue)\n```
92,464