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
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.
714
8
# Intuition\nThe problem requires counting the number of items that match a given rule. We are given an array of items, where each item is represented by its type, color, and name. The rule is defined by a ruleKey and a ruleValue. We need to determine if the ruleKey matches the corresponding attribute of each item, and if so, check if the ruleValue matches the value of that attribute. By counting the items that satisfy the rule, we can determine the final result.\n\n\n# Approach\nWe can solve the problem by iterating over each item in the items array. For each item, we check if the ruleKey matches the corresponding attribute and if the ruleValue matches the value of that attribute. If both conditions are true, we increment a counter variable by 1. Finally, we return the value of the counter variable, which represents the number of items that match the given rule.\n\n\n# Complexity\n- Time complexity:\nThe time complexity of this approach is O(n), where n is the number of items in the input array. We iterate over each item once to check if it matches the given rule.\n\n\n- Space complexity:\nThe space complexity is O(1) because we only use a constant amount of additional space to store the counter variable and the loop variables. The input array is not modified during the process, so we don\'t need any extra space to store intermediate results.\n\n\n\n# Code\n```\nclass Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n res=0\n for i in items:\n if ruleKey=="type":\n if i[0]==ruleValue:\n res+=1\n elif ruleKey=="color":\n if i[1]==ruleValue:\n res+=1\n elif ruleKey=="name":\n if i[2]==ruleValue:\n res+=1\n return res\n\n```
92,468
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.
687
5
Runtime: 305 ms, faster than 70.89% of Python3 online submissions for Count Items Matching a Rule.\nMemory Usage: 20.3 MB, less than 34.60% of Python3 online submissions for Count Items Matching a Rule.\n\n```\nclass Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n return sum(item_list[{"type": 0, "color": 1, "name": 2}[ruleKey]] == ruleValue for item_list in items)
92,476
Closest Dessert Cost
closest-dessert-cost
You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert: You are given three inputs: You want to make a dessert with a total cost as close to target as possible. Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
Array,Dynamic Programming,Backtracking
Medium
As the constraints are not large, you can brute force and enumerate all the possibilities.
4,648
24
\n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n toppingCosts *= 2\n \n @cache\n def fn(i, x):\n """Return sum of subsequence of toppingCosts[i:] closest to x."""\n if x < 0 or i == len(toppingCosts): return 0\n return min(fn(i+1, x), toppingCosts[i] + fn(i+1, x-toppingCosts[i]), key=lambda y: (abs(y-x), y))\n \n ans = inf\n for bc in baseCosts: \n ans = min(ans, bc + fn(0, target - bc), key=lambda x: (abs(x-target), x))\n return ans \n```\nTime complexity `O(MNV)`\n\nEdited on 2/28/2021\n\nAdding the version by @lenchen1112\n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n \n @cache\n def fn(i, cost):\n """Return sum of subsequence closest to target."""\n if cost >= target or i == len(toppingCosts): return cost\n return min(fn(i+1, cost), fn(i+1, cost+toppingCosts[i]), key=lambda x: (abs(x-target), x))\n \n ans = inf\n toppingCosts *= 2\n for cost in baseCosts: \n ans = min(ans, fn(0, cost), key=lambda x: (abs(x-target), x))\n return ans \n```\n\nAdding binary search implementation\n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n top = {0}\n for x in toppingCosts*2: \n top |= {x + xx for xx in top}\n top = sorted(top)\n \n ans = inf \n for bc in baseCosts: \n k = bisect_left(top, target - bc)\n if k < len(top): ans = min(ans, bc + top[k], key=lambda x: (abs(x-target), x))\n if k: ans = min(ans, bc + top[k-1], key=lambda x: (abs(x-target), x))\n return ans \n```\nTime complexity `O(N*2^(2N) + MN)`
92,494
Closest Dessert Cost
closest-dessert-cost
You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert: You are given three inputs: You want to make a dessert with a total cost as close to target as possible. Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
Array,Dynamic Programming,Backtracking
Medium
As the constraints are not large, you can brute force and enumerate all the possibilities.
1,901
15
Just by looking at the constrains 1<=n,m<=10 we can say that this problem can be easily solved using backtracking.\n\nIdea: Generate all possible solutions, In the below given fashion.\n![image]()\n\nI hope this recursive idea makes sense!\n\nLet n = number of bases and m = number of toppings\nTime = O(n) for base and O(3^m) for toppings as each toppings has three possibilities (0,1,2) = O(n * 3^m).\nSpace = O(3^n) for a ternary tree (3-way recursive stack).\n\nThe Full code:\n```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n self.ans = self.diff = float(\'inf\')\n \n n = len(baseCosts)\n m = len(toppingCosts)\n \n \n def solve(sum, target, indx):\n if abs(sum - target) < self.diff:\n self.diff = abs(sum - target)\n self.ans = sum\n elif abs(sum - target) == self.diff:\n self.ans = min(self.ans, sum)\n \n \n if indx == m:\n return\n \n i = indx\n for count in range(3):\n sum += toppingCosts[i]*count\n solve(sum,target,i+1)\n sum -= toppingCosts[i]*count\n \n for i in baseCosts:\n solve(i, target, 0)\n return self.ans\n```\n
92,500
Closest Dessert Cost
closest-dessert-cost
You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert: You are given three inputs: You want to make a dessert with a total cost as close to target as possible. Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.
Array,Dynamic Programming,Backtracking
Medium
As the constraints are not large, you can brute force and enumerate all the possibilities.
750
7
```\nclass Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n q = [target - basecost for basecost in baseCosts]\n\n for toppingcost in toppingCosts:\n q += [val - cost for val in q if val > 0 for cost in (toppingcost, toppingcost * 2)]\n\n return target - min(q, key=lambda x: abs(x) * 2 - (x > 0))\n```
92,504
Equal Sum Arrays With Minimum Number of Operations
equal-sum-arrays-with-minimum-number-of-operations
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.
Array,Hash Table,Greedy,Counting
Medium
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
4,138
82
We have two arrays, by calculating the sum, we can know which is larger and which is the smaller.\nTo reach a same sum value (reduce the difference on sum to 0):\n* For larger array, at each operation, we want to decrease the number as much as possible.\nSince the min value we can decrease to is 1, at position` i`, the max contribution (to reduce the difference) we can "gain" is ` larger_array[i] - 1`\n* Similarly, for smaller array, we want to increase the number as much as possible. \nSince the max value we can increase to is 6, the "gain" at position `i` is ` 6-smaller_array[i]`\n\nThus, following this idea, we can: \n1. calculate the "gain" at each position in the larger and smaller array\n2. sort them together in an ascending order.\n3. by accumulating the "gain" from large to small, we can know the least steps to reduce the difference to 0 \n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \n\t\t# step1. determine the larger array and the smaller array, and get the difference on sum\n sum1 = sum(nums1)\n sum2 = sum(nums2)\n \n if sum1==sum2:\n return 0\n elif sum1>sum2:\n larger_sum_nums = nums1\n smaller_sum_nums = nums2\n else:\n larger_sum_nums = nums2\n smaller_sum_nums = nums1\n\t\t\n sum_diff = abs(sum1-sum2)\n \n # step2. calculate the max "gain" at each position (how much difference we can reduce if operating on that position) \n gains_in_larger_array = [num-1 for num in larger_sum_nums]\n gains_in_smaller_array = [6-num for num in smaller_sum_nums]\n \n\t\t# step3. sort the "gain" and check the least number of steps to reduce the difference to 0\n gains = gains_in_larger_array + gains_in_smaller_array\n gains.sort(reverse = True)\n \n count = 0\n target_diff = sum_diff\n \n for i in range(len(gains)):\n target_diff -= gains[i]\n count += 1\n \n if target_diff <= 0:\n return count\n\t\t\n\t\t# return -1 if the difference still cannot be reduced to 0 even after operating on all positions\n return -1\n```
92,544
Equal Sum Arrays With Minimum Number of Operations
equal-sum-arrays-with-minimum-number-of-operations
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.
Array,Hash Table,Greedy,Counting
Medium
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
1,434
19
\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n if 6*len(nums1) < len(nums2) or 6*len(nums2) < len(nums1): return -1 # impossible \n \n if sum(nums1) < sum(nums2): nums1, nums2 = nums2, nums1\n s1, s2 = sum(nums1), sum(nums2)\n \n nums1 = [-x for x in nums1] # max-heap \n heapify(nums1)\n heapify(nums2)\n \n ans = 0\n while s1 > s2: \n x1, x2 = nums1[0], nums2[0]\n if -1-x1 > 6-x2: # change x1 to 1\n s1 += x1 + 1\n heapreplace(nums1, -1)\n else: \n s2 += 6 - x2\n heapreplace(nums2, 6)\n ans += 1\n return ans \n```\n\nEdited on 2/28/2021\nAdding 2-pointer approach \n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n if 6*len(nums1) < len(nums2) or 6*len(nums2) < len(nums1): return -1 # impossible \n \n if sum(nums1) < sum(nums2): nums1, nums2 = nums2, nums1\n s1, s2 = sum(nums1), sum(nums2) # s1 >= s2\n \n nums1.sort()\n nums2.sort()\n \n ans = j = 0\n i = len(nums1)-1\n \n while s1 > s2: \n if j >= len(nums2) or 0 <= i and nums1[i] - 1 > 6 - nums2[j]: \n s1 += 1 - nums1[i]\n i -= 1\n else: \n s2 += 6 - nums2[j]\n j += 1\n ans += 1\n return ans \n```
92,551
Equal Sum Arrays With Minimum Number of Operations
equal-sum-arrays-with-minimum-number-of-operations
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.
Array,Hash Table,Greedy,Counting
Medium
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
1,084
13
### Explanation\n- There will be a difference (`diff`) between `the sum of nums1` and `the sum of nums2`\n- To make the `diff` converges to 0 the fastest way, we want to make \n\t- The list with larger sum, become smaller\n\t- The list with smaller sum, become larger\n\t- We define `effort` as the absolute difference between the new value & the original value\n\t- In each turn, whoever makes the greater `effort` will get picked (use `heap` for the help)\n- Above is the idea for the first `while` loop\n- If there are `nums1` or `nums2` left over, use them up until the difference is less than or equal to 0\n\t- Second & third `while` loop\n- Return `ans` only if `diff` is less than or equal to 0, otherwise return -1 as there is no way to make `diff` to 0\n### Implementation\n```\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n s1, s2 = sum(nums1), sum(nums2)\n if s1 > s2:\n s1, s2 = s2, s1\n nums1, nums2 = nums2, nums1\n # to make s1 < s2 \n heapq.heapify(nums1) \n nums2 = [-num for num in nums2]\n heapq.heapify(nums2) \n ans = 0\n diff = s2 - s1\n while diff > 0 and nums1 and nums2:\n a = 6 - nums1[0]\n b = - (1 + nums2[0])\n if a > b:\n heapq.heappop(nums1) \n diff -= a\n else:\n heapq.heappop(nums2) \n diff -= b\n ans += 1 \n while diff > 0 and nums1: \n a = 6 - heapq.heappop(nums1) \n diff -= a\n ans += 1 \n while diff > 0 and nums2: \n b = - (1 + heapq.heappop(nums2))\n diff -= b\n ans += 1 \n return ans if diff <= 0 else -1\n```
92,558
Equal Sum Arrays With Minimum Number of Operations
equal-sum-arrays-with-minimum-number-of-operations
You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive. In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive. Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.
Array,Hash Table,Greedy,Counting
Medium
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
646
6
Few Things to consider before approching to the solution:\n1. We should always decrease the elements of an array having higher sum.\n2. We should always increase the elements of an array having lower sum.\n3. It\'s always better to target the element having higher flexibility to change (Greedy). \n\n**What is element flexibility?** \nElement flexibility is capability of stretching or shriking the value. \nFor Example,\nIf my number is 4, it has maximum stretchability of 2 (6-4) in the right direction.\nand maximum shrikability of 3 (4-1) in the left direction.\n1 <- 2 <- 3 <- *4* -> 5 -> 6\nAs discussed above, we\'ll go towards only one direction for a particular element.\n\n```\nclass Solution:\n\t# This function takes the merged arrays and sort them according to the flexibilties of element.\n\t# No matter whether the element shrink or stretch, we are concerned about how much change they bring.\n def findNums(self, arr, val):\n arr = sorted(arr, reverse = True)\n count = 0\n flag = False\n\t\t# Taking the highest number and reducing the difference\n for i in arr:\n if val >= i:\n val -= i\n count += 1\n elif val > 0:\n return count + 1\n if val == 0:\n return count\n return -1\n \n def minOperations(self, num1: List[int], num2: List[int]) -> int:\n s1, s2 = sum(num1), sum(num2)\n # difference to cover\n\t\tdiff = abs(s1-s2)\n if s1 == s2:\n return 0\n\t\t# we define flexibilities of each item in one direction.\n if s1 > s2: \n cnum1 = [i-1 for i in num1]\n cnum2 = [6-i for i in num2]\n else:\n cnum1 = [6-i for i in num1]\n cnum2 = [i-1 for i in num2]\n return self.findNums(cnum1 + cnum2, diff)\n```
92,563
Car Fleet II
car-fleet-ii
There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents: For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet. Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.
Array,Math,Stack,Heap (Priority Queue),Monotonic Stack
Hard
We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all cars with speeds higher than the current car since the current car cannot intersect with those ones. Now, all cars to the right having speed strictly less than current car are to be considered. Now, for two cars c1 and c2 with positions p1 and p2 (p1 < p2) and speed s1 and s2 (s1 > s2), if c1 and c2 intersect before the current car and c2, then c1 can never be the first car of intersection for any car to the left of current car including current car. So we can remove that car from our consideration. We can see that we can maintain candidate cars in this way using a stack, removing cars with speed greater than or equal to current car, and then removing cars which can never be first point of intersection. The first car after this process (if any) would be first point of intersection.
1,320
12
The problem can be solved with a heap or a stack. Heap solution is probably easier to arrive at, given that it only requires us to make two observations about the input, but involves writing more code. Stack solution is elegant and fast, but is harder to come up with, since we have to make more observations about the input.\n\n# Heap solution\nThe intuition behind this solution is that earlier collisions have the potential to affect later collisions and not vice versa. Therefore we\'d like to process collisions in the order they are happening. For this, we put each car that has a potential to collide with the next one in a heap and order it based on the expected collision time based on cars\' positions and speed. A car that has collided is no longer interesting to us, since the previous car can now only collide with the car that follows it. To emulate this behavior we place cars in a linked list so we can easily remove the car after collision.\n## Complexity\nTime: O(NlogN)\nSpace: O(N)\n```\nclass Car:\n def __init__(self, pos, speed, idx, prev=None, next=None):\n self.pos = pos\n self.speed = speed\n self.idx = idx\n self.prev = prev\n self.next = next\n\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n colis_times = [-1] * len(cars)\n cars = [Car(pos, sp, i) for i, (pos, sp) in enumerate(cars)]\n for i in range(len(cars)-1): cars[i].next = cars[i+1]\n for i in range(1, len(cars)): cars[i].prev = cars[i-1]\n \n catchup_order = [((b.pos-a.pos)/(a.speed-b.speed), a.idx, a)\n for i, (a, b) \n in enumerate(zip(cars, cars[1:])) if a.speed > b.speed]\n heapify(catchup_order)\n \n while catchup_order:\n catchup_time, idx, car = heappop(catchup_order)\n if colis_times[idx] > -1: continue # ith car has already caught up\n colis_times[idx] = catchup_time\n if not car.prev: continue # no car is following us\n car.prev.next, car.next.prev = car.next, car.prev\n if car.next.speed >= car.prev.speed: continue # the follower is too slow to catch up\n new_catchup_time = (car.next.pos-car.prev.pos)/(car.prev.speed-car.next.speed)\n heappush(catchup_order, (new_catchup_time, car.prev.idx, car.prev))\n \n return colis_times\n```\n# Stack solution\nObservations:\n* For every car we only care about the cars ahead, because those are the ones that we can collide with.\n* Among those ahead of us, some are faster and we will never catch up with those, so we can ignore them.\n* Some of the cars ahead that are slower than us will be in a collision before us, those we can also ignore because after they collide they are not any different to us that the car they collided with.\n* Anything we ignore can also be safely ignored by the cars that follow us, because they can only go as fast as us after colliding with us.\n\nBased on aforementioned observations we produce a stack solution below. We iterate over the cars starting from the last one and process the cars in front of us, getting rid of them if they are no longer interesting.\nTip: for index `i`, `~i` will give us the index with the same offset from the end of the array, e.g. for ` == 0`, `~i == -1`, etc.\n## Complexity\nTime: O(N)\nSpace: O(N)\n```\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n colis_times = [-1] * len(cars)\n cars_in_front_stack = []\n for i, (position, speed) in enumerate(reversed(cars)):\n while cars_in_front_stack:\n front_car_pos, front_car_speed, front_car_collision = cars_in_front_stack[-1]\n if front_car_speed >= speed or \\\n (our_collision_with_front := (front_car_pos - position) / (speed - front_car_speed)) >= front_car_collision: \n cars_in_front_stack.pop()\n else: break\n \n if cars_in_front_stack:\n front_car_pos, front_car_speed, front_car_collision = cars_in_front_stack[-1]\n colis_times[~i] = (front_car_pos - position) / (speed - front_car_speed)\n cars_in_front_stack.append((position, speed, colis_times[~i] if colis_times[~i] != -1 else inf))\n \n return colis_times\n```
92,598
Second Largest Digit in a String
second-largest-digit-in-a-string
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits.
Hash Table,String
Easy
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
1,128
5
```\ndef secondHighest(self, s: str) -> int:\n digits = set()\n s = list(set(s))\n for letter in s:\n if letter.isdigit():\n digits.add(letter)\n digits = sorted(list(digits))\n return -1 if len(digits) < 2 else digits[-2]\n```\n![image]()\n
92,657
Second Largest Digit in a String
second-largest-digit-in-a-string
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits.
Hash Table,String
Easy
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
681
5
```\nclass Solution:\n def secondHighest(self, s: str) -> int:\n s=set(s)\n a=[]\n for i in s:\n if i.isnumeric() :\n a.append(int(i))\n a.sort()\n if len(a)<2:\n return -1\n return a[len(a)-2]\n```\n**optimized code**\n```\ndef secondHighest(self, s: str) -> int:\n st = (set(s))\n f1,s2=-1,-1\n for i in st:\n if i.isnumeric():\n i=int(i)\n if i>f1:\n s2=f1\n f1=i\n elif i>s2 and i!=f1:\n s2=i\n return s2\n```
92,658
Second Largest Digit in a String
second-largest-digit-in-a-string
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits.
Hash Table,String
Easy
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
1,269
16
```\ndef secondHighest(self, s):\n t = set() # create set to store unique digits\n for i in s:\n if \'0\'<=i<=\'9\':\n t.add(int(i)) # add digit to the set\n if len(t)>1:\n return sorted(list(t))[-2] # sort and return second largest one if number of elements are more than 1 \n return -1 # otherwise return -1\n```
92,664
Design Authentication Manager
design-authentication-manager
There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime. Implement the AuthenticationManager class: Note that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.
Hash Table,Design
Medium
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
2,328
10
```\nclass AuthenticationManager(object):\n\n def __init__(self, timeToLive):\n self.token = dict()\n self.time = timeToLive # store timeToLive and create dictionary\n\n def generate(self, tokenId, currentTime):\n self.token[tokenId] = currentTime # store tokenId with currentTime\n\n def renew(self, tokenId, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n if tokenId in self.token and self.token[tokenId]>limit: # filter tokens and renew its time\n self.token[tokenId] = currentTime\n\n def countUnexpiredTokens(self, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n c = 0\n for i in self.token:\n if self.token[i]>limit: # count unexpired tokens\n c+=1\n return c\n```
92,706
Maximize Score After N Operations
maximize-score-after-n-operations
You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array. In the ith operation (1-indexed), you will: Return the maximum score you can receive after performing n operations. The function gcd(x, y) is the greatest common divisor of x and y.
Array,Math,Dynamic Programming,Backtracking,Bit Manipulation,Number Theory,Bitmask
Hard
Find every way to split the array until n groups of 2. Brute force recursion is acceptable. Calculate the gcd of every pair and greedily multiply the largest gcds.
7,426
27
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. Next assignment will be shared tomorrow. **DON\'T FORGET** to Subscribe\n\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n# or\n\n# Click the Link in my Profile\n\n# Approach:\n\nThe given problem can be solved using dynamic programming. The basic idea is to consider all possible pairs of numbers in the given array and calculate their gcd. Then, we can use a bitmask to represent all possible subsets of indices and use dynamic programming to calculate the maximum score for each subset.\n\nTo calculate the maximum score for a given subset of indices, we can iterate over all possible pairs of indices in the subset and calculate their gcd. We can then add the product of this gcd and half the number of indices in the subset to the maximum score for the subset obtained by removing these indices from the original subset.\n\nThe maximum score for the original subset can then be obtained by considering all possible subsets of indices and choosing the one with the maximum score.\n\n# Intuition:\n\nThe problem requires us to maximize a score that is calculated based on the gcd of pairs of numbers in the given array. We can observe that if we fix a pair of indices, the gcd of the corresponding pair of numbers will be the same for all subsets that contain these indices. Therefore, we can precompute the gcd of all pairs of numbers in the array and use it to calculate the score for each subset.\n\nWe can also observe that if we remove a pair of indices from a subset, the resulting subset will have an even number of indices. This is because the total number of indices in the original subset is even, and removing a pair of indices will reduce this number by 2. Therefore, we can iterate over all possible even-sized subsets of indices and use dynamic programming to calculate the maximum score for each subset.\n\n\n\n\n\n\n```Python []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n n = len(nums)\n \n \n gcd_matrix = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(i+1, n):\n gcd_matrix[i][j] = gcd_matrix[j][i] = gcd(nums[i], nums[j])\n \n \n dp = [0] * (1 << n)\n \n \n for state in range(1, 1 << n):\n \n cnt = bin(state).count(\'1\')\n \n \n if cnt % 2 == 1:\n continue\n \n \n for i in range(n):\n if not (state & (1 << i)):\n continue\n for j in range(i+1, n):\n if not (state & (1 << j)):\n continue\n nextState = state ^ (1 << i) ^ (1 << j)\n dp[state] = max(dp[state], dp[nextState] + cnt // 2 * gcd_matrix[i][j])\n \n return dp[(1 << n) - 1]\n\n```\n```Java []\nclass Solution {\n public int maxScore(int[] nums) {\n int n = nums.length;\n \n \n int[][] gcdMatrix = new int[n][n];\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n gcdMatrix[i][j] = gcdMatrix[j][i] = gcd(nums[i], nums[j]);\n }\n }\n \n \n int[] dp = new int[1 << n];\n \n \n for (int state = 1; state < (1 << n); state++) {\n \n int cnt = Integer.bitCount(state);\n \n \n if (cnt % 2 == 1) {\n continue;\n }\n \n \n for (int i = 0; i < n; i++) {\n if ((state & (1 << i)) == 0) {\n continue;\n }\n for (int j = i + 1; j < n; j++) {\n if ((state & (1 << j)) == 0) {\n continue;\n }\n int nextState = state ^ (1 << i) ^ (1 << j);\n dp[state] = Math.max(dp[state], dp[nextState] + cnt / 2 * gcdMatrix[i][j]);\n }\n }\n }\n \n return dp[(1 << n) - 1];\n }\n \n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int maxScore(vector<int>& nums) {\n int n = nums.size();\n \n \n vector<vector<int>> gcdMatrix(n, vector<int>(n));\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n gcdMatrix[i][j] = gcdMatrix[j][i] = gcd(nums[i], nums[j]);\n }\n }\n \n \n vector<int> dp(1 << n);\n \n \n for (int state = 1; state < (1 << n); state++) {\n \n int cnt = __builtin_popcount(state);\n \n \n if (cnt % 2 == 1) {\n continue;\n }\n \n \n for (int i = 0; i < n; i++) {\n if ((state & (1 << i)) == 0) {\n continue;\n }\n for (int j = i + 1; j < n; j++) {\n if ((state & (1 << j)) == 0) {\n continue;\n }\n int nextState = state ^ (1 << i) ^ (1 << j);\n dp[state] = max(dp[state], dp[nextState] + cnt / 2 * gcdMatrix[i][j]);\n }\n }\n }\n \n return dp[(1 << n) - 1];\n }\n \n int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n};\n\n```\n# An Upvote will be encouraging \uD83D\uDC4D
92,787
Count Pairs With XOR in a Range
count-pairs-with-xor-in-a-range
Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs. A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.
Array,Bit Manipulation,Trie
Hard
Let's note that we can count all pairs with XOR ≤ K, so the answer would be to subtract the number of pairs withs XOR < low from the number of pairs with XOR ≤ high. For each value, find out the number of values when you XOR it with the result is ≤ K using a trie.
2,515
45
\n```\nclass Trie: \n def __init__(self): \n self.root = {}\n \n def insert(self, val): \n node = self.root \n for i in reversed(range(15)):\n bit = (val >> i) & 1\n if bit not in node: node[bit] = {"cnt": 0}\n node = node[bit]\n node["cnt"] += 1\n \n def count(self, val, high): \n ans = 0 \n node = self.root\n for i in reversed(range(15)):\n if not node: break \n bit = (val >> i) & 1 \n cmp = (high >> i) & 1\n if cmp: \n if node.get(bit, {}): ans += node[bit]["cnt"]\n node = node.get(1^bit, {})\n else: node = node.get(bit, {})\n return ans \n \n \nclass Solution:\n def countPairs(self, nums: List[int], low: int, high: int) -> int:\n trie = Trie()\n ans = 0\n for x in nums: \n ans += trie.count(x, high+1) - trie.count(x, low)\n trie.insert(x)\n return ans \n```
92,794
Count Pairs With XOR in a Range
count-pairs-with-xor-in-a-range
Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs. A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.
Array,Bit Manipulation,Trie
Hard
Let's note that we can count all pairs with XOR ≤ K, so the answer would be to subtract the number of pairs withs XOR < low from the number of pairs with XOR ≤ high. For each value, find out the number of values when you XOR it with the result is ≤ K using a trie.
1,423
16
We can use some number theory to calculate all possible XOR values of two numbers in the range (0, max(nums)). Obviously this knowledge isn\'t expected in a normal interview, but it can come in handy.\n\nThe trick, which is used in cryptography/signal processing, is to convert our array into a frequency array, then use an [n-dimensional Discrete Fourier Transform]() called the Walsh-Hadamard transform on those frequencies. The algorithm is short, and even has the full Python code on the Wikipedia page. Here, n = log(N) is the bit-length of N, the max value of nums. The transform can be done in N log N steps with divide and conquer (which you can do iteratively with log N loops of length N each). \n\nThen the transformed frequency of pairs with each XOR value becomes the square of each element in our transformed array (using properties of Fourier transforms). Inverting the transform (which is equivalent to the normal transform with an extra division at the end) gives us our desired pair-frequency array.\n\n\n\n```python\ndef countPairs(self, nums, low, high):\n\tdef walsh_hadamard(my_freqs):\n\t\tmy_max = len(my_freqs)\n\n\t\t# If our array\'s length is not a power of 2, \n\t\t# increase its length by padding zeros to the right\n\t\tif my_max & (my_max - 1):\n\t\t\tmy_max = 2 ** (my_max.bit_length())\n\n\t\tif my_max > len(my_freqs):\n\t\t\tmy_freqs.extend([0] * (my_max - len(my_freqs)))\n\n\t\th = 2\n\t\twhile h <= my_max:\n\t\t\thf = h // 2\n\t\t\tfor i in range(0, my_max, h):\n\t\t\t\tfor j in range(hf):\n\t\t\t\t\tu, v = my_freqs[i + j], my_freqs[i + j + hf]\n\t\t\t\t\tmy_freqs[i + j], my_freqs[i + j + hf] = u + v, u - v\n\t\t\th *= 2\n\t\treturn my_freqs\n\n\thigh += 1\n\tmax_num = max(nums) + 1\n\t# If high is larger than any possible XOR,\n\t# we can use a results array of the size of max(nums)\n\tif high.bit_length() > max_num.bit_length():\n\t\tmy_max1 = max_num\n\telse:\n\t\tmy_max1 = max(high, max_num)\n\n\tmy_freq = [0] * my_max1\n\tfor x in nums:\n\t\tmy_freq[x] += 1\n\n\t# Get the WHT transform of our frequencies, square it,\n\t# and take a second transform (which we invert after summing)\n\tmy_freq = walsh_hadamard([x * x for x in walsh_hadamard(my_freq)])\n\n\t# Find the sum of freq in our range,\n\t# divide by 2 to count only (i,j) with i<j,\n\t# and divide by length to invert\n\treturn sum(my_freq[low:high]) // (2 * len(my_freq))\n```\nRun time is O(N log N) here with a slight catch: the N here means the maximum of nums, not the length of our initial array, which means that sparse arrays will have worse runtime than the other solutions, especially the O(n) trie solutions. This can probably be fixed by using a defaultdict to hold our frequencies and modifying the transform code, although that implementation might be a bit tricky. Also, this easily generalizes when we want XOR pairs from 2 different arrays, although the Trie solution can handle that case as well.
92,797
Recyclable and Low Fat Products
recyclable-and-low-fat-products
Table: Products Write an SQL query to find the ids of products that are both low fat and recyclable. Return the result table in any order. The query result format is in the following example.
Database
Easy
null
1,381
8
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```python []\ndef find_products(products: pd.DataFrame) -> pd.DataFrame:\n return products[\n (products[\'low_fats\'] == \'Y\') & \\\n (products[\'recyclable\'] == \'Y\')\n ][[\'product_id\']]\n\n```\n```SQL []\nSELECT product_id\n FROM Products\n WHERE low_fats = \'Y\'\n AND recyclable = \'Y\';\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
92,848
Check if Binary String Has at Most One Segment of Ones
check-if-binary-string-has-at-most-one-segment-of-ones
Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false.
String
Easy
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
1,729
38
**Solution 1**: Check for ```"01"```\nSince the input string cannot ```s``` cannot have any leading zeroes and must contain ```at most one contiguous segment of 1s```, we need to check if ```"01"``` is present in ```s``` or not. If it is present, we can return False, else True.\n\nA few testcases to help understand the intuition:\n1. ```1100``` - True\n2. ```11001``` - False (since ```01``` is present).\n3. ```111111000000``` - True\n4. ```1101010100``` - False\n5. ```1``` - True\n6. ```1111110000111``` - False\n\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return "01" not in s\n```\n<br>\n<br>\n\n**Solution 2**: Using ```strip()```\n```strip("0")``` will remove both the leading and trailing zeroes in the string. Thus, if zeroes are present inside the string, the output must be False.\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n s = s.strip("0")\n return ("0" not in s)\n```\n
92,897
Check if Binary String Has at Most One Segment of Ones
check-if-binary-string-has-at-most-one-segment-of-ones
Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false.
String
Easy
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
968
15
I was just in the mood of trying out almost every single language on Leetcode \nAlmost all of the solutions were 0 ms and faster than 100% !!!\n**C++:**\n```\nclass Solution {\npublic:\n bool checkOnesSegment(string s) {\n return s.find("01") == -1;\n }\n};\n```\n**C:**\n```\nbool checkOnesSegment(char * s){\n return !strstr(s, "01");\n}\n```\n**Python:**\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return "01" not in s\n```\n**Java:**\n```\nclass Solution {\n public boolean checkOnesSegment(String s) {\n return !s.contains("01");\n }\n}\n```\n**Go:**\n```\nfunc checkOnesSegment(s string) bool {\n return !strings.Contains(s, "01")\n}\n```\n**C#:**\n```\npublic class Solution {\n public bool CheckOnesSegment(string s) {\n return !s.Contains("01");\n }\n}\n```\n**Javascript:**\n```\nvar checkOnesSegment = function(s) {\n return s.indexOf("01") == -1\n};\n```\n**Ruby:**\n```\ndef check_ones_segment(s)\n !s.include? \'01\'\nend\n```\n**Kotlin:**\n```\nclass Solution {\n fun checkOnesSegment(s: String): Boolean {\n return !("01" in s)\n }\n}\n```\n**Scala:**\n```\nobject Solution {\n def checkOnesSegment(s: String): Boolean = {\n return !s.contains("01")\n }\n}\n```\n**Rust:**\n```\nimpl Solution {\n pub fn check_ones_segment(s: String) -> bool {\n return !s.contains("01");\n }\n}\n```\n**Like it? please upvote!**
92,905
Minimum Elements to Add to Form a Given Sum
minimum-elements-to-add-to-form-a-given-sum
You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit. Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit. Note that abs(x) equals x if x >= 0, and -x otherwise.
Array,Greedy
Medium
Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the sum of the array. For example, if the goal is 5 and the sum is -3, then it's exactly the same as if the goal is 8 and the array is empty. The answer is ceil(abs(goal-sum)/limit) = (abs(goal-sum)+limit-1) / limit.
693
6
### Explanation\n- Find the absolute difference\n- Add new numbers using `limit`, count how many numbers need to be added using `ceil`\n### Implementation\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return math.ceil(abs(goal - sum(nums)) / limit)\n```
92,952
Make the XOR of All Segments Equal to Zero
make-the-xor-of-all-segments-equal-to-zero
You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.
Array,Dynamic Programming,Bit Manipulation
Hard
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
3,640
51
The first observation we need to make is that the moving window of size k must cycle. When a new element enter the window from the right, the same element must leave from the left.\n\nNow, we need to decide which element to place in each position of the window. Since the position of every element in `nums[i::k]` should be equal `for i in range(k)`, we first compile the freqency of each value for each position in the window.\n\n```python\nLIMIT = 2**3 # for now\nmrr = [[0 for _ in range(LIMIT)] for _ in range(k)]\nfor i,x in enumerate(nums):\n mrr[i%k][x] += 1\n```\n\nFor test case `nums = [3,4,5,2,1,7,3,4,7], k = 3` , the freqeuncy matrix now looks like this.\n\n```\n0 0 1 2 0 0 0 0\n0 1 0 0 2 0 0 0\n0 0 0 0 0 1 0 2\n```\n\nEach row is represents a position in the window. Each column represents a value (up to 8 for now). \n\nWe want to maximise the number of values that we do not change. The task is to choose one value from each row such that the target is maximised, subject to having the XOR of all selected values to be zero.\n\nYou might consider a greedy approach where you select the most common element in each position. However, there can be many ties to break and this greatly increases computational complexity.\n\nWe take a dymanic programming approach.\n- Each state is the XOR sum from the first position to the current position. There are C=1024 states.\n- Each stage is the position that we have considered. There are up to k=2000 stages.\n- The value of each state is the maximum number of values we could keep if we our XOR sum equal to the value.\n\nAt each position, we consider the previous position\n- If we choose to value for the current position, it maps all the previous XOR sum to a new XOR sum.\n- We update the dp considering\n - how often the value is found in the current position\n - the maximum number of values we have kept\n\n```python\ndp = [-2000 for _ in range(LIMIT)]\ndp[0] = 0\nfor row in mrr:\n new_dp = [0 for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev+cnt)\n dp = new_dp\n\nreturn len(nums) - new_dp[0]\n```\n\nThis is the value for each state after each stage of the dynamic programming.\n\n```\n0 - - - - - - -\n0 0 1 2 0 0 0 0\n2 2 3 2 2 2 3 4\n6 5 5 4 4 5 4 4\n```\n\nWe return the bottom left value - which is the maximum number of values we can leave unchanged such that the XOR of the window is zero.\n\nHowever, the complexity of the above algorithm is O(kC^2) which will run out of time.\n\nWe observe the we do not need to update the state if the count is zero. There are at most 2000 nonzero count because the array size is up to 2000. This reduces the complexity to O(nC).\n\nWe can split the enumerate logic into two cases - where `cnt == 0` and where `cnt > 0`\n\n```python\nfor row in mrr:\n new_dp = [0 for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n if cnt == 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev)\n for i,cnt in enumerate(row):\n if cnt > 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j],prev+cnt)\n dp = new_dp\n```\n\nThe iteration involving `cnt == 0` it is equivalent to applying `max(dp)` to `new_dp`.\n\nIterating `i^j` for all `j` for a given `i` will cover all 1024 possible values, because of how XOR functions works. When `prev = max(dp)`, this maximum score will be applied to all 1024 values. \n\nWe can replace the block with `cnt == 0` with an `O(C)` code that applies `max(dp)` to all of `new_dp`.\n\nThis is the full code.\n\n```python\ndef minChanges(self, nums: List[int], k: int) -> int:\n\n LIMIT = 2**10\n mrr = [[0 for _ in range(LIMIT)] \n for _ in range(k)]\n for i,x in enumerate(nums):\n mrr[i%k][x] += 1\n\n dp = [-2000 for _ in range(LIMIT)]\n dp[0] = 0\n for row in mrr:\n maxprev = max(dp)\n new_dp = [maxprev for _ in range(LIMIT)]\n for i,cnt in enumerate(row):\n if cnt > 0:\n for j,prev in enumerate(dp):\n new_dp[i^j] = max(new_dp[i^j], prev+cnt)\n dp = new_dp\n\n return len(nums) - new_dp[0]\n```
93,043
Make the XOR of All Segments Equal to Zero
make-the-xor-of-all-segments-equal-to-zero
You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.
Array,Dynamic Programming,Bit Manipulation
Hard
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
769
11
It took me a while to chew up other fellow\'s posts. So I think I could post my understandings here as well that may be helpful to somebody.\n\nTo make all length-k segments of `nums` XOR to 0, it follows that every `nums[0:k], nums[k:2k], ...` are all the same. We then need to decide the numbers in `nums[0:k]`. It\'s straightforward to count the frequencies at each column of the segment (i.e., `col i` for `i \u2208 [0, k-1]`) and change as few elements as possible based on this.\n\nDuring the weekly contest, I tried a more naive non-DP approach but got TLE. How to use DP in this problem? -- That\'s the part I didn\'t immediately understand after digesting other fellows\' posts.\n\n<br/>\n\nLet `dp[i][x]` mean the minimum number of needed changes to have the segment `col[i] XOR col[i+1] XOR ... XOR col[k-1] = x`, where `i \u2208 [0, k-1]`. Therefore, eventually what we need is `dp[0][0]`.\n\nInductively,\n```\ndp[i][x] = min_{v} (dp[i+1][x XOR v] + cost of changing all col i elements to v).\n```\nTo decide the value `?` to look up for level `i+1`, observe that `?` XOR `v` equals the target value `x` to update. Hence,\n```\n? XOR v = x \u21D2\n? XOR v XOR v = x XOR v \u21D2\n? = x XOR v\n```\nSo what is the range of `v`? The problem constraint says each number in `nums \u2208 [0, 1024)`. `v` also belongs to this range because we only need values up to this range to make `XOR(v, v)` outputs 0.\n\nIn the base case, `dp[k-1][x]` means changing the last (`k-1`) column to all have value `x`. There is no XOR here, so `dp[k-1][x]` is essentially counting how many elements are not yet `x`.\n\nWith above being said, we could write something like:\n```\n# initialize dp\ndp = [[float(\'inf\')] * 1024 for _ in range(k)]\nfor x in range(1024):\n\tdp[-1][x] = num_cnts[-1] - counters[-1][x]\n\n# update dp[i][x] iteratively\nfor i in range(k-2, -1, -1):\n\tfor x in range(1024):\n\t\tbest_res = float(\'inf\')\n\t\tfor v in range(1024):\n\t\t\ttmp = num_cnts[i] - counters[i][v] + dp[i+1][x ^ v]\n\t\t\tbest_res = min(best_res, tmp)\n\t\tdp[i][x] = best_res\n```\nIn the inner-most loop, here `v` is the value all column i values change to. `tmp` first checks how many elements in column `i` need to change and then query level `i+1` as discussed earlier.\n\nHowever, this will still TLE, as the inner loops are taking too long. To further improve, observe that in the line\n```\ntmp = num_cnts[i] - counters[i][v] + dp[i+1][x ^ v]\n```\nif `counters[i][v] == 0`, the loop is essentially picking the minimum of `dp[i+1]`, we can move that to outer loop and enumerate the inner-most loop on those occurrences of `counters[i]` only. Now, it will successfully pass all test cases.\n\nFull code pasted below:\n```\ndef minChanges(self, nums: List[int], k: int) -> int:\n\t# count frequencies on each segment column\n\tcounters = [Counter() for _ in range(k)]\n\tfor i, v in enumerate(nums):\n\t\tcounters[i % k][v] += 1\n\n\t# use dp to compute minimum changes\n\tnum_cnts = [sum(cnt.values()) for cnt in counters]\n\tdp = [[float(\'inf\')] * 1024 for _ in range(k)]\n\tfor x in range(1024):\n\t\tdp[-1][x] = num_cnts[-1] - counters[-1][x] # base case\n\n\tfor i in range(k-2, -1, -1):\n\t\t# assuming counters[i][v] == 0, change all column i to a new value\n\t\tchange_all_cost = num_cnts[i] + min(dp[i+1])\n\t\tfor x in range(1024):\n\t\t\tbest_res = change_all_cost\n\t\t\tfor v in counters[i].keys():\n\t\t\t\ttmp = num_cnts[i] - counters[i][v] + dp[i+1][x ^ v]\n\t\t\t\tbest_res = min(best_res, tmp)\n\t\t\tdp[i][x] = best_res\n\treturn dp[0][0]\n```\n
93,046
Make the XOR of All Segments Equal to Zero
make-the-xor-of-all-segments-equal-to-zero
You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.
Array,Dynamic Programming,Bit Manipulation
Hard
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
1,685
14
## Insight:\n`XOR[1, k] == XOR[2, k+1] == 0` means `nums[1] == nums[k+1]`\n\nHence for any `i`, we have `nums[i] == nums[k+i] == nums[2*k+i] ...`.\n\nThe final list should be repeating of a list of length `k`.\n\n## Solution:\nFor every `nums[i]`, put it in `group[i % k]`. And we need to choose k numbers, one from each group.\n\n* Case 1: one of these `k` numbers are not from `nums`. \n \n This is easy.\n\n* Case 2: all `k` numbers are from `nums`\n\n During looping `i` through `0~k-1` (choosing the `i`th number), we maintain a dict `d` where `d[j]` is the maximal total count of chosen numbers in `nums` while `XOR[1, i] == j`.\n\tThen the final minimum number of elements to change is `n - d[0]` in this case.\n\n### Time complexity:\nTime complexity of case 1 is `O(k)`.\n\nIn case 2, if only looking at the nested loops, you might think there could be more than `44^44 \u2248 2e72 (2000^0.5 \u2248 44.7)` items in `d`.\nBut since the result of XOR cannot have more bits set than its operands and any `nums[i]` are limited to 10 bits, so items in `d` won\'t be more than `2^10`. (Thanks to @yaroslav-repeta pointing out my mistake.)\n\nSo the time complexity of case 2 is `O(k * n/k * 2^10) = O(n)`.\n\nIn total, the time complexity is `O(n)`.\n\n### Python code:\n```py\ndef minChanges(self, A: List[int], k: int) -> int:\n n = len(A)\n cnts = [collections.Counter(A[j] for j in range(i, n, k)) for i in range(k)]\n \n # case 1: one number is not from list\n mxs = [cnts[i].most_common(1)[0][1] for i in range(k)]\n ans = n - (sum(mxs) - min(mxs))\n \n # case 2: all k numbers are from list\n d = cnts[0]\n for i in range(1, k):\n d2 = collections.defaultdict(int)\n for x in d:\n for y in cnts[i]:\n t = x^y\n d2[t] = max(d2[t], d[x] + cnts[i][y])\n d = d2\n \n return min(ans, n - d[0])\n```\n\n### C++ code:\n```\nint minChanges(vector<int>& nums, int k) {\n\tint n = nums.size();\n\tvector<unordered_map<int, int>> cnts(k);\n\tfor (int i=0; i<n; ++i)\n\t\t++cnts[i%k][nums[i]];\n\n\t// case 1: one number is not from list\n\tvector<int> mxs;\n\tint tot_mx = 0, mn = INT_MAX;\n\tauto comp = [](auto x, auto y) { return x.second < y.second; };\n\tfor (int i=0; i<k; ++i) {\n\t\tint mx = max_element(begin(cnts[i]), end(cnts[i]), comp)->second;\n\t\ttot_mx += mx;\n\t\tmn = min(mn, mx);\n\t}\n\tint case1 = n - (tot_mx - mn);\n\n\t// case 2: all k numbers are from list\n\tunordered_map<int, int> dp{{0, 0}}, dp2;\n\tfor (int i=0; i<k; ++i) {\n\t\tdp2.clear();\n\t\tfor (auto &x : dp)\n\t\t\tfor (auto &y : cnts[i]) {\n\t\t\t\tint t = x.first ^ y.first;\n\t\t\t\tdp2[t] = max(dp2[t], x.second + y.second);\n\t\t\t}\n\t\tdp.swap(dp2);\n\t}\n\n\treturn min(case1, n - dp[0]);\n}\n```
93,048
Make the XOR of All Segments Equal to Zero
make-the-xor-of-all-segments-equal-to-zero
You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.
Array,Dynamic Programming,Bit Manipulation
Hard
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
453
6
The property for this question has been well explained in other posts.\nHere I just want to discuss an approach other than DP.\n\nThe basic idea is to generate a counter of numbers for each position in [0 ... k-1].\nThen we enumerate the possible combinations for first k-2 positions.\nFor each combinition, we can get the XOR of all its numbers, and check the count of that XOR in column k-1.\nThen we can compute the total count of numbers that won\'t change.\nFrom all the possible combinations, we find the largest one.\n\nIt is very time comsuming to check every combinition.\nHowever, we can easily prune the solutions that are unable to beat the current best one.\nInitially, we can get a very good solution with the numbers that have the largest count in the first k-2 columns.\n\n```\ndef minChanges(self, nums: List[int], k: int) -> int:\n\t# special cases when k < 3\n\tif k == 1: return sum([1 for x in nums if x])\n\tif k == 2: return len(nums) - Counter(nums).most_common(1)[0][1]\n\n\t# get the Counter for each position in [0 ... k-1]\n\t# sort it based on the length so that we can reduce the combinitions since the order doesn\'t matter\n\tcntr = sorted([Counter(nums[i::k]) for i in range(k)], key=lambda x: len(x))\n\n\t# cache the accumulated largest possible count for the rest of the columns\n\tacc = list(accumulate([c.most_common(1)[0][1] for c in reversed(cntr)]))[::-1]\n\n\tself._max = 0\n\t# pos: position in [0:k]; val: previous XOR; tt: previous total counts\n\tdef countXOR(pos=0, val=0, tt=0):\n\t\tif pos == k-1:\n\t\t\tself._max = max(self._max, cntr[pos][val] + tt)\n\t\telse:\n\t\t\tfor c, w in cntr[pos].items():\n\t\t\t\tif tt+w + acc[pos+1] > self._max:\n\t\t\t\t\tcountXOR(pos+1, val^c, tt+w)\n\n\tcountXOR()\n\treturn len(nums) - self._max\n```\n\nAny suggestions?
93,050
Make the XOR of All Segments Equal to Zero
make-the-xor-of-all-segments-equal-to-zero
You are given an array nums​​​ and an integer k​​​​​. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]. Return the minimum number of elements to change in the array such that the XOR of all segments of size k​​​​​​ is equal to zero.
Array,Dynamic Programming,Bit Manipulation
Hard
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
517
5
The question is easier than you think, but you have to know some properties of XOR. One thing we see from the examples given is that the resulting array after we make changes is periodic of period k (for every i, A[i] == A[i+k] == A[i+2k]==...). In fact, once we choose the first k elements, there is only one way to fill the rest of the array. \n\n* If A[0] XOR A[1] XOR ... XOR A[k-1] == 0 and \n* A[1] XOR ... XOR A[k-1] XOR A[k] == 0, then \n* A[0] XOR A[k] == 0, so \n* A[0] == A[k].\n\nWe can rephrase the problem as: given an array A and integer k, find a sequence of k numbers (a_0,a_1,...a_(k-1) ) in the range 0 <= a_i < 2^10 that XOR to zero, and that minimize the cost of changing the array A to be the repeating sequence (a_0,a_1,...a_(k-1) , a_0,a_1,...a_(k-1) , ...). \n\nThis lets us phrase the problem in terms of DP:\nDP[i][bits] = minimum cost to change our original array to match the last k-i indices of a pattern (a_i, a_(i+1),...,a_{k-1)) such that the current XOR of (a_i, a_(i+1),...,a_{k-1)) is equal to \'bits\'. Then our final answer is DP[0][0]. \n\nFor i < k-1, DP[i][bits] is the minimum over (0<= currX < 2^10) of DP[i+1][bits^currX] + (cost to change all elements of nums[i::k] to currX)\n\n So we need to do two things: \n1. Get counts of every number in the original array, taking steps of size k, using collections.Counter(nums[j::k]). \n2. Iterate over i from k-1 downto 0 to calculate newDP[currX] == DP[i][currX] using the above formula, and the standard DP trick of only saving the last 2 rows.\n\nThe DP array is initialized at every iteration i to be the minimum of our old DP array, plus the cost of replacing all elements in our congruence class nums[i::k]. Runtime: O(1024* 1024 * k + n) == O(k+n)\n\n```python\ndef minChanges(self, nums: List[int], k: int) -> int:\n\tmaxNum = 1<<10\n\n\tn = len(nums)\n\ttots = [(n-j+k-1)//k for j in range(k)] # Same as len(nums[j::k]) for j in range(k)\n\tcounts = [Counter(nums[j::k]).most_common() for j in range(k)]\n\n\tlast = counts[-1]\n\ttLast = tots[-1]\n\tdp = [tLast] * maxNum # Initialize final row\n\tfor j,v in last:\n\t\tdp[j] -= v\n\n\tfor itNum in range(k-2,-1,-1):\n\t\ttHere = tots[itNum]\n\t\tminCost = min(dp)\n\t\tnewDP = [minCost + tHere]*maxNum\n\n\t\tfor j,v in counts[itNum]:\n\t\t\tnewAdd = tHere-v\n\t\t\tfor currX in range(maxNum):\n\t\t\t\tnewDP[currX] = min(newDP[currX], newAdd + dp[j^currX])\n\t\tdp = newDP[:]\n\treturn dp[0]\n```
93,051
Check if One String Swap Can Make Strings Equal
check-if-one-string-swap-can-make-strings-equal
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
Hash Table,String,Counting
Easy
The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters.
9,138
80
\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff = [[x, y] for x, y in zip(s1, s2) if x != y]\n return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]\n```
93,108
Check if One String Swap Can Make Strings Equal
check-if-one-string-swap-can-make-strings-equal
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
Hash Table,String,Counting
Easy
The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters.
4,263
39
```\ndef areAlmostEqual(self, s1: str, s2: str) -> bool:\n if s1 == s2:\n return True # if strings are equal then swaping is not required\n if sorted(s1) != sorted(s2):\n return False # if sorted s1 and s2 are not equal then swaping will not make strings equal\n \n count = 0\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n count +=1 \n if count != 2: # the count should be 2, then only we can do at most one string swap\n return False\n \n return True\n```
93,110
Check if One String Swap Can Make Strings Equal
check-if-one-string-swap-can-make-strings-equal
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
Hash Table,String,Counting
Easy
The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters.
1,186
12
```\nclass Solution(object):\n def areAlmostEqual(self, s1, s2):\n """\n :type s1: str\n :type s2: str\n :rtype: bool\n """\n count=0\n for i in range(len(s1)):\n if s1[i]!=s2[i]:\n count+=1\n if (count==2 or count==0) and sorted(s1)==sorted(s2):\n return True\n return False
93,115
Check if One String Swap Can Make Strings Equal
check-if-one-string-swap-can-make-strings-equal
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.
Hash Table,String,Counting
Easy
The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters.
1,596
14
This solution just chooses one string (the first one) and then counts how many "bad" characters exist. A "bad" character is a character that doesn\'t match it\'s corresponding character in the second string. If there are more than 2 bad indices, one swap is not enough to make them equal. (In fact, if there are any odd number of bad indices, no swaps can make the two strings equal). We only care about the case where we have 2 bad indices. We can then make an array of the characters in the string to then swap the two bad ones, and finally re-create the string to then compare it to our goal string.\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n bad = [] # list of bad indices\n if s1 == s2 : return True\n \n for i in range(len(s1)):\n if s1[i] != s2[i]:\n bad.append(i)\n \n if not (len(bad) == 2): return False \n \n s1 = list(s1)\n s1[bad[0]], s1[bad[1]] = s1[bad[1]], s1[bad[0]]\n res = ""\n \n for char in s1:\n res += char\n \n return (res == s2)\n```
93,116
Find Center of Star Graph
find-center-of-star-graph
There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.
Graph
Easy
The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center.
1,475
17
\n\n# 1. Awesome Logic----->One Line Code\n```\nclass Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n return list(set(edges[0]) & set(edges[1]))[0]\n\n #please upvote me it would encourage me alot\n\n```\n# 2. Check first value and Second Value\n```\nclass Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n first=edges[0][0]\n second=edges[0][1]\n if edges[1][0]==first or edges[1][1]==first:\n return first\n return second\n #please upvote me it would encourage me alot\n\n\n```\n# please upvote me it would encourage me alot\n
93,152
Find Center of Star Graph
find-center-of-star-graph
There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.
Graph
Easy
The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center.
1,874
10
```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1]:\n return edges[0][0]\n return edges[0][1]\n```\nReducing it to one liner......\n```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n return edges[0][1] if edges[0][1]==edges[1][0] or edges[0][1]==edges[1][1] else edges[0][0]
93,153
Find Center of Star Graph
find-center-of-star-graph
There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.
Graph
Easy
The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center.
4,212
21
C++:\n\n int findCenter(vector<vector<int>>& edges) {\n int x = edges[0][0], y = edges[0][1];\n return (y == edges[1][0] || y == edges[1][1]) ? y : x;\n }\nJava:\n\n public int findCenter(int[][] edges) {\n int x = edges[0][0], y = edges[0][1];\n return (y == edges[1][0] || y == edges[1][1]) ? y : x;\n }\n\nPython:\n\n\tdef findCenter(self, edges: List[List[int]]) -> int:\n x,y = edges[0][0], edges[0][1]\n if x==edges[1][0] or x == edges[1][1]:\n return x\n return y\n
93,182
Find Center of Star Graph
find-center-of-star-graph
There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node. You are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.
Graph
Easy
The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center.
3,669
19
```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn (set(e[0]) & set(e[1])).pop()\n```\n\t\t\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\tif e[0][0]==e[1][0] or e[0][0]==e[1][1]:\n\t\treturn e[0][0]\n\treturn e[0][1]\n```\n\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn e[0][e[0][1] in e[1]]\n```
93,187
Maximum Average Pass Ratio
maximum-average-pass-ratio
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam. You are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes. The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes. Return the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.
Array,Greedy,Heap (Priority Queue)
Medium
Pay attention to how much the pass ratio changes when you add a student to the class. If you keep adding students, what happens to the change in pass ratio? The more students you add to a class, the smaller the change in pass ratio becomes. Since the change in the pass ratio is always decreasing with the more students you add, then the very first student you add to each class is the one that makes the biggest change in the pass ratio. Because each class's pass ratio is weighted equally, it's always optimal to put the student in the class that makes the biggest change among all the other classes. Keep a max heap of the current class sizes and order them by the change in pass ratio. For each extra student, take the top of the heap, update the class size, and put it back in the heap.
1,436
16
**Key Idea:** We need to keep assigning the remaining extra students to the class which can experience the greatest impact. \n\nLet see an example below, if we have following clasess - [[2,4], [3,9], [4,5], [2,10]], then the impact of assignment students to each class can be defined as,\n\n```\n# In simple terms it can be understood as follows,\n\ncurrentRatio = passCount/totalCount\nexpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\nimpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\nOR\n\n# Formula to calculate impact of assigning a student to a class\nimpacts[i] = (classes[i][0]+1) / (classes[i][1]+1) - classes[i][0]/classes[i][1]\ni.e.\nimpacts[0] -> (4+1)/(2+1)-4/2 \nimpacts[1] -> (3+1)/(9+1)-3/9 \n.\n.\netc.\n```\n\nAnd, once we assign a student to a class, then we need the class with "next" greatest impact. We know that heap is perfect candidate for scenarios in which you need to pick the least/greatest of all the collections at any point of time.\n\nHence, we can leverage that to fetch the greatest impacts in all the cases. \n\n**Note:** in below code we have negated (observe `-` sign ), because by default python heaps are min heaps. Hence, it\'s sort of a workaround to make our logic work :)\n\n```\nclass Solution:\n\tdef maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:\n\t\t\n\t\tn = len(classes)\n\t\t\n\t\timpacts = [0]*n\n\t\tminRatioIndex = 0\n\t\t\n\t\t# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)\n\t\tfor i in range(n):\n\t\t\tpassCount = classes[i][0]\n\t\t\ttotalCount = classes[i][1]\n\t\t\t\n\t\t\t# calculate the impact for class i\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\timpacts[i] = (-impact, passCount, totalCount) # note the - sign for impact\n\t\t\t\n\t\theapq.heapify(impacts)\n\t\t\n\t\twhile(extraStudents > 0):\n\t\t\t# pick the next class with greatest impact \n\t\t\t_, passCount, totalCount = heapq.heappop(impacts)\n\t\t\t\n\t\t\t# assign a student to the class\n\t\t\tpassCount+=1\n\t\t\ttotalCount+=1\n\t\t\t\n\t\t\t# calculate the updated impact for current class\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\t# insert updated impact back into the heap\n\t\t\theapq.heappush(impacts, (-impact, passCount, totalCount))\n\t\t\textraStudents -= 1\n\t\t\n\t\tresult = 0\n\t\t\t\n\t\t# for all the updated classes calculate the total passRatio \n\t\tfor _, passCount, totalCount in impacts:\n\t\t\tresult += passCount/totalCount\n\t\t\t\n\t\t# return the average pass ratio\n\t\treturn result/n\n```
93,205
Maximum Score of a Good Subarray
maximum-score-of-a-good-subarray
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Hard
Try thinking about the prefix before index k and the suffix after index k as two separate arrays. Using two pointers or binary search, we can find the maximum prefix of each array where the numbers are less than or equal to a certain value
1,812
25
# * *Read article Explaination and codes : \n\n![image]()\n\n![image]()\n\n
93,239
Maximum Score of a Good Subarray
maximum-score-of-a-good-subarray
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Hard
Try thinking about the prefix before index k and the suffix after index k as two separate arrays. Using two pointers or binary search, we can find the maximum prefix of each array where the numbers are less than or equal to a certain value
3,068
38
![Screenshot 2023-10-22 092838.png]()\n\n\n# YouTube Video Explanation:\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: 150 Subscribers*\n*Current Subscribers: 104*\n\n# Intuition:\n\nThe goal is to find a good subarray, which starts at index `k`. A good subarray is one where `k` is positioned in such a way that it optimizes the minimum value of the subarray while maximizing its length.\n\n# Approach:\n\n1. Initialize the result variable `res` and the minimum variable `mini` to the value at index `k`. The idea is to start with `k` as the midpoint of the subarray.\n2. Initialize two pointers, `i` and `j`, both initially set to `k`. These pointers will help expand the subarray.\n3. While one of the pointers (`i` or `j`) is not at the boundary of the array:\n - If `i` is at the left boundary (0), increment `j`.\n - If `j` is at the right boundary (`n - 1`), decrement `i`.\n - If the element at `A[i - 1]` is smaller than the element at `A[j + 1]`, increment `j` to expand the subarray to the right.\n - Otherwise, decrement `i` to expand the subarray to the left.\n4. Update `mini` with the minimum value between `A[i]` and `A[j]`.\n5. Update `res` with the maximum of the current `res` and `mini * (j - i + 1)`. This step is crucial as it calculates the score of the current subarray and keeps track of the maximum score found.\n6. Continue the process until one of the pointers reaches a boundary.\n7. Finally, return `res` as the maximum score of a good subarray.\n\n# Time Complexity:\n\n- Time Complexity: The time complexity of this approach is `O(n)`, where n is the length of the input array A. This is because we traverse the array from left to right just once.\n\n- Space complexity: The space complexity of this approach is `O(1)`, beacuse we use only few variables.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n<iframe src="" frameBorder="0" width="800" height="400"></iframe>\n\n---\n\n![upvote1.jpeg]()\n
93,240
Maximum Score of a Good Subarray
maximum-score-of-a-good-subarray
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Hard
Try thinking about the prefix before index k and the suffix after index k as two separate arrays. Using two pointers or binary search, we can find the maximum prefix of each array where the numbers are less than or equal to a certain value
1,289
29
# Problem Description\n\nGiven an array of integers `nums` and an integer `k`, find the **maximum** score of a **good** subarray. \nA **good** subarray is one that contains the element at index `k` and is defined by the **product** of the **minimum** value within the subarray and its **length**. Where `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)` and `i <= k <= j`.\n\n- Constraints:\n - `1 <= nums.length <= 10e5`\n - `1 <= nums[i] <= 2 * 10e4`\n - `0 <= k < nums.length`\n\n---\n\n\n\n# Intuition\n\nHi there friends,\uD83D\uDE03\n\nLet\'s take a look\uD83D\uDC40 into our today\'s problem.\nIn our today\'s problem we have some **formula** for calculating the score for a subarray and a number `k` that we must include in our subarray.\uD83E\uDD28\nThe formula indicates that the **minimum** element in the subarray should be **multiplied** by its **length**.\n\nThe **first solution** that can pop\uD83C\uDF7F into mind is to calculate the score for all **possible subarrays** and take the maximum score for subarrays that includes `k` in it.\nUnfortunately, It will give **TLE** since it is $O(N^2)$.\uD83D\uDE22\n\nCan we do better?\uD83E\uDD14\nActually, we can !\uD83E\uDD2F\nI will pretend like every time that I didn\'t say the solution in the title.\uD83D\uDE02\n\n- Let\'s revise what we need in our problem:\n - **good** subarray with element `K` in it.\n - **maximum** score for this subarray.\n\nSome people -I was one of them- can think of **fixing** the `K\'th` element and search **around** it for the best subarray but why don\'t we change our **prespective** a little ?\uD83E\uDD14\nInstead of fixing `K\'th` element why don\'t we iterate over the array and **fix** the `i\'th` element as the **minimum** element in its subarray and search if `k` is within this subarray -that the lower element of it is `i\'th` element-.\n\nLet\'s see for the array: (5, 8, 14, 20, 3, 1, 7), k = 2\n\n![image.png]()\nFor element 5 -> `k` is within the subarray.\nscore = 5 * 4 =20\n\n![image.png]()\nFor element 8 -> `k` is within the subarray.\nscore = 8 * 3 = 24\n\n![image.png]()\nFor element 14 -> `k` is within the subarray.\nscore = 14 * 2 = 28\n\n![image.png]()\nFor element 20 -> `k` is **not** within the subarray.\n\n![image.png]()\nFor element 3 -> `k` is within the subarray.\nscore = 3 * 5 = 15\n\n![image.png]()\nFor element 1 -> `k` is within the subarray.\nscore = 1 * 6 = 6\n\n![image.png]()\nFor element 20 -> `k` is **not** within the subarray.\n\nThe **best** score = `28` for subarray `(2, 3)` inclusive.\n\nI think, this approach will succesed but how can we implement it?\nThis is a job for our today\'s hero **Monotonic Stack**.\uD83E\uDDB8\u200D\u2642\uFE0F\n\n**Monotonic Stack** is a great data structure that preserve elements in it **sorted** -increasily or decreasily- so we can use it for each element to know the exact element **lower** than them in certain **range**.\nthen after computing the lower element from **left** and **right** we can iterate over each element and see what is the score for the subarray that this element is the **minimum** element in it.\n\n\nAnd this is the solution for our today\'S problem I hope that you understood it\uD83D\uDE80\uD83D\uDE80\n\n---\n\n\n\n# Approach\n1. **Initialize** two vectors `leftBoundary` and `rightBoundary`, which will store the next **lower** element to the **left** and **right** of each element, respectively.\n2. Create two **stacks**, `leftStack` and `rightStack`, both functioning as **monotonic** stacks.\n3. Begin by calculating the next **lower** element from the **left** side of the array.\n4. iterate through `nums` in **reverse** order:\n - check if `leftStack` is not empty and if the **current** element is **smaller** than the top element in `leftStack`. \n - If true, set the **left** boundary for the elements in `leftStack` to the current element\'s index and remove them from `leftStack` which indicates that the current element is the next lower for the top of the stack. \n - Push the current element onto `leftStack`.\n5. Continue by calculating the next **lower** element from the **right** side of the array. Iterate through `nums` from the **start** to the end and the same conditions.\n6. **Iterate** through `nums` once more. For each element `i`:\n - check if `k` is **within** the subarray that element `i` is the **minimum** element in it.\n - If true, calculate the **score** for this subarray.\n - Update `maxScore`.\n7. Finally, return `maxScore`.\n\n# Complexity\n- **Time complexity:** $O(N)$\nSince we are iterating over the array **three** times each whith cost `N` then total cost is `3 * N` so the total complexity is `O(N)`.\n- **Space complexity:** $O(N)$\nSince we are for each element, we store the next lower element from right and left and we have two stacks each can store at most `N` elements then total cost is `4 * N` so the total complexity is `O(N)`.\n\n\n\n---\n\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maximumScore(vector<int>& nums, int k) {\n int n = nums.size();\n \n vector<int> leftBoundary(n, -1); // Store the next lower element from the left.\n vector<int> rightBoundary(n, n); // Store the next lower element from the right.\n \n stack<int> leftStack; // Monotonic Stack to help calculate left array.\n stack<int> rightStack; // Monotonic Stack to help calculate right array.\n \n // Calculate next lower element from the left.\n for (int i = n - 1; i >= 0; i--) {\n while (!leftStack.empty() && nums[leftStack.top()] > nums[i]) {\n // If the current element is smaller than elements in the stack,\n // set the left boundary for those elements to the current element\'s index.\n leftBoundary[leftStack.top()] = i;\n leftStack.pop();\n }\n leftStack.push(i);\n }\n \n // Calculate next lower element from the right\n for (int i = 0; i < n; i++) {\n while (!rightStack.empty() && nums[rightStack.top()] > nums[i]) {\n // If the current element is smaller than elements in the stack,\n // set the right boundary for those elements to the current element\'s index.\n rightBoundary[rightStack.top()] = i; \n rightStack.pop();\n }\n rightStack.push(i);\n }\n \n int maxScore = 0; // Initialize the maximum score to 0.\n \n // Calculate the maximum score for good subarrays\n for (int i = 0; i < n; i++) {\n if (leftBoundary[i] < k && rightBoundary[i] > k) {\n // Calculate the score for the subarray that contains element \'k\'.\n int subarrayScore = nums[i] * (rightBoundary[i] - leftBoundary[i] - 1);\n maxScore = max(maxScore, subarrayScore); // Update the maximum score.\n }\n }\n \n return maxScore; // Return the maximum score for a good subarray.\n }\n};\n\n```\n```Java []\nclass Solution {\n public int maximumScore(int[] nums, int k) {\n int n = nums.length;\n\n int[] leftBoundary = new int[n]; // Store the next lower element from the left.\n int[] rightBoundary = new int[n]; // Store the next lower element from the right.\n for(int i = 0 ;i < n ; i ++){\n leftBoundary[i] = -1;\n rightBoundary[i] = n ;\n }\n\n Stack<Integer> leftStack = new Stack<>(); // Monotonic Stack to help calculate left array.\n Stack<Integer> rightStack = new Stack<>(); // Monotonic Stack to help calculate right array.\n\n // Calculate next lower element from the left.\n for (int i = n - 1; i >= 0; i--) {\n while (!leftStack.empty() && nums[leftStack.peek()] > nums[i]) {\n // If the current element is smaller than elements in the stack,\n // set the left boundary for those elements to the current element\'s index.\n leftBoundary[leftStack.pop()] = i;\n }\n leftStack.push(i);\n }\n\n // Calculate next lower element from the right\n for (int i = 0; i < n; i++) {\n while (!rightStack.empty() && nums[rightStack.peek()] > nums[i]) {\n // If the current element is smaller than elements in the stack,\n // set the right boundary for those elements to the current element\'s index.\n rightBoundary[rightStack.pop()] = i;\n }\n rightStack.push(i);\n }\n\n int maxScore = 0; // Initialize the maximum score to 0.\n\n // Calculate the maximum score for good subarrays\n for (int i = 0; i < n; i++) {\n if (leftBoundary[i] < k && rightBoundary[i] > k) {\n // Calculate the score for the subarray that contains element \'k\'.\n int subarrayScore = nums[i] * (rightBoundary[i] - leftBoundary[i] - 1);\n maxScore = Math.max(maxScore, subarrayScore); // Update the maximum score.\n }\n }\n\n return maxScore; // Return the maximum score for a good subarray.\n }\n}\n```\n```Python []\nclass Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n n = len(nums)\n\n leftBoundary = [-1] * n # Store the next lower element from the left.\n rightBoundary = [n] * n # Store the next lower element from the right.\n\n leftStack = [] # Monotonic Stack to help calculate left array.\n rightStack = [] # Monotonic Stack to help calculate right array.\n\n # Calculate next lower element from the left.\n for i in range(n - 1, -1, -1):\n while leftStack and nums[leftStack[-1]] > nums[i]:\n # If the current element is smaller than elements in the stack,\n # set the left boundary for those elements to the current element\'s index.\n leftBoundary[leftStack[-1]] = i\n leftStack.pop()\n leftStack.append(i)\n\n # Calculate next lower element from the right.\n for i in range(n):\n while rightStack and nums[rightStack[-1]] > nums[i]:\n # If the current element is smaller than elements in the stack,\n # set the right boundary for those elements to the current element\'s index.\n rightBoundary[rightStack[-1]] = i\n rightStack.pop()\n rightStack.append(i)\n\n maxScore = 0 # Initialize the maximum score to 0.\n\n # Calculate the maximum score for good subarrays.\n for i in range(n):\n if leftBoundary[i] < k and rightBoundary[i] > k:\n # Calculate the score for the subarray that contains element \'k\'.\n subarrayScore = nums[i] * (rightBoundary[i] - leftBoundary[i] - 1)\n maxScore = max(maxScore, subarrayScore) # Update the maximum score.\n\n return maxScore # Return the maximum score for a good subarray.\n```\n\n\n\n![leet_sol.jpg]()\n
93,242
Maximum Score of a Good Subarray
maximum-score-of-a-good-subarray
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Hard
Try thinking about the prefix before index k and the suffix after index k as two separate arrays. Using two pointers or binary search, we can find the maximum prefix of each array where the numbers are less than or equal to a certain value
273
23
# Intuition\nThe description accidentally say an answer. lol\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n`0:05` Easy way to solve a constraint\n`2:04` How we can move i and j pointers\n`3:59` candidates for minimum number and max score\n`4:29` Demonstrate how it works\n`8:25` Coding\n`11:04` 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,778\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nFirst of all, we have two constraints.\n\n---\n\n- min( from nums[i] to nums[j]) * (j - i + 1)\n- i <= k <= j\n\n---\n\nLet\'s focuns on `i <= k <= j`. The problem is it\'s hard to manage 3 indices at the same time.\n\nSo we should change our idea. Simply, since we know that `k` index number,\nI think it\'s good idea to start from `k index`.\n\n`i` index is less than or equal to `k`, so move towards `index 0`. On the other hand, `j` is greater than or equal to `k`, so move towards the last index.\n\n\n---\n\n\u2B50\uFE0F Points\n\nWe should start iterating from `k` index, so that we don\'t have to care about `i <= k <= j` constraint.\n\n---\n\n- How we can move `i` and `j` pointers?\n\nThe next point is "how we can move `i` and `j` pointers". The description says "Return the maximum possible score of a good subarray."\n\nSo, I think we have 3 cases.\n\n\n---\n\n\u2B50\uFE0F Points\n\n1. **not reach end of array at both sides**\n\n In this case, `if nums[i] >= nums[j]`, move `i` with `-1`, if not, move `j` with `+1`, that\'s because we want to get maximum score, so take larger number.\n\n - Why `i` with `-1`, `j` with `+1`?\n\n That\'s because we start from `k` index. Let\'s say k = `2`. As I told you, i move towards `index 0`, so we need to subtract `-1` from `2` to move to `index 1`. `j` is the same reason. we need to add `+1` to move to the last index from `k` index.\n\n2. **reach index `0` first**\n\n In this case, simply move `j` with `+1`\n\n3. **reach the last index first**\n\n In this case, simply move `i` with `-1`\n\n---\n\nVery simple right?\n\n- It\'s time to calculate minimum number and max score\n\nLet\'s calculate minimum number and max score.\n\nRegarding minimum number, we need to compare 3 numbers\n\n---\n\n\u2B50\uFE0F Points\n\ncandidates of minimum number should be\n\n- `current minimum number` (this is initialized with `nums[k]` at first)\n- `nums[i]`\n- `nums[j]`\n\n---\n\nAfter we take current minimum number, it\'s time to calculate max score with the formula.\n\n---\n\n\u2B50\uFE0F Points\n\ncandidates of max score should be\n\n- `current max score`\n- `minimum number * (j - i + 1)`\n\n---\n\nwe compare the two numbers and take a larger number.\n\nwe repeat the same process until `i` reach index `0` and `j` reach the last index.\n\n\n### How it works\n\nLet\'s see how it works with a simple example.\n\n```\nInput: [1,4,3,7], k = 2\n```\n\nWe start from index `k`\n\n```\ni = 2\nj = 2\nminimum = 3 (= nums[k])\nmax score = 3 (= nums[k])\n```\n\n```\nnums[i - 1] = 4\nnums[j + 1] = 7\n\ntake 7, so move j with +1\n\ni = 2\nj = 3\nminimum = 3 (= min(minimum(3), nums[i](3), nums[j](7)))\nmax score = 6 (= max(max_score(3), minimum(3) * (j(3) - i(2) + 1)))\n``` \n\n```\nWe already reached the last index, so move i with -1\n\ni = 1\nj = 3\nminimum = 3 (= min(minimum(3), nums[i](4), nums[j](7)))\nmax score = 9 (= max(max_score(6), minimum(3) * (j(3) - i(1) + 1)))\n``` \n\n```\nWe already reached the last index, so move i with -1\n\ni = 0\nj = 3\nminimum = 1 (= min(minimum(3), nums[i](1), nums[j](7)))\nmax score = 9 (= max(max_score(9), minimum(1) * (j(3) - i(0) + 1)))\n``` \n\n```\nOutput: 9\n```\n\nEasy! Let\'s see a real algorithm!\n\n### Algorithm Overview:\n\nThe algorithm aims to find the maximum score of a good subarray within a given list of numbers, represented by `nums`, with a starting index `k`.\n\n### Detailed Explanation:\n\n1. Initialize necessary variables:\n - Set `minimum` and `max_score` to the value of the element at index `k`. These variables keep track of the minimum element within the subarray and the maximum score found.\n - Initialize `i` and `j` to `k`. These pointers represent the left and right bounds of the subarray under consideration.\n - Determine the length of the input list `n`.\n\n2. Begin a while loop that continues as long as either `i` is greater than 0 or `j` is less than `n - 1`. This loop iteratively expands the subarray and calculates the score.\n\n3. Inside the loop:\n - Check if it\'s possible to expand the subarray towards the left (i > 0) and right (j < n - 1). This is done to ensure we consider the entire list while trying to maximize the score.\n - If both expansions are possible, compare the neighbors at indices `i - 1` and `j + 1`. Expand the subarray towards the side with the larger neighbor. Update `i` or `j` accordingly.\n - If expanding to the left is not possible (i == 0), or expanding to the right is not possible (j == n - 1), expand the subarray in the direction that is feasible.\n\n4. After expanding the subarray, update the `minimum` value by finding the minimum of the following values: `minimum`, `nums[i]`, and `nums[j]`. This keeps track of the minimum element within the current subarray.\n\n5. Calculate the score for the current subarray and update `max_score`. The score is determined by multiplying `minimum` by the width of the subarray, which is `(j - i + 1)`.\n\n6. The loop continues until `i` is not greater than 0 and `j` is not less than `n - 1`. This ensures that the algorithm explores the entire array for maximizing the score.\n\n7. Once the loop ends, return `max_score` as the maximum score of a good subarray.\n\nThe algorithm iterates through the list, expanding the subarray towards the side with the larger neighbor and continuously updating the minimum element and the maximum score. This process is repeated until the subarray cannot be expanded further, ensuring that the maximum score is found.\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\nclass Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n minimum = max_score = nums[k]\n i = j = k\n n = len(nums)\n\n while i > 0 or j < n - 1:\n # Check if we can expand the subarray\n if i > 0 and j < n - 1:\n # Expand the subarray towards the side with the larger neighbor\n if nums[i - 1] >= nums[j + 1]:\n i -= 1\n else:\n j += 1\n elif i == 0 and j < n - 1:\n j += 1\n elif j == n - 1 and i > 0:\n i -= 1\n\n # Update the minimum and the maximum score\n minimum = min(minimum, nums[i], nums[j])\n max_score = max(max_score, minimum * (j - i + 1))\n\n return max_score\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar maximumScore = function(nums, k) {\n let minimum = nums[k];\n let max_score = nums[k];\n let i = k;\n let j = k;\n let n = nums.length;\n\n while (i > 0 || j < n - 1) {\n // Check if we can expand the subarray\n if (i > 0 && j < n - 1) {\n // Expand the subarray towards the side with the larger neighbor\n if (nums[i - 1] >= nums[j + 1]) {\n i--;\n } else {\n j++;\n }\n } else if (i === 0 && j < n - 1) {\n j++;\n } else if (j === n - 1 && i > 0) {\n i--;\n }\n\n // Update the minimum and the maximum score\n minimum = Math.min(minimum, nums[i], nums[j]);\n max_score = Math.max(max_score, minimum * (j - i + 1));\n }\n\n return max_score;\n}\n```\n```java []\nclass Solution {\n public int maximumScore(int[] nums, int k) {\n int minimum = nums[k];\n int max_score = nums[k];\n int i = k;\n int j = k;\n int n = nums.length;\n\n while (i > 0 || j < n - 1) {\n // Check if we can expand the subarray\n if (i > 0 && j < n - 1) {\n // Expand the subarray towards the side with the larger neighbor\n if (nums[i - 1] >= nums[j + 1]) {\n i--;\n } else {\n j++;\n }\n } else if (i == 0 && j < n - 1) {\n j++;\n } else if (j == n - 1 && i > 0) {\n i--;\n }\n\n // Update the minimum and the maximum score\n minimum = Math.min(minimum, Math.min(nums[i], nums[j]));\n max_score = Math.max(max_score, minimum * (j - i + 1));\n }\n\n return max_score; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maximumScore(vector<int>& nums, int k) {\n int minimum = nums[k];\n int max_score = nums[k];\n int i = k;\n int j = k;\n int n = nums.size();\n\n while (i > 0 || j < n - 1) {\n // Check if we can expand the subarray\n if (i > 0 && j < n - 1) {\n // Expand the subarray towards the side with the larger neighbor\n if (nums[i - 1] >= nums[j + 1]) {\n i--;\n } else {\n j++;\n }\n } else if (i == 0 && j < n - 1) {\n j++;\n } else if (j == n - 1 && i > 0) {\n i--;\n }\n\n // Update the minimum and the maximum score\n minimum = min(minimum, min(nums[i], nums[j]));\n max_score = max(max_score, minimum * (j - i + 1));\n }\n\n return max_score; \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### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n`0:05` Easy way to solve a constraint\n`0:03` Example code with Bitwise Operations\n`0:19` Solution with Build-in function\n`1:23` Coding with Build-in function\n`1:50` Time Complexity and Space Complexity with Build-in function\n`2:15` Coding without Build-in function\n`3:08` Time Complexity and Space Complexity without Build-in function\n\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n`0:04` Explain a few basic idea\n`3:21` What data we should put in deque?\n`5:10` Demonstrate how it works\n`13:27` Coding\n`16:03` Time Complexity and Space Complexity\n
93,245
Maximum Score of a Good Subarray
maximum-score-of-a-good-subarray
You are given an array of integers nums (0-indexed) and an integer k. The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j. Return the maximum possible score of a good subarray.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Hard
Try thinking about the prefix before index k and the suffix after index k as two separate arrays. Using two pointers or binary search, we can find the maximum prefix of each array where the numbers are less than or equal to a certain value
12,974
76
# Intuition\nThe core of the problem revolves around identifying a subarray where the outcome of multiplying its length by its minimum element is the largest. A vital insight here is recognizing that the subarray yielding the utmost score will invariably encompass the element at index `k`. This observation drives the solution\'s strategy: initiate from the element at index `k` and consistently widen our window in both left and right directions. Throughout this expansion, we meticulously maintain the minimum element within this evolving window. This enables us to determine the score for every possible window and subsequently amplify it to the maximum.\n\n## Live Coding with Comments\n\n\n# Approach\n1. **Initialization**: \n - We kick off by positioning the `left` and `right` pointers at index `k`. \n - The variable `min_val` is promptly initialized with the element present at index `k`.\n - Simultaneously, `max_score` is set to the value of `min_val`. This essentially represents the score of the subarray `[k, k]`, a window with only one element, the `k`-th element.\n\n2. **Expansion**:\n - During every loop iteration, we\'re faced with a decision: Should we shift the `left` pointer to the left, or should we move the `right` pointer to the right?\n - This decision hinges on two factors: \n 1. Ensuring we haven\'t reached the boundaries of the array.\n 2. Comparing the values adjacent to the current `left` and `right` pointers to decide the more promising direction for expansion.\n\n3. **Score Calculation**:\n - Post each expansion step, we refresh the value of `min_val`. This ensures it always mirrors the smallest element within our current window.\n - Subsequent to this update, we compute the score affiliated with the current window. This is straightforward and is the product of `min_val` and the current window\'s length. If this newly calculated score surpasses our existing `max_score`, we update `max_score`.\n\n4. **Termination**:\n - The expansion loop is designed to persevere until it\'s impossible to further extend the window. This state is reached when the `left` pointer touches the start of the array or the `right` pointer hits the array\'s end.\n\n# Complexity\n- **Time complexity**: $$ O(n) $$ - Each element of the array is visited at most twice: once when expanding to the left and once when expanding to the right.\n- **Space complexity**: $$ O(1) $$ - We only use a constant amount of extra space, irrespective of the input size.\n\n# Code\n``` Python []\nclass Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n left, right = k, k\n min_val = nums[k]\n max_score = min_val\n \n while left > 0 or right < len(nums) - 1:\n if left == 0 or (right < len(nums) - 1 and nums[right + 1] > nums[left - 1]):\n right += 1\n else:\n left -= 1\n min_val = min(min_val, nums[left], nums[right])\n max_score = max(max_score, min_val * (right - left + 1))\n \n return max_score\n```\n``` Rust []\nimpl Solution {\n pub fn maximum_score(nums: Vec<i32>, k: i32) -> i32 {\n let mut left = k as usize;\n let mut right = k as usize;\n let mut min_val = nums[k as usize];\n let mut max_score = min_val;\n\n while left > 0 || right < nums.len() - 1 {\n if left == 0 || (right < nums.len() - 1 && nums[right + 1] > nums[left - 1]) {\n right += 1;\n } else {\n left -= 1;\n }\n min_val = min_val.min(nums[left].min(nums[right]));\n max_score = max_score.max(min_val * (right as i32 - left as i32 + 1));\n }\n \n max_score\n }\n}\n```\n``` Go []\nfunc maximumScore(nums []int, k int) int {\n left, right := k, k\n min_val := nums[k]\n max_score := min_val\n\n for left > 0 || right < len(nums) - 1 {\n if left == 0 || (right < len(nums) - 1 && nums[right+1] > nums[left-1]) {\n right++\n } else {\n left--\n }\n min_val = min(min_val, min(nums[left], nums[right]))\n max_score = max(max_score, min_val * (right - left + 1))\n }\n \n return max_score\n}\n\nfunc min(a, b int) int {\n if a < b {\n return a\n }\n return b\n}\n\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n```\n``` C++ []\nclass Solution {\npublic:\n int maximumScore(std::vector<int>& nums, int k) {\n int left = k, right = k;\n int min_val = nums[k];\n int max_score = min_val;\n\n while (left > 0 || right < nums.size() - 1) {\n if (left == 0 || (right < nums.size() - 1 && nums[right + 1] > nums[left - 1])) {\n right++;\n } else {\n left--;\n }\n min_val = std::min(min_val, std::min(nums[left], nums[right]));\n max_score = std::max(max_score, min_val * (right - left + 1));\n }\n \n return max_score;\n }\n};\n```\n``` Java []\npublic class Solution {\n public int maximumScore(int[] nums, int k) {\n int left = k, right = k;\n int min_val = nums[k];\n int max_score = min_val;\n\n while (left > 0 || right < nums.length - 1) {\n if (left == 0 || (right < nums.length - 1 && nums[right + 1] > nums[left - 1])) {\n right++;\n } else {\n left--;\n }\n min_val = Math.min(min_val, Math.min(nums[left], nums[right]));\n max_score = Math.max(max_score, min_val * (right - left + 1));\n }\n \n return max_score;\n }\n}\n```\n``` C# []\npublic class Solution {\n public int MaximumScore(int[] nums, int k) {\n int left = k, right = k;\n int min_val = nums[k];\n int max_score = min_val;\n\n while (left > 0 || right < nums.Length - 1) {\n if (left == 0 || (right < nums.Length - 1 && nums[right + 1] > nums[left - 1])) {\n right++;\n } else {\n left--;\n }\n min_val = Math.Min(min_val, Math.Min(nums[left], nums[right]));\n max_score = Math.Max(max_score, min_val * (right - left + 1));\n }\n \n return max_score;\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar maximumScore = function(nums, k) {\n let left = k, right = k;\n let min_val = nums[k];\n let max_score = min_val;\n\n while (left > 0 || right < nums.length - 1) {\n if (left == 0 || (right < nums.length - 1 && nums[right + 1] > nums[left - 1])) {\n right++;\n } else {\n left--;\n }\n min_val = Math.min(min_val, Math.min(nums[left], nums[right]));\n max_score = Math.max(max_score, min_val * (right - left + 1));\n }\n \n return max_score;\n }\n```\n``` PHP []\nclass Solution {\n function maximumScore($nums, $k) {\n $left = $k;\n $right = $k;\n $min_val = $nums[$k];\n $max_score = $min_val;\n\n while ($left > 0 || $right < count($nums) - 1) {\n if ($left == 0 || ($right < count($nums) - 1 && $nums[$right + 1] > $nums[$left - 1])) {\n $right++;\n } else {\n $left--;\n }\n $min_val = min($min_val, min($nums[$left], $nums[$right]));\n $max_score = max($max_score, $min_val * ($right - $left + 1));\n }\n \n return $max_score;\n }\n}\n```\n\n# Performance\n| Language | Execution Time (ms) | Memory Usage (MB) |\n|------------|---------------------|-------------------|\n| Java | 8 | 59 |\n| Rust | 16 | 3 |\n| JavaScript | 75 | 53.7 |\n| C++ | 127 | 90.1 |\n| Go | 140 | 8.6 |\n| C# | 238 | 55.3 |\n| PHP | 360 | 30.1 |\n| Python3 | 1011 | 26.6 |\n\n![v5.png]()\n\n\n# Why It Works\nThis strategy thrives due to the inherent constraint that the optimal subarray must include the element at index `k`. By commencing our search from this element and methodically expanding outwards, we ensure every possible subarray containing the element at `k` is evaluated. By perpetually updating `min_val` and recalculating the score after each expansion, we guarantee that the maximum score is captured by the time the algorithm concludes.\n\n# What We Learned\n- The importance of identifying and leveraging the constraints of a problem. In this case, knowing that the subarray must contain the element at index $$ k $$ is crucial for devising the optimal strategy.\n- The two-pointer approach is a versatile technique, especially for problems involving arrays and strings. By moving the pointers based on certain conditions, we can explore the solution space efficiently.\n
93,249
Sentence Similarity III
sentence-similarity-iii
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words consist of only uppercase and lowercase English letters. Two sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = "Hello my name is Jane" and sentence2 = "Hello Jane" can be made equal by inserting "my name is" between "Hello" and "Jane" in sentence2. Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.
Array,Two Pointers,String
Medium
One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.
1,908
37
If the first words match, pop them out\nIf the last words match,pop them out\nIf neither matches, return False\n```\nclass Solution:\n def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:\n s1 = sentence1.split()\n s2 = sentence2.split()\n if(len(s1)>len(s2)): #let s1 be the smaller and s2 be the greater\n s1,s2 = s2,s1\n while(s1): \n if(s2[0]==s1[0]):\n s2.pop(0)\n s1.pop(0)\n elif(s2[-1]==s1[-1]):\n s2.pop()\n s1.pop()\n else:\n return(False) \n return(True)\n```
93,344
Maximum Number of Groups Getting Fresh Donuts
maximum-number-of-groups-getting-fresh-donuts
There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut. When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group. You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.
Array,Dynamic Programming,Bit Manipulation,Memoization,Bitmask
Hard
The maximum number of happy groups is the maximum number of partitions you can split the groups into such that the sum of group sizes in each partition is 0 mod batchSize. At most one partition is allowed to have a different remainder (the first group will get fresh donuts anyway). Suppose you have an array freq of length k where freq[i] = number of groups of size i mod batchSize. How can you utilize this in a dp solution? Make a DP state dp[freq][r] that represents "the maximum number of partitions you can form given the current freq and current remainder r". You can hash the freq array to store it more easily in the dp table. For each i from 0 to batchSize-1, the next DP state is dp[freq`][(r+i)%batchSize] where freq` is freq but with freq[i] decremented by 1. Take the largest of all of the next states and store it in ans. If r == 0, then return ans+1 (because you can form a new partition), otherwise return ans (continuing the current partition).
694
10
**Approach:**\n\nFirstly, notice that the maximum group size is only 30.\nThat\'s just a little bit too large to try all possible combinations of groups (max &approx; 20 elements).\n\nSo let\'s see how we can optimize our approach.\n\nOur goal is to have as many possible groups get served where the first person\nreceives the first donut in a batch. Logically, we can bump any group that is divisible by `batchSize`\nto the front of the line. Every one of these groups will receive <b>one</b> fresh batch.\n\nFollowing the same logic, all pairs of groups that are divisible by `batchSize` should go next.\nThis way every other group receives one fresh batch of donuts.\n\nThese first two steps can be performed greedily since they are fully constrained.\n```html5\ni.e. batchSize = 7\nFor single group there is only one choice, all groups where size % batchSize is zero. \n <b>i.e. 7, 14, 21, ...</b>\nFor pairs of groups the first group <b>must be paired with a group of size batchSize - size</b> \n <b>i.e. 1 must be paired with 6.</b>\n <b>2 must be paired with 5.</b>\n\t\t <b>3 must be paired with 4.</b>\n```\n\nHowever... for groups of size 3 or larger it gets more complicated.\n```html5\ni.e. batchSize = 7\n[2, 2, 3, 6, 6, 6, 6]\nDo we pair 2 with (2, 3) or with (6, 6)? Yes, one of these answers is the wrong choice.\n\n<b>Our decision now will affect the possible group combinations that can be made later on.</b>\nIf we pick [2, 2, 3] then we\'re left with: [6, 6, 6, 6] for 2 points\nBut if we pick [2, 6, 6] then we\'re left with: [2, 6, 6], [3] for 3 points.\n```\n\nAnd here\'s where dynamic programming steps in.\nAfter greedily serving all possible customers in clusters of groups of size 1 or size 2 we will \nhopefully have narrowed down our group list to less than 20 elements.\n\nThe DP solution is to iterate over all customer groups and if the customer group has not been used, \nthen decide whether or not to add them to the current group.\nIf we add them to the group, mark the customer group as used via bitmasking and then update the total group size.\nWhen the total group size is divisible by the batchSize (when `r == 0`) then add one point to the result.\nReturn the option that results in the most points.\n\n<hr>\n\n**Optimizations:**\n\n1. Greedy: All groups that are divisible by batchSize can go first.\n2. Greedy: All pairs of groups that are divisible by batchsize can go next.\n3. All groups &geq; batchSize can be treated as `group % batchSize` without any loss of information.\n4. Pruning: When performing top-down dp, if you\'ve already tried adding a group of size `g` to the current group,\nthen do not consider adding any other groups of size `g` to the current group, the result will be the same.\n\n```python\nclass Solution:\n def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int:\n \n @functools.lru_cache(None)\n def helper(rem, used):\n if used == target:\n return 0\n seen = set()\n best = 0\n for i in range(len(groups)):\n if not (bitmask[i] & used):\n if groups[i] not in seen:\n seen.add(groups[i])\n r = (rem + groups[i]) % batchSize\n best = max(best, helper(r, used | bitmask[i]))\n if r == 0:\n return int(rem == 0) + best\n return int(rem == 0) + best\n \n # 1. Greedily serve all groups that are a multiple of batchSize first.\n new_groups = [g%batchSize for g in groups]\n res = len(groups) - len(new_groups)\n groups = new_groups\n \n # 2. Greedily serve all pairs of groups where group1 + group2 is a multiple of batchsize.\n count = collections.defaultdict(int)\n for g in groups:\n target = batchSize - g\n if count[target]:\n count[target] -= 1\n res += 1\n else:\n count[g] += 1\n \n # 3. Use top-down DP to find the optimal configuration of the remaining groups. \n groups = sum([[i]*count[i] for i in count], [])\n target = (1 << len(groups)) - 1\n bitmask = [1 << i for i in range(len(groups))]\n return res + helper(0, 0)\n```
93,397
Count Nice Pairs in an Array
count-nice-pairs-in-an-array
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
Array,Hash Table,Math,Counting
Medium
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i].
2,812
14
![image.png]()\n\n# Intuition\nThe problem involves counting the number of "nice pairs" in an array, where a "nice pair" is defined as a pair of elements whose difference is equal to the difference between the reverse of the two elements. The intuition is to iterate through the array, calculate the temporary number (the difference between the element and its reverse), and maintain a count of occurrences for each temporary number.\n\n# Approach\n| Index | Element | Reversed | Modified Element |\n|-------|---------|----------|-------------------|\n| 0 | 42 | 24 | 18 |\n| 1 | 11 | 11 | 0 |\n| 2 | 1 | 1 | 0 |\n| 3 | 97 | 79 | 18 |\n- Create a HashMap to store the occurrences of temporary numbers.\n- Iterate through the array, calculate the temporary number for each element, and update the count in the HashMap.\n- Iterate through the counts in the HashMap and calculate the total number of nice pairs using the formula \\(\\frac{n \\cdot (n - 1)}{2}\\), where \\(n\\) is the count of occurrences for each temporary number.\n- Use modular arithmetic to handle large numbers.\n\n# Complexity\n- Time complexity: \\(O(n)\\), where \\(n\\) is the length of the input array. The algorithm iterates through the array once.\n- Space complexity: \\(O(n)\\), where \\(n\\) is the number of unique temporary numbers. The HashMap stores the occurrences of temporary numbers.\n\n# Code\n```java []\nimport java.util.HashMap;\nimport java.util.Collection;\nimport java.util.Map;\n\nclass Solution {\n public int countNicePairs(int[] nums) {\n /// Create a HashMap to store occurrences of temporary numbers\n Map<Integer, Integer> numbers = new HashMap<>();\n\n /// Iterate through the array\n for (int num : nums) {\n /// Calculate the temporary number\n int temporary_number = num - reverse(num);\n\n /// Update the count in the HashMap\n if (numbers.containsKey(temporary_number)) {\n numbers.put(temporary_number, numbers.get(temporary_number) + 1);\n } else {\n numbers.put(temporary_number, 1);\n }\n }\n\n /// Calculate the total number of nice pairs\n long result = 0;\n Collection<Integer> values = numbers.values();\n int mod = 1000000007;\n for (int value : values) {\n result = (result % mod + ((long) value * ((long) value - 1) / 2)) % mod;\n }\n\n // Return the result as an integer\n return (int) result;\n }\n\n /// Helper function to reverse a number\n private int reverse(int number) {\n int reversed_number = 0;\n while (number > 0) {\n reversed_number = reversed_number * 10 + number % 10;\n number /= 10;\n }\n return reversed_number;\n }\n}\n```\n```C# []\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n public int CountNicePairs(int[] nums) {\n Dictionary<int, int> numbers = new Dictionary<int, int>();\n\n foreach (int num in nums) {\n int temporaryNumber = num - Reverse(num);\n\n if (numbers.ContainsKey(temporaryNumber)) {\n numbers[temporaryNumber]++;\n } else {\n numbers[temporaryNumber] = 1;\n }\n }\n\n long result = 0;\n int mod = 1000000007;\n foreach (int value in numbers.Values) {\n result = (result % mod + ((long)value * ((long)value - 1) / 2)) % mod;\n }\n\n return (int)result;\n }\n\n private int Reverse(int number) {\n int reversedNumber = 0;\n while (number > 0) {\n reversedNumber = reversedNumber * 10 + number % 10;\n number /= 10;\n }\n return reversedNumber;\n }\n}\n```\n``` C++ []\n#include <unordered_map>\n#include <vector>\n\nclass Solution {\npublic:\n int countNicePairs(std::vector<int>& nums) {\n std::unordered_map<int, int> numbers;\n\n for (int num : nums) {\n int temporaryNumber = num - reverse(num);\n\n if (numbers.find(temporaryNumber) != numbers.end()) {\n numbers[temporaryNumber]++;\n } else {\n numbers[temporaryNumber] = 1;\n }\n }\n\n long result = 0;\n int mod = 1000000007;\n for (const auto& entry : numbers) {\n result = (result % mod + ((long)entry.second * ((long)entry.second - 1) / 2)) % mod;\n }\n\n return static_cast<int>(result);\n }\n\nprivate:\n int reverse(int number) {\n int reversedNumber = 0;\n while (number > 0) {\n reversedNumber = reversedNumber * 10 + number % 10;\n number /= 10;\n }\n return reversedNumber;\n }\n};\n```\n``` Python []\nclass Solution:\n def countNicePairs(self, nums):\n numbers = {}\n\n for num in nums:\n temporary_number = num - self.reverse(num)\n\n if temporary_number in numbers:\n numbers[temporary_number] += 1\n else:\n numbers[temporary_number] = 1\n\n result = 0\n mod = 1000000007\n for value in numbers.values():\n result = (result % mod + (value * (value - 1) // 2)) % mod\n\n return int(result)\n\n def reverse(self, number):\n reversed_number = 0\n while number > 0:\n reversed_number = reversed_number * 10 + number % 10\n number //= 10\n return reversed_number\n```\n``` Ruby []\nclass Solution\n def count_nice_pairs(nums)\n numbers = {}\n\n nums.each do |num|\n temporary_number = num - reverse(num)\n\n if numbers.key?(temporary_number)\n numbers[temporary_number] += 1\n else\n numbers[temporary_number] = 1\n end\n end\n\n result = 0\n numbers.values.each do |value|\n result = (result % 1_000_000_007 + (value * (value - 1) / 2) % 1_000_000_007) % 1_000_000_007\n end\n\n result.to_i\n end\n\n private\n\n def reverse(number)\n reversed_number = 0\n while number > 0\n reversed_number = reversed_number * 10 + number % 10\n number /= 10\n end\n reversed_number\n end\nend\n```
93,439
Count Nice Pairs in an Array
count-nice-pairs-in-an-array
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
Array,Hash Table,Math,Counting
Medium
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i].
6,749
57
# Intuition\n- We have an array of non-negative integers.\n- We\'re looking for pairs of indices (i, j) where a specific condition is satisfied.\n- The condition involves the sum of a number and its reverse (digits reversed).\n- More precisely, for indices i and j (where i < j):\n- Original condition: $$nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])$$\n- Modified condition: We simplify this by creating a new array, subtracting the reverse from each number, and storing the differences, $$nums[i] - rev(nums[i]) == nums[j] - rev(nums[j])$$.\n- For each number in the original array, we create a new array by subtracting its reverse from itself.\n- To efficiently count pairs, we sort the new array. This helps group numbers with the same differences together.\n- We count how many times each unique difference appears consecutively in the sorted array.\n- This count represents the number of pairs that satisfy the modified condition.\n- We use these counts to calculate the total number of pairs satisfying the modified condition.\n- This involves counting combinations, essentially determining how many ways we can choose pairs from the counted occurrences.\n- Since the result might be a large number, we take the answer modulo $$10^9 + 7$$ to keep it within a reasonable range.\n\n# Approach\n- Define a function reverse to reverse the digits of a non-negative integer.\n- Iterate through the array and subtract the reversed form of each number from the original number, updating the array with the differences.\n- Sort the modified array to group identical differences together.\n- Iterate through the sorted array to count the occurrences of each unique difference.\n- Use the count of occurrences to calculate the number of pairs that meet the condition.\n- Return the result modulo 10^9 + 7.\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n- Space complexity: $$O(n)$$ for the modified array.\n\n\n# Code\n```Python3 []\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n mod = 1000000007\n length = len(nums)\n for i in range(length):\n nums[i] = nums[i] - self.reverse(nums[i])\n nums.sort()\n res = 0\n i = 0\n while i < length - 1:\n count = 1\n while i < length - 1 and nums[i] == nums[i + 1]:\n count += 1\n i += 1\n res = (res % mod + (count * (count - 1)) // 2) % mod\n i += 1\n\n return int(res % mod)\n def reverse(self, num: int) -> int:\n rev = 0\n while num > 0:\n rev = rev * 10 + num % 10\n num //= 10\n return rev\n```\n```Java []\nclass Solution {\n public int countNicePairs(int[] nums) {\n final int mod = 1000000007;\n int len = nums.length;\n for (int i = 0; i < len; i++) {\n nums[i] = nums[i] - reverse(nums[i]);\n }\n Arrays.sort(nums);\n long res = 0;\n for (int i = 0; i < len - 1; i++) {\n long count = 1;\n while (i < len - 1 && nums[i] == nums[i + 1]) {\n count++;\n i++;\n }\n res = (res % mod + (count * (count - 1)) / 2) % mod;\n }\n\n return (int) (res % mod);\n }\n private int reverse(int num) {\n int rev = 0;\n while (num > 0) {\n rev = rev * 10 + num % 10;\n num /= 10;\n }\n return rev;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int countNicePairs(std::vector<int>& nums) {\n const int mod = 1000000007;\n int len = nums.size();\n for (int i = 0; i < len; i++) {\n nums[i] = nums[i] - reverse(nums[i]);\n }\n std::sort(nums.begin(), nums.end());\n long res = 0;\n for (int i = 0; i < len - 1; i++) {\n long count = 1;\n while (i < len - 1 && nums[i] == nums[i + 1]) {\n count++;\n i++;\n }\n res = (res % mod + (count * (count - 1)) / 2) % mod;\n }\n\n return static_cast<int>(res); // Add this line to return the result.\n }\n\nprivate:\n int reverse(int num) {\n int rev = 0;\n while (num > 0) {\n rev = rev * 10 + num % 10;\n num /= 10;\n }\n return rev;\n }\n};\n```\n
93,440
Count Nice Pairs in an Array
count-nice-pairs-in-an-array
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
Array,Hash Table,Math,Counting
Medium
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i].
2,690
21
### Number of pairs:\nThe formula `\uD835\uDC5B(\uD835\uDC5B\u22121)/2`for the number of pairs you can form from an `\uD835\uDC5B` element set has many derivations.\n\nOne is to imagine a room with `\uD835\uDC5B` people, each of whom shakes hands with everyone else. If you focus on just one person you see that he participates in `\uD835\uDC5B\u22121` handshakes. Since there are `\uD835\uDC5B` people, that would lead to `\uD835\uDC5B(\uD835\uDC5B\u22121)` handshakes.\n\nTo finish the problem, we should realize that the total of `\uD835\uDC5B(\uD835\uDC5B\u22121)` counts every handshake `twice`, once for each of the two people involved. So the number of handshakes is `\uD835\uDC5B(\uD835\uDC5B\u22121)/2`.\n\n###### Another way to understand the number of pairs (will be used in the second solution): \n Imagine the people entering the room one at a time and introducing themselves. The first person has nothing to do. The second person shakes one hand. The third person shakes with the two already there, and so on. The last person has `\uD835\uDC5B\u22121` hands to shake. So the total number of handshakes is `0 + 1 + 2 + ... +(\uD835\uDC5B\u22121)`.\n\n### Reverse a number:\nTo reverse a number use this: `int(str(i)[::-1]` => convert int to string, reverse and convert again to int.\n\n### Math:\nA simple math (`just move a number from left to right or right to left side with opposite sign`) and now this problem is equivalent to [1. Two Sum]() problem.\n \n # a + b == c + d ==> a - d == c - b ==> a + b - c - d == 0\n # nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])\n # nums[i] - rev(nums[i]) == nums[j] - rev(nums[j])\n\n\n##### Bonus 2-lines and 1-lines approaches on the other tabs.\n```python3 []\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n nums = [n - int(str(n)[::-1]) for n in nums]\n res = 0\n for n in Counter(nums).values():\n res += n*(n-1)//2 \n return res % (10**9 + 7)\n```\n```python3 []\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n nums = [n - int(str(n)[::-1]) for n in nums]\n return sum(n*(n-1)//2 for v in Counter(nums).values()) % (10**9 + 7)\n```\n```python3 []\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n return sum(v*(v-1)//2 for v in Counter(n - int(str(n)[::-1]) for n in nums).values()) % (10**9 + 7)\n```\nLike a classic 2 Sum problem, but slower than code above.\nNew value `k` is making pairs with all the same values k before `d[k]`. Step by step.\n```python3 []\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n res, d = 0, defaultdict(int)\n for i, n in enumerate(nums):\n k = n - int(str(n)[::-1])\n res += d[k]\n d[k] += 1\n return res % (10**9 + 7)\n```\n![Screenshot 2023-11-21 at 03.33.57.png]()\n\n### Similar problems:\n[2006. Count Number of Pairs With Absolute Difference K]()\n[2176. Count Equal and Divisible Pairs in an Array]()\n[1010. Pairs of Songs With Total Durations Divisible by 60]()\n[1711. Count Good Meals]()\n[1814. Count Nice Pairs in an Array]()\n[2364. Count Number of Bad Pairs]()\n[2342. Max Sum of a Pair With Equal Sum of Digits]()\n[2023. Number of Pairs of Strings With Concatenation Equal to Target]()\n
93,441
Count Nice Pairs in an Array
count-nice-pairs-in-an-array
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
Array,Hash Table,Math,Counting
Medium
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i].
205
6
# Code\n```py\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n ans,mp=0,{}\n for i in nums:\n rev=i-int((str(i)[::-1]))\n if rev not in mp:mp[rev]=1\n else:mp[rev]+=1\n print(mp)\n for i in mp:ans+=((mp[i]*(mp[i]-1)//2))%(10**9+7)\n return ans%(10**9+7)\n```
93,444
Count Nice Pairs in an Array
count-nice-pairs-in-an-array
You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions: Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.
Array,Hash Table,Math,Counting
Medium
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i].
2,099
15
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe given code seems to be solving a problem related to counting "nice pairs" in an array. A "nice pair" is a pair of indices (i, j) where nums[i] - rev(nums[j]) is the same as nums[j] - rev(nums[i]). The approach involves reversing the digits of each number in the array, subtracting the reversed number from the original, and then counting the occurrences of the differences.\n\nReversing Digits: The rev function is used to reverse the digits of a number.\n\nFact Function: The fact function computes the total number of nice pairs based on occurences.\n\nCounting Nice Pairs: The main function countNicePairs subtracts the reversed number from each element in the array, counts the occurrences using a map (mp).\n\n# Complexity\n- Time complexity:\nThe time complexity is O(N) where N is the length of the input array, as each element is processed once.\n\n- Space complexity:\nThe space complexity is O(N) due to the map used to count occurrences.\n\n# Code\n```c++ []\nclass Solution {\npublic:\n int rev(int n)\n {\n int re=0;\n while(n>0)\n {\n re= re*10 + n%10;\n n/=10;\n }\n return re;\n } \n long long fact(int n)\n {\n if(n==1)\n return 1;\n return n + fact(n-1);\n }\n int countNicePairs(vector<int>& nums) {\n long count=0;\n const int mod = 1000000007;\n for(int i=0;i<nums.size();i++)\n {\n nums[i]= nums[i] - rev(nums[i]);\n }\n map<int,int> mp;\n for(auto i: nums)\n {\n mp[i]++;\n }\n for(auto i: mp)\n {\n if(i.second > 1)\n count = (count % mod + fact(i.second-1) ) % mod ;\n }\n return count ;\n }\n};\n```\n```python []\nclass Solution:\n def rev(self, n):\n re = 0\n while n > 0:\n re = re * 10 + n % 10\n n //= 10\n return re\n\n def fact(self, n):\n if n == 1:\n return 1\n return n + self.fact(n - 1)\n\n def countNicePairs(self, nums):\n count = 0\n mod = 1000000007\n\n for i in range(len(nums)):\n nums[i] = nums[i] - self.rev(nums[i])\n\n mp = Counter(nums)\n\n for key, value in mp.items():\n if value > 1:\n count = (count % mod + self.fact(value - 1)) % mod\n\n return int(count)\n```\n```java []\npublic class Solution {\n public int rev(int n) {\n int re = 0;\n while (n > 0) {\n re = re * 10 + n % 10;\n n /= 10;\n }\n return re;\n }\n\n public long fact(int n) {\n if (n == 1)\n return 1;\n return n + fact(n - 1);\n }\n\n public int countNicePairs(int[] nums) {\n long count = 0;\n final int mod = 1000000007;\n\n for (int i = 0; i < nums.length; i++) {\n nums[i] = nums[i] - rev(nums[i]);\n }\n\n Map<Integer, Integer> mp = new HashMap<>();\n for (int i : nums) {\n mp.put(i, mp.getOrDefault(i, 0) + 1);\n }\n\n for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {\n if (entry.getValue() > 1) {\n count = (count % mod + fact(entry.getValue() - 1)) % mod;\n }\n }\n\n return (int) count;\n }\n}\n\n```\n![WhatsApp Image 2023-10-20 at 08.23.29.jpeg]()\n\n
93,450
Maximum Ascending Subarray Sum
maximum-ascending-subarray-sum
Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums. A subarray is defined as a contiguous sequence of numbers in an array. A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.
Array
Easy
It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next
1,077
7
\n```\nclass Solution:\n def maxAscendingSum(self, nums: List[int]) -> int:\n ans = 0\n for i, x in enumerate(nums): \n if not i or nums[i-1] >= nums[i]: val = 0 # reset val \n val += nums[i]\n ans = max(ans, val)\n return ans \n```\n\nEdited on 3/22/2021\nAdding C++ implementation\n```\nclass Solution {\npublic:\n int maxAscendingSum(vector<int>& nums) {\n int ans = 0, val = 0; \n for (int i = 0; i < nums.size(); ++i) {\n if (i == 0 || nums[i-1] >= nums[i]) val = 0; \n val += nums[i]; \n ans = max(ans, val); \n }\n return ans; \n }\n};\n```
93,520
Number of Orders in the Backlog
number-of-orders-in-the-backlog
You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is: Note that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i. There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.
Array,Heap (Priority Queue),Simulation
Medium
Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap.
1,031
6
\n```\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n ans = 0\n buy, sell = [], [] # max-heap & min-heap \n \n for p, q, t in orders: \n ans += q\n if t: # sell order\n while q and buy and -buy[0][0] >= p: # match \n pb, qb = heappop(buy)\n ans -= 2*min(q, qb)\n if q < qb: \n heappush(buy, (pb, qb-q))\n q = 0 \n else: q -= qb \n if q: heappush(sell, (p, q))\n else: # buy order \n while q and sell and sell[0][0] <= p: # match \n ps, qs = heappop(sell)\n ans -= 2*min(q, qs)\n if q < qs: \n heappush(sell, (ps, qs-q))\n q = 0 \n else: q -= qs \n if q: heappush(buy, (-p, q))\n \n return ans % 1_000_000_007\n```\n\nA conciser implementation by @lee215\n```\nclass Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n buy, sell = [], [] # max-heap & min-heap \n for p, q, t in orders: \n if t: heappush(sell, [p, q])\n else: heappush(buy, [-p, q])\n \n while buy and sell and -buy[0][0] >= sell[0][0]: \n qty = min(buy[0][1], sell[0][1])\n buy[0][1] -= qty\n sell[0][1] -= qty\n if not buy[0][1]: heappop(buy)\n if not sell[0][1]: heappop(sell)\n return (sum(q for _, q in sell) + sum(q for _, q in buy)) % 1_000_000_007\n```
93,547
Number of Orders in the Backlog
number-of-orders-in-the-backlog
You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is: Note that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i. There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.
Array,Heap (Priority Queue),Simulation
Medium
Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap.
862
9
Logic is:\n* Since we need to do a lot of **find min/max** operations: use 2 heaps:\n\t* max-heap `b` for buy, min-heap `s` for sell\n\t* So, max buy offer is on top of heap `b`\n\t* Min sell offer is on top of heap `s`\n* Each element of heap is an array: `[price, amount]`\n* *For* each buy/sell order:\n\t* Check for the **good** condition\n\t\t* Good condition is when:\n\t\t\t* Both `b` and `s` are non-empty\n\t\t\t* Top elements satisfy: `s[0][0] <= -b[0][0]` - means `sell price <= buy price`\n\t\t\t* If **good** condition is true: a *sale* will definitely happen\n\t* *While* condition stays **good**, keep performing *sales*\n\t\t* A *sale* means:\n\t\t\t* Pick the top element of both heaps\n\t\t\t* Call their amounts `a1` and `a2`\n\t\t\t* Reduce `a1` and `a2` until one of them becomes `0`\n\t\t\t* If either `a1` or `a2` becomes `0`, pop the heap to which it belongs\n\t\t* Check if the new top of the heap satisfies **good** condition\n* Count the sum of amounts in each heap\n\n```\nclass Solution:\n def getNumberOfBacklogOrders(self, orders):\n b, s = [], []\n heapq.heapify(b)\n heapq.heapify(s)\n \n for p,a,o in orders:\n if o == 0:\n heapq.heappush(b, [-p, a])\n \n elif o == 1:\n heapq.heappush(s, [p, a])\n \n # Check "good" condition\n while s and b and s[0][0] <= -b[0][0]:\n a1, a2 = b[0][1], s[0][1]\n \n if a1 > a2:\n b[0][1] -= a2\n heapq.heappop(s)\n elif a1 < a2:\n s[0][1] -= a1\n heapq.heappop(b)\n else:\n heapq.heappop(b)\n heapq.heappop(s)\n \n count = sum([a for p,a in b]) + sum([a for p,a in s])\n return count % (10**9 + 7)\n ``` \n
93,548
Maximum Value at a Given Index in a Bounded Array
maximum-value-at-a-given-index-in-a-bounded-array
You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions: Return nums[index] of the constructed array. Note that abs(x) equals x if x >= 0, and -x otherwise.
Binary Search,Greedy
Medium
What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is too large to actually generate the array, so you can use the formula 1 + 2 + ... + n = n * (n+1) / 2 to quickly find the sum of nums[0...index] and nums[index...n-1]. Binary search for the target. If it is possible, then move the lower bound up. Otherwise, move the upper bound down.
7,973
11
# !! BIG ANNOUNCEMENT !!\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for the first 10,000 Subscribers. **DON\'T FORGET** to Subscribe.\n\n\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n# Video Solution\n\n# Search \uD83D\uDC49 `Maximum Value at a Given Index in a Bounded Array By Tech Wired` \n\n# or\n\n\n# Click the Link in my Profile\n\nHappy Learning, Cheers Guys \uD83D\uDE0A\n\n\n```Python []\nclass Solution:\n def check(self, a):\n left_offset = max(a - self.index, 0)\n result = (a + left_offset) * (a - left_offset + 1) // 2\n right_offset = max(a - ((self.n - 1) - self.index), 0)\n result += (a + right_offset) * (a - right_offset + 1) // 2\n return result - a\n\n def maxValue(self, n, index, maxSum):\n self.n = n\n self.index = index\n\n maxSum -= n\n left, right = 0, maxSum\n while left < right:\n mid = (left + right + 1) // 2\n if self.check(mid) <= maxSum:\n left = mid\n else:\n right = mid - 1\n result = left + 1\n return result\n```\n```Java []\nclass Solution {\n private long check(long a, int index, int n) {\n long leftOffset = Math.max(a - index, 0);\n long result = (a + leftOffset) * (a - leftOffset + 1) / 2;\n long rightOffset = Math.max(a - ((n - 1) - index), 0);\n result += (a + rightOffset) * (a - rightOffset + 1) / 2;\n return result - a;\n }\n\n public int maxValue(int n, int index, int maxSum) {\n maxSum -= n;\n int left = 0, right = maxSum;\n while (left < right) {\n int mid = (left + right + 1) / 2;\n if (check(mid, index, n) <= maxSum) {\n left = mid;\n } else {\n right = mid - 1;\n }\n }\n return left + 1;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n long long check(long long a, int index, int n) {\n long long leftOffset = std::max(a - static_cast<long long>(index), 0LL);\n long long result = (a + leftOffset) * (a - leftOffset + 1) / 2;\n long long rightOffset = std::max(a - static_cast<long long>((n - 1) - index), 0LL);\n result += (a + rightOffset) * (a - rightOffset + 1) / 2;\n return result - a;\n }\n\n int maxValue(int n, int index, int maxSum) {\n maxSum -= n;\n int left = 0, right = maxSum;\n while (left < right) {\n int mid = (left + right + 1) / 2;\n if (check(mid, index, n) <= maxSum) {\n left = mid;\n } else {\n right = mid - 1;\n }\n }\n return left + 1;\n }\n};\n```\n\n# An Upvote will be encouraging \uD83D\uDC4D\n
93,592
Number of Different Integers in a String
number-of-different-integers-in-a-string
You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123  34 8  34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34". Return the number of different integers after performing the replacement operations on word. Two integers are considered different if their decimal representations without any leading zeros are different.
Hash Table,String
Easy
Try to split the string so that each integer is in a different string. Try to remove each integer's leading zeroes and compare the strings to find how many of them are unique.
1,599
5
# Code \u2705\n```\nclass Solution:\n def numDifferentIntegers(self, word: str) -> int: # // word = "a123bc34d8ef34"\n digit_index = 0\n digit_found = False\n number_list = []\n for i in range(len(word)):\n if word[i].isdigit() and not digit_found: # // condition will be true when i = 1,6,9,12\n digit_index = i \n digit_found = True\n if not word[i].isdigit() and digit_found: # // condition will be true when i = 4,8,10\n number_list.append(int(word[digit_index:i]))\n digit_found = False\n if i == len(word) -1 and digit_found: # // condition will be true when i = 13\n number_list.append(int(word[digit_index:i+1])) # // number_list = [123, 34, 8, 34]\n return len(set(number_list)) # // 3\n```
93,721
Number of Different Integers in a String
number-of-different-integers-in-a-string
You are given a string word that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, "a123bc34d8ef34" will become " 123  34 8  34". Notice that you are left with some integers that are separated by at least one space: "123", "34", "8", and "34". Return the number of different integers after performing the replacement operations on word. Two integers are considered different if their decimal representations without any leading zeros are different.
Hash Table,String
Easy
Try to split the string so that each integer is in a different string. Try to remove each integer's leading zeroes and compare the strings to find how many of them are unique.
1,105
9
We want to return only the part that matches the condition **(\'\\d+)\'** (matches one or more digits), then convert every element to **int** and the length of the **set(nums)** will be the answer.\n```\nclass Solution:\n def numDifferentIntegers(self, word: str) -> int:\n word = re.findall(\'(\\d+)\', word)\n nums = [int(i) for i in word]\n \n return len(set(nums))\n```
93,722
Evaluate the Bracket Pairs of a String
evaluate-the-bracket-pairs-of-a-string
You are given a string s that contains some bracket pairs, with each pair containing a non-empty key. You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei. You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will: Each key will appear at most once in your knowledge. There will not be any nested brackets in s. Return the resulting string after evaluating all of the bracket pairs.
Array,Hash Table,String
Medium
Process pairs from right to left to handle repeats Keep track of the current enclosed string using another string
466
8
```\ndef evaluate(self, s: str, knowledge: List[List[str]]) -> str:\n d = dict()\n for i, j in knowledge:\n d[i]=j\n res, i = \'\', 0\n while i < len(s):\n if s[i] ==\'(\':\n i,t = i+1,i+1\n while s[i]!=\')\':\n i+=1\n if s[t:i] in d:\n res+=d[s[t:i]]\n else:\n res += \'?\'\n else:\n res += s[i]\n i += 1\n return res\n```
93,760
Minimum Number of Operations to Reinitialize a Permutation
minimum-number-of-operations-to-reinitialize-a-permutation
You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​. In one operation, you will create a new array arr, and for each i: You will then assign arr​​​​ to perm. Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.
Array,Math,Simulation
Medium
It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution.
2,772
66
The permutation we\'re given is a bit hard to work with, and we\'re asked to find the order of this permutation:\n\n```\nif i % 2 == 0, then arr[i] = perm[i / 2].\nif i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2] = perm[(n - 1 + i) / 2]\n```\nLet\'s look at an example and see what patterns we can observe when n = 10:\n1. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n2. [0, 5, 1, 6, 2, 7, 3, 8, 4, 9]\n3. [0, 7, 5, 3, 1, 8, 6, 4, 2, 9]\n4. [0, 8, 7, 6, 5, 4, 3, 2, 1, 9]\n5. [0, 4, 8, 3, 7, 2, 6, 1, 5, 9]\n6. [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]\n7. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nOne thing to notice is that the **start and end of the list** never change. Looking at the second to last column shows another pattern: it seems that the values in a column are almost divided by 2 each time: 8 -> 4 -> 2 -> 1, then we get a different value. Let\'s dive in and see if we can solve this.\n\nA very handy property of permutations is that they\'re invertible: we can consider the opposite permutation, since the number of iterations to go from our sorted list is equal in either direction. Let\'s write the formula for the **inverse permutation**:\n\narr_inverse[f(x)] = perm[x]\n```\nif i * 2 <= n-1, then arr_inverse[i] = perm[2 * i]\nif i * 2 > n-1, then arr_inverse[i] = perm[2 * i - (n-1)]\n\nSo arr_inverse[i] = perm[(2 * i) % (n-1)]\n```\n\nSo our permutation really just takes every index to twice that index, modulo n-1. To find the inverse, we just need to **find the smallest power of 2 congruent to 1 modulo n-1**. This can be done in O(n) by brute force, or in O((log n) + O(factoring)) by factoring n-1 and using the Chinese Remainder theorem,\n\nPython Code:\n```python\ndef reinitializePermutation(self, n: int) -> int:\n\tif n == 2:\n\t\treturn 1\n\tmod = n - 1\n\tcurr_power = 2\n\tcnt = 1\n\t# Find multiplicative order modulo n-1\n\twhile curr_power != 1:\n\t\tcurr_power = (2*curr_power) % mod\n\t\tcnt += 1\n\treturn cnt\n```\nIf you have any questions, feel free to ask. If this was helpful, upvotes are appreciated :)\n\n\nEdit: For those who are curious, here\'s the **strictly better than O(n)** solution using prime factorization and Chinese Remainder Theorem. The factoring method here takes O(sqrt(n)) time; it\'s hard to write the actual optimal complexity of integer factoring without using a huge formula, but the runtime is bigger than any polynomial of log n, and smaller than any polynomial of n.\n\nI\'m using some code based on [Rosetta Code](), modified heavily:\n\n```python\ndef reinitializePermutation(self, n: int) -> int:\n\n\tdef lcm(a, b):\n\t\treturn (a * b) // math.gcd(a, b)\n\n\tdef factor(a):\n\t\tsmall_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]\n\t\tfor p in small_primes:\n\t\t\tj = 0\n\t\t\twhile a % p == 0:\n\t\t\t\ta = a // p\n\t\t\t\tj += 1\n\t\t\tif j > 0:\n\t\t\t\tyield p, j\n\t\t\tif a < p * p:\n\t\t\t\tbreak\n\t\tif a > 1:\n\t\t\tyield a, 1\n\n\tdef mult_ordr_helper(a, p, e):\n\t\tm = p ** e\n\t\tt = (p - 1) * (p ** (e - 1)) # = Phi(p**e) where p prime\n\t\tqs = [1, ]\n\t\tfor f in factor(t):\n\t\t\tqs = [q * f[0] ** j for j in range(1 + f[1]) for q in qs]\n\t\tqs.sort()\n\n\t\tfor q in qs:\n\t\t\tif pow(a, q, m) == 1:\n\t\t\t\treturn q\n\t\treturn qs[-1]\n\n\tdef mult_order(a, m):\n\t\tmult_order_for_all_primes = (mult_ordr_helper(a, r[0], r[1]) for r in factor(m))\n\t\treturn functools.reduce(lcm, mult_order_for_all_primes, 1)\n\n\treturn mult_order(2, n - 1)\n```\n
93,790
Minimum Operations to Make the Array Increasing
minimum-operations-to-make-the-array-increasing
You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. Return the minimum number of operations needed to make nums strictly increasing. An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.
Array,Greedy
Easy
nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) .
1,578
12
```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n count = 0\n for i in range(1,len(nums)):\n if nums[i] <= nums[i-1]:\n x = nums[i]\n nums[i] += (nums[i-1] - nums[i]) + 1\n count += nums[i] - x\n return count\n```\n**If you like this solution, please upvote for this**
93,929
Minimum Operations to Make the Array Increasing
minimum-operations-to-make-the-array-increasing
You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. Return the minimum number of operations needed to make nums strictly increasing. An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.
Array,Greedy
Easy
nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) .
1,349
9
**Python :**\n\n```\ndef minOperations(self, nums: List[int]) -> int:\n\tans = 0\n\n\tfor i in range(1, len(nums)):\n\t\tif nums[i] <= nums[i - 1]:\n\t\t\tans += (nums[i - 1] - nums[i] + 1)\n\t\t\tnums[i] = (nums[i - 1] + 1)\n\n\treturn ans\n```\n\n**Like it ? please upvote !**
93,937
Minimum Operations to Make the Array Increasing
minimum-operations-to-make-the-array-increasing
You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. Return the minimum number of operations needed to make nums strictly increasing. An array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.
Array,Greedy
Easy
nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) .
649
6
Modifying mutable input data is bad practice in Python for functions like this, because when using it, the user may not be aware of the changes, and this will lead to subsequent errors.\nWe can solve this problem without modifying a list by using an additional variable (`max_elem`).\n\nAlgo:\n* Initialize variables: `n_operations` with `0` and `max_elem` with `0`.\n* \tIterate over the input array\n\t* \tCompare `cur_elem` with `max_elem`\n\t* \tIf `cur_elem` > `max_elem`:\n\t\t* \tThen we update `max_elem` to the value of `cur_elem`\n\t* If `cur_elem` <= `max_elem`:\n\t\t* Then we **calculate current minimum number of operations** needed for cur_elem to be the maximum of all previous elements (`max_elem - cur_num + 1`)\n\t\t* Add the **current minimum number of operations** to the total (`n_operations`)\n\t\t* And update our current `max_elem` with `max_elem += 1`, because our new maximum is 1 more than the previous one.\n* Return result (`n_operations`) \n\n```Python\ndef minOperations(self, nums: List[int]) -> int:\n n_operations = 0\n max_elem = 0\n \n for cur_num in nums:\n if cur_num <= max_elem:\n n_operations += max_elem - cur_num + 1\n max_elem += 1\n else:\n max_elem = cur_num\n return n_operations\n```\n\n**Complexity:**\n**Time:** Linear `O(n)`\n**Memory:** `O(1)`, we use only constant memory
93,938
Queries on Number of Points Inside a Circle
queries-on-number-of-points-inside-a-circle
You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. Return an array answer, where answer[j] is the answer to the jth query.
Array,Math,Geometry
Medium
For a point to be inside a circle, the euclidean distance between it and the circle's center needs to be less than or equal to the radius. Brute force for each circle and iterate overall points and find those inside it.
994
5
![image.png]()\n\n# Code\n```\nclass Solution(object):\n def countPoints(self, points, queries):\n """\n :type points: List[List[int]]\n :type queries: List[List[int]]\n :rtype: List[int]\n """\n lst=[]\n for i in queries:\n cnt=0\n x1=i[0]\n y1=i[1]\n r=i[2]\n for j in points:\n if sqrt((x1-j[0])**2 + (y1-j[1])**2)<=r:\n cnt+=1\n lst.append(cnt)\n return lst\n```
93,956
Queries on Number of Points Inside a Circle
queries-on-number-of-points-inside-a-circle
You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. Return an array answer, where answer[j] is the answer to the jth query.
Array,Math,Geometry
Medium
For a point to be inside a circle, the euclidean distance between it and the circle's center needs to be less than or equal to the radius. Brute force for each circle and iterate overall points and find those inside it.
5,932
28
```\nclass Solution:\n def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]:\n return [sum(math.sqrt((x0-x1)**2 + (y0-y1)**2) <= r for x1, y1 in points) for x0, y0, r in queries]\n```
93,957
Queries on Number of Points Inside a Circle
queries-on-number-of-points-inside-a-circle
You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. Return an array answer, where answer[j] is the answer to the jth query.
Array,Math,Geometry
Medium
For a point to be inside a circle, the euclidean distance between it and the circle's center needs to be less than or equal to the radius. Brute force for each circle and iterate overall points and find those inside it.
1,132
11
# **MOST UNDERSTANDABLE CODE**\n```\nclass Solution:\n def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]:\n #create a empty list k \n k = []\n #create a variable and initialise it to 0 \n count = 0 \n #iterate over the elements in the queries\n for i in queries:\n #in each sublist 1st element is x co-ordinate\n x1 = i[0]\n #in each sublist 2nd element is y co-ordinate\n y1 = i[1]\n #in each sublist 3rd element is radius\n r = i[2]\n #iterate ovet the lists in points\n for j in points:\n #in each sublist 1st element is x co-ordinate\n x2 = j[0]\n #in each sublist 2nd element is y co-ordinate\n y2 = j[1]\n #if the distance between those two co-ordinates is less than or equal to radius \n if (((x2 - x1)**2 + (y2 - y1)**2)**0.5) <= r :\n #then the point lies inside the cirle or on the circle\n #then count how many points are inside the circle or on the circle by incrementing count variable\n count = count + 1\n \n #after finishing one co-ordinate in points then add the count value in list k \n k.append(count)\n #then rearrange the value of count to 0 before starting next circle \n count = 0 \n #after finishing all circles return the list k \n return k\n```
93,967
Queries on Number of Points Inside a Circle
queries-on-number-of-points-inside-a-circle
You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates. You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj. For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside. Return an array answer, where answer[j] is the answer to the jth query.
Array,Math,Geometry
Medium
For a point to be inside a circle, the euclidean distance between it and the circle's center needs to be less than or equal to the radius. Brute force for each circle and iterate overall points and find those inside it.
2,555
17
```\nclass Solution:\n def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]:\n points = list(map(complex, *zip(*points)))\n\t\tqueries = ((complex(x, y), r) for x, y, r in queries)\n return [sum(abs(p - q) <= r for p in points) for q, r in queries]\n```
93,971
Minimum Number of Operations to Make String Sorted
minimum-number-of-operations-to-make-string-sorted
You are given a string s (0-indexed)​​​​​​. You are asked to perform the following operation on s​​​​​​ until you get a sorted string: Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 109 + 7.
Math,String,Combinatorics
Hard
Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately
1,289
25
[DBabibichev gave an excellent explaination of the approach.]((26n)-math-solution-beats-100-explained) Written independently, this is a shorter and faster version of the same concept. Some notation is borrowed from their solution for consistency. The version takes advantage of the iterative update of the key parameter, and does mod operation only at the end. \n\nAt each letter (starting from the end), we need to calculate the the number of operations to sort the string from this letter onward to the end. This is an iterative process. The aswer is the number operations to sort the tail starting from the next letter position, plus for each smaller letter in the tail of the string that is smaller than the current letter (excluding repetitions), the number of combinations to place the letters in the tail given that the smaller letter is placed at the current position. Let the current letter is *cur_letter.* \n\nLet *tot* be the number of letters starting from the current position onward and *cnt[letter]* is the number of occurences of letter *letter* starting from the current position onward.\n\nIf we put *lower_letter* at the current position, then the number of possible permutations for the tail is (*tot*-1)! *cnt[*lower_letter*] / (*cnt*[*letter 1*]! ... *cnt*[*letter k*]!). This is classical formula for the multinomial distribution. One can see that the expression equals *tot*!/(*cnt*[*letter 1*]! * ... * cnt[*letter k*]!) * *cnt*[*lower_letter*]/*tot*, where the first component is the same for all the smaller letters *lower_letter* and can be iteratively calculated as *comb_tot*=(*comb_tot* * *tot*) / *cnt*[*cur_letter*].\n\nOnce we have *comb_tot*, the number of operations for the current positions (excluding sorting the tail from the next position onward) is *comb_tot* (*cnt*[*lower_letter 1*] + ... + *cnt*[*lower_letter p*]) / *tot*.\n\nMemory: O(26) - letters counter, time: O(26n) -loop over all letters in the string and then over all smaller letters\n\nBeautiful problem with beutiful solution!\n\n# 8-line solution, 320 ms\n```\nclass Solution:\n def makeStringSorted(self, s: str) -> int:\n \n cnt, ans, tot, comb_tot = [0]*26, 0, 0, 1 # cnt - counter of the letters, tot - number of letters onward, comb_tot - see in the explanation \n for cur_letter in s[::-1]: # Loop over all the letters from the end\n num = ord(cur_letter) - ord(\'a\') # Convert letter to number\n cnt[num] += 1 # Increment the counter for the current letter\n tot += 1 # Increment the number of letters from the current one onward\n comb_tot = (comb_tot * tot) // cnt[num] # Iteratively update comb_tot\n ans = ans + (comb_tot * sum(cnt[:num]))//tot # Add the number of combinations for all letters that are smaller than the current one\n return ans % 1_000_000_007\n```\n\n# 90 ms solution\n[kcsquared]() further improved the solution by pre-processing division and using *mod* on *comb_tot* - see their comment in the section below. I am still trying to figure how this improvement works, will provide details later.\n\n```\nclass Solution:\n def makeStringSorted(self, s: str) -> int:\n MOD = 10 ** 9 + 7\n inverses = [1] * (len(s) + 1)\n for a in range(2, len(s) + 1):\n inverses[a] = MOD - ((MOD // a) * inverses[MOD % a]) % MOD\n\n ans, tot, comb_tot = 0, 0, 1\n cnt = [0] * 26\n for cur in map(ord, reversed(s)):\n num = cur - 97\n cnt[num] += 1\n tot += 1\n comb_tot = (comb_tot * tot * inverses[cnt[num]]) % MOD\n ans += comb_tot * sum(cnt[:num]) * inverses[tot]\n return ans % MOD\n```
94,042
Truncate Sentence
truncate-sentence
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation). You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.
Array,String
Easy
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
882
9
\n# 1 liner\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n return \' \'.join(s.split()[:k])\n```\n\n# Count space and do slicing\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n count=0\n for i,c in enumerate(s):\n if c==\' \':\n count+=1\n if count==k:\n return s[:i]\n return s\n```\n\n# Split the words\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n ans=""\n words=s.split()\n count=0\n for word in words:\n if count==k:\n break\n count+=1\n if count<k:\n ans+=word+" "\n else:\n ans+=word\n return ans\n```
94,166
Finding the Users Active Minutes
finding-the-users-active-minutes
You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei. Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j. Return the array answer as described above.
Array,Hash Table
Medium
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
1,095
9
\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n mp = {}\n for i, t in logs: \n mp.setdefault(i, set()).add(t)\n \n ans = [0]*k\n for v in mp.values(): \n if len(v) <= k: \n ans[len(v)-1] += 1\n return ans \n```
94,205
Finding the Users Active Minutes
finding-the-users-active-minutes
You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei. Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute. The user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it. You are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j. Return the array answer as described above.
Array,Hash Table
Medium
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
587
5
\tdef findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n \n hashmap = {}\n # We will declare an empty dictionary first\n \n for key,value in logs: # now we will loop throught the user id and time of each user in the logs and then append those values in the dictionary\n \n if key in hashmap: # If the key is found in hashmap then append the value\n hashmap[key].append(value)\n else: # Else set the key to that value\n hashmap[key] = [value]\n\t# IF the above loop was to be executed on this example 1:logs = [[0,5],[1,2],[0,2],[0,5],[1,3]] then the output of the above loop will be this -> {0: [5, 2, 5], 1: [2, 3]}\n\n\t# The resulting array will be of the length k hence forming that\n result = [0] * k\n \n # Now we need to find how many user are active for how many minutes\n # In our example we can say that the user 0 is active for 2 minutes (2,5) and user 1 is also active for 2 minutes (2,3)\n # This means that 2 users are active for 2 minutes hence the resulting array will be such [0,2,0,0,0] for the example taken\n \n # To put this into code we just need to remove the duplicate minutes for active user and then take the length of those minutes and subtract 1 from the lenght because in this case the minutes will be 1,2,3,4,5 for the array [0,2,0,0,0]. This means that 2 users are active for 2 mintues. Users are 0 and 1\n for users in hashmap.keys():\n \n result[len(set(hashmap[users])) - 1] += 1\n \n return result\n![image]()\n
94,214
Minimum Absolute Sum Difference
minimum-absolute-sum-difference
You are given two positive integer arrays nums1 and nums2, both of length n. The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference. Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7. |x| is defined as:
Array,Binary Search,Sorting,Ordered Set
Medium
Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal.
1,425
12
![image]()\n\n\tclass Solution:\n\t\tdef minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\tn = len(nums1)\n\t\t\tdiff = []\n\t\t\tsum = 0\n\t\t\tfor i in range(n):\n\t\t\t\ttemp = abs(nums1[i]-nums2[i])\n\t\t\t\tdiff.append(temp)\n\t\t\t\tsum += temp\n\t\t\tnums1.sort()\n\t\t\tbest_diff = []\n\t\t\tfor i in range(n):\n\t\t\t\tidx = bisect.bisect_left(nums1, nums2[i])\n\t\t\t\tif idx != 0 and idx != n:\n\t\t\t\t\tbest_diff.append(\n\t\t\t\t\t\tmin(abs(nums2[i]-nums1[idx]), abs(nums2[i]-nums1[idx-1])))\n\t\t\t\telif idx == 0:\n\t\t\t\t\tbest_diff.append(abs(nums2[i]-nums1[idx]))\n\t\t\t\telse:\n\t\t\t\t\tbest_diff.append(abs(nums2[i]-nums1[idx-1]))\n\t\t\tsaved = 0\n\t\t\tfor i in range(n):\n\t\t\t\tsaved = max(saved, diff[i]-best_diff[i])\n\t\t\treturn (sum-saved) % ((10**9)+(7))\nIf you have any questions, please ask me, and if you like this approach, please **vote it up**!
94,235
Rearrange Products Table
rearrange-products-table
Table: Products Write an SQL query to rearrange the Products table so that each row has (product_id, store, price). If a product is not available in a store, do not include a row with that product_id and store combination in the result table. Return the result table in any order. The query result format is in the following example.
Database
Easy
null
3,257
61
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef rearrange_products_table(products: pd.DataFrame) -> pd.DataFrame:\n return pd.melt(\n products, id_vars=\'product_id\', var_name=\'store\', value_name=\'price\'\n ).dropna()\n```\n```SQL []\nSELECT product_id,\n \'store1\' AS store,\n store1 AS price\n FROM Products\n WHERE store1 IS NOT NULL\n\n UNION\n\n SELECT product_id,\n \'store2\' AS store,\n store2 AS price\n FROM Products\n WHERE store2 IS NOT NULL\n\n UNION\n\n SELECT product_id,\n \'store3\' AS store,\n store3 AS price\n FROM Products\n WHERE store3 IS NOT NULL\n\n ORDER BY product_id, store;\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
94,326
Find the Winner of the Circular Game
find-the-winner-of-the-circular-game
There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: Given the number of friends, n, and an integer k, return the winner of the game.
Array,Math,Recursion,Queue,Simulation
Medium
Simulate the process. Maintain in a circular list the people who are still in the circle and the current person you are standing at. In each turn, count k people and remove the last person from the list.
7,448
71
This is the josephus problem, [wikipedia]()\nThe classic algorithm to this problem is very weird, let me talk with the example1 in "leetcode problem description". \nAt first [aaa,bbb,cac,ddd,eee] is playing this game.\n\n| #alive | aaa | bbb | cac | ddd | eee |\n|-------------|-----|-----|-----|-----|-----|\n| 5 | 1 | 2 | 3 | 4 | 5 |\n| 4 | 4 | (\u2191eliminated) | 1 | 2 | 3 |\n| 3 | 2 | | 3 | (0) | 1 |\n| 2 | | | 1 | | 2 |\n| 1 | | | 1 | | |\n\nEvery different round, we name these people using different number sequences.\nEvery time someone died, the number sequence start again from 1.\nThe table describes how we name these people.\n\nThe winner have a number `1` in the last round. \nYou have to induce his(cac) \'s number in the first round.\nSuppose when there are `i` people alive, cac\'s number is `f(i,\'cac\')`. And when there are `i+1` people alive, cac\'s number is `f(i+1,\'cac\')`.\nThen `f(i+1,\'cac\') == (k + f(i,\'cac\') - 1 )%(i+1) + 1`.\n\n<details><summary> prove </summary><p>\n\n**When there are `i+1` people alive**, person with number *`k % (i+1)`* will be eliminated \n\n**When `i` people alive**, He(\u2191) has a dummy number 0 . So count the next `f(i,\'cac\')` people , ( turn back to round when `i+1` people alive ) number *`(k+f(i,\'cac\')) % (i+1)`* is the value of *`f(i+1, \'cac\')`* . \n\nA good example from this table is when `i==3`. `f(i,\'cac\')` is `3`, \'ddd\' will be eliminated, `f(i+1, \'cac\')` is *`(2+f(i,\'cac\'))%4`*.\n\nNotice, `f(i+1,\'cac\')` can\'t be zero, you need change it to *`(k+f(i,\'cac\')-1)%(i+1)+1`*. ( for example, when `i==2`, the value of *`(k+f(i,\'cac\'))%(i+1)`* maybe `0,1,2`, but indeed, we need `3,1,2`, so additionally map `0` into `3` while remeining other values unchanged. ). \n\nTo avoid this problem, you can make all indices in this problem start from 0, i.e. map all indices from `i` to `i-1`. \n\n---\n</p></details>\n\nThen you can build a relation between each round and finally get the correct answer.\n\nThere is also a `O(klg(n))` hybrid algorithm, I will introduce later.\nThere is also a time `O(lgn)` space `O(1)` formula/algorithm when `k` is `2`, refer to wikipedia.\n## code\n-----\n\ntop-down recursion: time \u0398(n) space \u0398(n)\n```python\nclass Solution:\n def findTheWinner(self, n: int, k: int) -> int:\n if n==1: return 1\n return (k + self.findTheWinner(n-1, k) -1) % n + 1\n```\n\nbottom-up time \u0398(n) space \u0398(1)\n\n```python\ndef findTheWinner(self, n: int, k: int) -> int:\n p = 1\n for i in range(1,n):\n # here i represent number of alive people\n\t\t# p is f(i,\'cac\')\n p=(k+p-1)%(i+1)+1\n\t\t# p is f(i+1, \'cac\')\n return p\n```\n\n## advanced code1\n\n## advanced code2\n-----\n\nlet\'s use `g(n,k)` to represent answer of this problem.\nIn the previous section, we know for any positive n,k, `g(n,k) = (k + g(n-1, k) -1)%n + 1`.\n\nWhen `n >= k and k!=1`, we can eliminate `floor(n/k)` people in a round, and then use new indices.\nFor example, `n=11, k=3`\n\nhere for convenience, index start from 0\n\n|||||||||||foo||\n|---|---|---|---|---|---|---|---|---|---|---|----|\n| y | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |\n| z | 2 | 3 | / | 4 | 5 | / | 6 | 7 | / | 0 | 1 |\n| x | 0 | 1 | / | 2 | 3 | / | 4 | 5 | / | 6 | 7 |\n|y-x| 0 | 0 | | 1 | 1 | | 2 | 2 | | 3 | 3 |\n\nAs table, on the same column, `x,y,z` are different indices on the same person. From row1 to row2, eliminate `floor(n/k)` people, the indices start again on foo.\n \n+ `nextn = n - floor(n/k)`\n+ `x = (z-n%k) mod nextn ` (`x>=0`)\n+ `y = x + floor(x/(k-1))`\n+ so let `z = g(nextn,k)` we can get `g(n,k)` from `y`\n\n```python\ndef findTheWinner(self, n: int, k: int) -> int:\n if n==1: \n return 1\n elif k==1:\n return n\n elif n>=k:\n next_n = n - n//k\n z = self.findTheWinner(next_n, k) - 1\n x = (z-n%k + next_n) % next_n\n return x + x//(k-1) + 1\n else:\n return (k + self.findTheWinner(n-1, k) -1) % n + 1\n```\n\nthe time complexity `O(klg(n))`, space `O(klg(n))`\n\nSolve `T(n) = T(n*k/(k+1)) + O(1) if n>k else T(n)=T(n-1)+1`, \n`(k/(k+1))^(T(n)-k) = k/n` \n> `T(n) = (log(n/k))/(log(k+1)-log(k)) + k`\n>> `1/(log(k+1)-log(k)) \u2248 k + 0.5` ( logarithm base `math.e`)\n>> \n> `T(n) \u2248 klog(n/k) + k`\n\nSo `klg(n)` is an upper bound, also refer to wikipedia.\n\n## similar problems\n-----\n\n+ leetcode #390 (hard on log(n) solution)\n+ leetcode #1900 (super hard on log(n) solution )\n\n## where I learn from \n\n+ , but there are some mistakes.
94,443
Find the Winner of the Circular Game
find-the-winner-of-the-circular-game
There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend. The rules of the game are as follows: Given the number of friends, n, and an integer k, return the winner of the game.
Array,Math,Recursion,Queue,Simulation
Medium
Simulate the process. Maintain in a circular list the people who are still in the circle and the current person you are standing at. In each turn, count k people and remove the last person from the list.
3,046
15
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe solution code is of few lines. You just need to understand the pattern here.\n\n## 1) Iterating over queue (If you know how to can skip this)\nBefore that understand how to iterate over the circular queue.\nSuppose no of students in circular queue are 6 starting from 0 index till 5th index.\nLet\'s say we are at 4th index \n\n![image.png]()\n\nincrementing to the next element is no brainer add just to the index\nNow we are at 5th.\nincrementing from here will reach to 6th index which is out of bound.\nUse modulus for incrementing\n## next_index = (current_index+1) % total_students\n next_index = (5+1) % 6 = 0\nThis will work for index less than 6 \n next_index = (4+1) % 6 = 5\n\n## 2) Understanding the pattern\n\nSuppose there are 7 friends are seating in linear way.\n### n = 7 and k = 4\n\n![image.png]()\n\nstarting from 0th index counting till 4 friend at index 3 will loose.\n\n![image.png]()\n\n> Keep in mind that we are counting in circular way even if they are seating in linear. \n\nThe number of students remain are\nn - 1 = 7 - 1 = 6\n\nStarting from 4 the next friend to loose will be at index 0\n\n![image.png]()\n\n### In linear way\n\n![image.png]()\n\nThere are 6 friends now seating in circular fashion and their indices are\n4 5 6 0 1 2\nSo we need to find out which friend will leave the queue if there are 6 friends and k is 4. (k has not changed.)\n\n![image.png]()\n\nKeep faith in recursion that it will return correct result for n=6 and k=4\n\nbut after the results will be returned we need to find out the relation between our current indices and index returned from the recursion.\n\nObserving first 3 element we can observe that after adding 4 to the indices are n=6 we can get indices of level n=7\n\n![image.png]()\n\nNow to iterate over start index again we will use modulus as it is circular queue.\n\nwe are at level n=7 , k = 4\nthe formula for conversion will be \n#### (findTheWinner(n-1) + k) % n\n\n![image.png]()\n\n\nThus we can retrieve the indices from the n-1 levels.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n\n# Code\n```\nclass Solution:\n def findTheWinner(self, n: int, k: int) -> int:\n return self.helper(n,k)+1\n\n def helper(self, n:int, k:int)-> int:\n if(n==1):\n return 0\n prevWinner = self.helper(n-1, k)\n return (prevWinner + k) % n\n```
94,459
Finding MK Average
finding-mk-average
You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: Implement the MKAverage class:
Design,Queue,Heap (Priority Queue),Ordered Set
Hard
At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements.
4,827
46
\n```\nclass Fenwick: \n\n def __init__(self, n: int):\n self.nums = [0]*(n+1)\n\n def sum(self, k: int) -> int: \n k += 1\n ans = 0\n while k:\n ans += self.nums[k]\n k &= k-1 # unset last set bit \n return ans\n\n def add(self, k: int, x: int) -> None: \n k += 1\n while k < len(self.nums): \n self.nums[k] += x\n k += k & -k \n\n\nclass MKAverage:\n\n def __init__(self, m: int, k: int):\n self.m = m\n self.k = k \n self.data = deque()\n self.value = Fenwick(10**5+1)\n self.index = Fenwick(10**5+1)\n\n def addElement(self, num: int) -> None:\n self.data.append(num)\n self.value.add(num, num)\n self.index.add(num, 1)\n if len(self.data) > self.m: \n num = self.data.popleft()\n self.value.add(num, -num)\n self.index.add(num, -1)\n\n def _getindex(self, k): \n lo, hi = 0, 10**5 + 1\n while lo < hi: \n mid = lo + hi >> 1\n if self.index.sum(mid) < k: lo = mid + 1\n else: hi = mid\n return lo \n \n def calculateMKAverage(self) -> int:\n if len(self.data) < self.m: return -1 \n lo = self._getindex(self.k)\n hi = self._getindex(self.m-self.k)\n ans = self.value.sum(hi) - self.value.sum(lo)\n ans += (self.index.sum(lo) - self.k) * lo\n ans -= (self.index.sum(hi) - (self.m-self.k)) * hi\n return ans // (self.m - 2*self.k)\n \n\n\n# Your MKAverage object will be instantiated and called as such:\n# obj = MKAverage(m, k)\n# obj.addElement(num)\n# param_2 = obj.calculateMKAverage()\n```
94,526
Finding MK Average
finding-mk-average
You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: Implement the MKAverage class:
Design,Queue,Heap (Priority Queue),Ordered Set
Hard
At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements.
2,623
39
python3 doesn\'t have a built-in [order statistic tree]() or even a basic BST and that may be why `sortedcontainers` is one of the few third-party libraries allowed.\n\nAnyway, with a [SortedList]() this solution is conceptually simple. I use both a deque and a SortedList to keep track of the last m numbers, FIFO. It\'s trivial to maintain the total sum of them. To maintain the sum of the smallest/largest k numbers, we examine the index at which the new number will be inserted into the SortedList and the index at which the oldest number will be removed from the SortedList. If the new number to be inserted will become one of the smallest/largest k numbers, we add it to self.first_k/self.last_k and subtract out the current kth smallest/largest number. The operation for removing the oldest number is similar but the reverse. The only gotcha is the off-by-1 error.\n\n```\nfrom sortedcontainers import SortedList\n\nclass MKAverage:\n\n def __init__(self, m: int, k: int):\n self.m, self.k = m, k\n self.deque = collections.deque()\n self.sl = SortedList()\n self.total = self.first_k = self.last_k = 0\n\n def addElement(self, num: int) -> None:\n self.total += num\n self.deque.append(num)\n index = self.sl.bisect_left(num)\n if index < self.k:\n self.first_k += num\n if len(self.sl) >= self.k:\n self.first_k -= self.sl[self.k - 1]\n if index >= len(self.sl) + 1 - self.k:\n self.last_k += num\n if len(self.sl) >= self.k:\n self.last_k -= self.sl[-self.k]\n self.sl.add(num)\n if len(self.deque) > self.m:\n num = self.deque.popleft()\n self.total -= num\n index = self.sl.index(num)\n if index < self.k:\n self.first_k -= num\n self.first_k += self.sl[self.k]\n elif index >= len(self.sl) - self.k:\n self.last_k -= num\n self.last_k += self.sl[-self.k - 1]\n self.sl.remove(num)\n\n def calculateMKAverage(self) -> int:\n if len(self.sl) < self.m:\n return -1\n return (self.total - self.first_k - self.last_k) // (self.m - 2 * self.k)\n```\n\nTime complexity: O(logM) add due to operations on the SortedList (essentially an [order statistic tree]()). O(1) calculate is trivial.\nSpace complexity: O(M) due to the deque and SortedList.
94,530
Finding MK Average
finding-mk-average
You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: Implement the MKAverage class:
Design,Queue,Heap (Priority Queue),Ordered Set
Hard
At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements.
652
10
There is a `sortedcontainers` package for Python ([link]()), which I think is a good alternative for red-black tree or ordered map for python players.\nUsing `SortedList`, it takes `~ O(logn)` time for both remove and insert. (Since `SortedList` is based on list of list, instead of tree structure, the time cost is not exactly `O(logn)`)\n\n```\nfrom sortedcontainers import SortedList\n\nclass MKAverage:\n\n MAX_NUM = 10 ** 5\n def __init__(self, m: int, k: int):\n \n self.m = m\n self.k = k\n \n # sorted list\n self.sl = SortedList([0] * m)\n\t\t# sum of k smallest elements\n self.sum_k = 0\n\t\t# sum of m - k smallest elements\n self.sum_m_k = 0\n \n # queue for the last M elements if the stream\n self.q = deque([0] * m)\n \n def addElement(self, num: int) -> None:\n # Time: O(logm)\n\t\t\n m, k, q, sl = self.m, self.k, self.q, self.sl \n \n # update q\n q.append(num)\n old = q.popleft()\n \n # remove the old num\n r = sl.bisect_right(old)\n\t\t# maintain sum_k\n if r <= k:\n self.sum_k -= old\n self.sum_k += sl[k]\n\t\t# maintain sum_m_k\n if r <= m - k:\n self.sum_m_k -= old\n self.sum_m_k += sl[m-k]\n # remove the old num\n sl.remove(old)\n \n # add the new num\n r = sl.bisect_right(num)\n if r < k:\n self.sum_k -= sl[k-1]\n self.sum_k += num\n if r < m - k:\n self.sum_m_k -= sl[m - k - 1]\n self.sum_m_k += num\n \n sl.add(num)\n \n return\n\n def calculateMKAverage(self) -> int:\n\t\t# Time: O(1)\n if self.sl[0] == 0:\n return -1\n return (self.sum_m_k - self.sum_k) // (self.m - self.k * 2)\n```
94,542
Finding MK Average
finding-mk-average
You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream. The MKAverage can be calculated using these steps: Implement the MKAverage class:
Design,Queue,Heap (Priority Queue),Ordered Set
Hard
At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements.
585
9
So the challenge here is how can we quickly sum the k-largest and k-smallest elements, and I want to talk about how I did that with a binary search tree. The key idea was to store the number of items in each sub-tree, as well as the sum of all the items in each sub tree. By storing the size of each node it becomes possible to determine if the ith smallest node is to the left of the current node, at the current node, or to the right of the current node. This means the ith smallest node can be found in a single trip down the tree. Because the sums are stored, we can also choose to sum elements which are smaller or larger than the target as we go (without having to actually traverse the tree).\n\nThe other aspects of my algorithm are fairly straightforward. I used a deque to store the last m elements in the stream, and an integer to store the sliding window sum for all of the last m elements. This means that to compute the average I have to subtract the sum of the k largest/smallest elements from the sliding window sum, and then divide by the number of elements (which is pre-computed since it\'s a constant). Whenever I add/remove an element to/from the queue I also/remove add it to/from the tree and update the sum, with different cases to handle when the tree is null, when the queue isn\'t full.\n\nBST Height (n is the number of nodes in the tree): \nBest : O(logn)\nAverage : O(logn)\nWorst : O(n)\n\nBST Runtimes (h is the height of the tree):\n\\_\\_init\\_\\_ : O(1)\ninsert/remove : O(h)\nklargets/ksmallest : O(h)\n\nMKAverage Runtimes:\n\\_\\_init\\_\\_ : O(1)\naddElement : O(h)\ncalculateMKAverage : O(h)\n\nBest Performance: 864 ms/49.3 MB : 100%/98%\n\nA more complete version of the binary search tree is below the code for this puzzle.\n\'\'\'\n\n\t#Binary Search Tree\n\tclass Node:\n\t\t#Create a Node\n\t\tdef __init__(self, val:int) -> None:\n\t\t\t"""Create a New Binary Search Tree Node"""\n\t\t\tself.val = val\n\t\t\tself.sum = val\n\t\t\tself.size = 1\n\t\t\tself.count = 1\n\t\t\tself.left = None\n\t\t\tself.right = None\n\t\t\n\t\t#Add a Node to the Tree\n\t\tdef insert(self, val:int) -> None:\n\t\t\t"""Add a Value to the Tree"""\n\t\t\t#Update the Size/Sum\n\t\t\tself.size += 1\n\t\t\tself.sum += val\n\t\t\t\n\t\t\t#Check the Case\n\t\t\tif val < self.val:\n\t\t\t\t#Check the Left Node\n\t\t\t\tif self.left:\n\t\t\t\t\t#Recurse\n\t\t\t\t\tself.left.insert(val)\n\t\t\t\telse:\n\t\t\t\t\t#Make a New Node\n\t\t\t\t\tself.left = Node(val)\n\t\t\telif val > self.val:\n\t\t\t\t#Check the Right Node\n\t\t\t\tif self.right:\n\t\t\t\t\t#Recurse\n\t\t\t\t\tself.right.insert(val)\n\t\t\t\telse:\n\t\t\t\t\t#Make a New Node\n\t\t\t\t\tself.right = Node(val)\n\t\t\telse:\n\t\t\t\t#Increment the Count\n\t\t\t\tself.count += 1\n\n\t\t#Remove a Node from the Tree (Safetys Removed)\n\t\tdef remove(self, val:int) -> None:\n\t\t\t"""Remove a Value From the Tree"""\n\t\t\t#Update the Size/Sum\n\t\t\tself.size -= 1\n\t\t\tself.sum -= val\n\t\t\t\n\t\t\t#Check the Case\n\t\t\tif val < self.val:\n\t\t\t\t#Recurse Left\n\t\t\t\treturn self.left.remove(val)\n\t\t\telif val > self.val:\n\t\t\t\t#Recurse Right\n\t\t\t\treturn self.right.remove(val)\n\t\t\telse:\n\t\t\t\t#Decrement the Count\n\t\t\t\tself.count -= 1\n\n\t\t#Sum the k Smallest Numbers\n\t\tdef ksmallest(self, k:int) -> int:\n\t\t\t"""Efficiently Sum the k Smallest Values in the Tree"""\n\t\t\t#Check the Left Branch\n\t\t\ts = 0\n\t\t\tif self.left:\n\t\t\t\t#Check the Case\n\t\t\t\tif k <= self.left.size:\n\t\t\t\t\t#Recurse Left\n\t\t\t\t\treturn self.left.ksmallest(k)\n\t\t\t\telse:\n\t\t\t\t\t#Update k/s\n\t\t\t\t\tk -= self.left.size\n\t\t\t\t\ts = self.left.sum\n\n\t\t\t#Check the Current Value\n\t\t\tif k <= self.count:\n\t\t\t\treturn s + k*self.val\n\t\t\telif self.right:\n\t\t\t\t#Recurse Right\n\t\t\t\treturn s + self.count*self.val + self.right.ksmallest(k - self.count)\n\t\t\telse:\n\t\t\t\t#Return Search Failure\n\t\t\t\treturn None\n\n\tclass MKAverage:\n\t\tdef __init__(self, m: int, k: int):\n\t\t\tself.k = k\n\t\t\tself.l = m - k\n\t\t\tself.m = m\n\t\t\tself.n = self.m - 2*self.k\n\t\t\tself.window = deque()\n\t\t\tself.tree = None\n\n\t\tdef addElement(self, num: int) -> None:\n\t\t\t#Check the Case\n\t\t\tif len(self.window) == self.m:\n\t\t\t\t#Remove the Previous Number from the Window/Tree\n\t\t\t\tself.tree.remove(self.window.popleft())\n\n\t\t\t\t#Add the New Number to the Window/Tree\n\t\t\t\tself.window.append(num)\n\t\t\t\tself.tree.insert(num)\n\t\t\telif self.window:\n\t\t\t\t#Add the New Number to the Window/Tree\n\t\t\t\tself.window.append(num)\n\t\t\t\tself.tree.insert(num)\n\t\t\telse:\n\t\t\t\t#Make a New Tree\n\t\t\t\tself.window.append(num)\n\t\t\t\tself.tree = Node(num)\n\n\t\tdef calculateMKAverage(self) -> int:\n\t\t\t#Check the Window\n\t\t\tif len(self.window) < self.m:\n\t\t\t\treturn -1\n\t\t\telse:\n\t\t\t\t#Compute Return the Average\n\t\t\t\treturn (self.tree.ksmallest(self.l) - self.tree.ksmallest(self.k))//self.n\n\'\'\'\n\nHere is my binary search tree class as it exists on my computer!\n\n\'\'\'\n\n #Binary Search Tree\n class Node:\n #Create a Node\n def __init__(self, val:int) -> None:\n """Create a New Binary Search Tree Node"""\n self.val = val\n self.sum = val\n self.size = 1\n self.count = 1\n self.left = None\n self.right = None\n \n #Get the Size of the Tree\n def __len__(self) -> int:\n """Return the Number of Items in the Tree"""\n return self.size\n \n #Search for an Item (Index Validity Guaranteed)\n def find(self, i:int):\n """Find and Return the Node at Index i\n \n It also returns an index describing which version of the \n current node was returned.\n \n If i is not a valid index then it returns None (but still \n does a non-trivial amount of work to figure that out, so \n be cautious when using this)\n """\n #Check the Left Branch\n if self.left:\n #Check the Case\n if i < self.left.size:\n #Recurse Left\n return self.left.find(i)\n else:\n #Update i\n i -= self.left.size\n \n #Check the Current Value\n if i < self.count:\n return self, i\n elif self.right:\n #Recurse Right\n return self.right.find(i - self.count)\n else:\n #Return Search Failure\n return None\n \n #Find the ith Smallest Element\n def __getitem__(self, i:int) -> int:\n """Get and Return the Value of the Node at Index i"""\n #Check i\n if i < -self.size or i >= self.size:\n #Index Out of Range\n return None\n elif i >= 0:\n #Find the Index Recursively\n return self.find(i)[0].val\n else:\n #Find the Index Recursively\n return self.find(self.size + i)[0].val\n \n #Count the Number of Occurences of an Item in the Tree\n def Count(self, val:int) -> int:\n #Check the Case\n if val == self.val:\n #Return the Count\n return self.count\n elif val < self.val:\n #Recurse Left\n return self.left.Count(val) if self.left else 0\n else:\n #Recurse Right\n return self.right.Count(val) if self.right else 0\n \n #Check if an Item is in the Tree\n def __contains__(self, val:int) -> bool:\n """Check Whether a Value is in the Tree"""\n return self.Count(val) > 0\n \n #Find the Minimum Item\n def getMin(self) -> int:\n """Returns the Minimum Value in the Tree"""\n return self[0]\n \n #Find the Maximum Item\n def getMax(self) -> int:\n """Returns the Maximum Valud in the Tree"""\n return self[-1]\n \n #Find the Median\n def median(self) -> float:\n """Returns the Median Value in the Tree"""\n #Check the Case\n if self.size%2:\n #The Median is a Single Item\n return self[self.size//2]\n else:\n #Find the Larger Item\n node, i = self.find(self.size//2)\n \n #Check the Case\n if i > 0:\n #The Median is Already Found\n return node.val\n elif node.left and node.left.size:\n #Get the Largest Value from the Left\n return (node.val + node.left[-1])/2\n else:\n #Do a Separate Search\n return (node.val + self[self.size//2 - 1])/2\n \n #Find the Average\n def mean(self) -> float:\n """Returns the Average Value in the Tree"""\n return self.sum/self.size\n \n #Add a Node to the Tree\n def insert(self, val:int) -> None:\n """Add a Value to the Tree"""\n #Check the Case\n self.size += 1\n self.sum += val\n if val < self.val:\n #Check the Left Node\n if self.left:\n #Recurse\n self.left.insert(val)\n else:\n #Make a New Node\n self.left = Node(val)\n elif val > self.val:\n #Check the Right Node\n if self.right:\n #Recurse\n self.right.insert(val)\n else:\n #Make a New Node\n self.right = Node(val)\n else:\n #Increment the Count\n self.count += 1\n \n #Remove a Node from the Tree\n def remove(self, val:int) -> bool:\n """Remove a Value From the Tree"""\n #Check the Case\n if val < self.val:\n #Check the Left Node\n if self.left and self.left.remove(val):\n #Decrement the Sum/Size\n self.sum -= val\n self.size -= 1\n \n #Return Success\n return True\n else:\n #The Node Wasn\'t Found\n return False\n elif val > self.val:\n #Check the Right Node\n if self.right and self.right.remove(val):\n #Decrement the Sum/Size\n self.sum -= val\n self.size -= 1\n \n #Return Success\n return True\n else:\n #The Node Wasn\'t Found\n return False\n else:\n #Check the Count\n if self.count:\n #Decrement the Count, Sum, and Size\n self.count -= 1\n self.sum -= val\n self.size -= 1\n \n #Return Success\n return True\n else:\n #Return Failure\n return False\n \n #Pop an Item at a Specified Index\n def pop(self, i:int) -> int:\n """Remove and Return the Item at Index i"""\n #Check i\n if i < 0 or i >= self.size:\n #Return Search Failure\n return None\n \n #Update the Size\n self.size -= 1\n \n #Check the Left Branch\n if self.left:\n #Check the Case\n if i < self.left.size:\n #Recurse Left\n val = self.left.pop(i)\n \n #Update the Sum\n self.sum -= val\n \n #Return the Value\n return val\n else:\n #Update i\n i -= self.left.size\n \n #Check the Current Value\n if i < self.count:\n #Update the Count/Sum\n self.count -= 1\n self.sum -= self.val\n \n #Return the Value\n return self.val\n else:\n #Recurse Right\n val = self.right.pop(i - self.count)\n \n #Update the Sum\n self.sum -= val\n \n #Return the Value\n return val\n \n #Yield Nodes in Increasing Order\n def increasing(self, unique:bool = False) -> int:\n """Yield the Values of the Tree in Increasing Order"""\n #Check the Left Node\n if self.left:\n #Recurse\n yield from self.left.increasing(unique)\n \n #Yield the Current Node\n if unique:\n yield self.val, self.count\n else:\n yield from (self.val for i in range(self.count))\n \n #Check the Right Node\n if self.right:\n #Recurse\n yield from self.right.increasing(unique)\n \n #Make the Tree Iterable\n def __iter__(self):\n return self.increasing()\n \n #Yield Nodes in Decreasing Order\n def decreasing(self, unique:bool = False) -> int:\n """Yield the Values in the Tree in Decreasing Order"""\n #Check the Right Node\n if self.right:\n #Recurse\n yield from self.right.decreasing(unique)\n \n #Yield the Current Node\n if unique:\n yield self.val, self.count\n else:\n yield from (self.val for i in range(self.count))\n \n #Check the Left Node\n if self.left:\n #Recurse\n yield from self.left.decreasing(unique)\n \n #Sum the k Largest Numbers\n def klargest(self, k:int) -> int:\n """Efficiently Sum the k Largest Values in the Tree"""\n #Check the Right Branch\n s = 0\n if self.right:\n #Check the Case\n if k <= self.right.size:\n #Recurse Left\n return self.right.klargest(k)\n else:\n #Update k/s\n k -= self.right.size\n s = self.right.sum\n \n #Check the Current Value\n if k <= self.count:\n return s + k*self.val\n elif self.left:\n #Recurse Left\n return s + self.count*self.val + self.left.klargest(k - self.count)\n else:\n #Return Search Failure\n return None\n \n #Sum the k Smallest Numbers\n def ksmallest(self, k:int) -> int:\n """Efficiently Sum the k Smallest Values in the Tree"""\n #Check the Left Branch\n s = 0\n if self.left:\n #Check the Case\n if k <= self.left.size:\n #Recurse Left\n return self.left.ksmallest(k)\n else:\n #Update k/s\n k -= self.left.size\n s = self.left.sum\n \n #Check the Current Value\n if k <= self.count:\n return s + k*self.val\n elif self.right:\n #Recurse Right\n return s + self.count*self.val + self.right.ksmallest(k - self.count)\n else:\n #Return Search Failure\n return None\n\'\'\'
94,545
Replace All Digits with Characters
replace-all-digits-with-characters
You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices. There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c. For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]). Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.
String
Easy
We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position
533
5
```\n for i in range(1,len(s),2):\n s = s[:i] + chr(ord(s[i-1])+int(s[i])) + s[i+1:]\n return s\n```
94,590
Replace All Digits with Characters
replace-all-digits-with-characters
You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices. There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c. For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]). Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.
String
Easy
We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position
1,141
9
```\nclass Solution(object):\n def replaceDigits(self, s):\n """\n :type s: str\n :rtype: str\n """\n res = []\n \n for i in range(len(s)):\n if i % 2 == 0:\n res.append(s[i])\n if i % 2 == 1:\n res.append( chr(ord(s[i-1]) + int(s[i])) )\n \n return \'\'.join(res) \n```
94,619
Seat Reservation Manager
seat-reservation-manager
Design a system that manages the reservation state of n seats that are numbered from 1 to n. Implement the SeatManager class:
Design,Heap (Priority Queue)
Medium
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations.
795
23
# Intuition\nUse min heap\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:04` Difficulty of Seat Reservation Manager\n`0:52` Two key points to solve Seat Reservation Manager\n`3:25` Coding\n`5:18` 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,955\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE22)\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nIf we only make reservations, this problem is straightforward. But difficilty is \n\n---\n\n\u25A0 Difficulty\n\nWe have unreserve function. Numbers will have gaps.\n\n---\n\nAccording to the description, the numbers we unreserved are available from small numbers again.\n\nWe have two points to solve this question.\n\n---\n\n\u2B50\uFE0F Points\n\n- How we can manage next number.\n\n- How we can manage unreserved numbers.\n\n---\n\n##### How we can manage next number.\n\nThis is very straightforward. Just use `counter` to count from 1 to `n`. Use simple variable.\n\n##### How we can manage unreserved numbers.\n\nIf we have only one unreserved number, it\'s easy to manage it. But what if we have multiple unreserved numbers. How do you manage them?\n\nIn that case, what data structure do you use?\n\nThinking time...\n\n...\uD83D\uDE29\n...\uD83D\uDE05\n...\uD83D\uDE29\n...\uD83D\uDE0F\n...\uD83D\uDE06\n...\uD83D\uDE04\n\nMy answer is to use `min heap`.\n\n---\n\n\u2B50\uFE0F Points\n\nUse min heap because we can manage unreserved numbers from small to large.\n\n---\n\nBasically, we manage the next number with a simple counter, but sometimes we have unreserved numbers which are smaller then current number from counter.\n\nSo, when we make a reverstaion, compare heap[0] with the next number from counter. If heap[0] is small, just pop the small number from heap.\n\nIf not the case, return the next number from counter.\n\n```\nself.next += 1 \nreturn self.next - 1\n```\n\n- Why `-1`?\n\nThat\'s because we add `+1` to `self.next`(counter) to manage next number(e.g. if current number is `3`, we manage `4` for the next reservation). But we need current next number(`3`), that\'s why we need to subtract `-1`.\n\nI hope you understand main idea now.\nLet\'s see a real algorithm.\n\n\n---\n\n\n**Algorithm Overview:**\n\nThe code defines a `SeatManager` class that manages seat reservations for a venue with `n` seats. The class uses a min-heap (implemented as a list) to keep track of unreserved seats. When a reservation is made, the code assigns the smallest available seat to the customer. When a reservation is canceled, the seat is added back to the min-heap for future use.\n\n**Detailed Explanation:**\n1. **Initialization (`__init__` method):**\n - When an instance of the `SeatManager` class is created, it takes an integer `n` as a parameter, which represents the total number of seats in the venue.\n - `self.next` is initialized to 1, representing the next available seat number.\n - `self.heap` is initialized as an empty list and will be used as a min-heap to store unreserved seat numbers.\n\n2. **Reserving a Seat (`reserve` method):**\n - When a customer wants to reserve a seat, the `reserve` method is called.\n - It first checks if the `heap` is not empty and if the smallest seat number in the `heap` (heap[0]) is less than the `next`. If so, it means there are unreserved seats available, and it\'s time to assign one.\n - If the condition is met, the smallest seat number is removed from the `heap` using `heapq.heappop()`, and that seat number is returned to the customer, indicating a successful reservation.\n - If the condition is not met, the `next` seat number is assigned to the customer, indicating the reservation of the next available seat.\n - In either case, `self.next` is incremented to prepare for the next reservation.\n\n3. **Unreserving a Seat (`unreserve` method):**\n - When a customer decides to unreserve a seat, the `unreserve` method is called with the `seatNumber` as an argument.\n - The `seatNumber` is added back to the `heap` using `heapq.heappush()`. This operation ensures that the unreserved seat is stored in the `heap` and will be allocated to future customers in ascending order.\n\nIn summary, the `SeatManager` class efficiently manages seat reservations and unreservations using a min-heap, ensuring that the smallest available seat is always assigned to customers. This algorithm provides an elegant way to optimize seat allocation in a venue.\n\n\n# Complexity\n- Time complexity:\n`__init__` is $$O(1)$$\n`reserve` is $$O(log n)$$\n`unreserve` is $$O(log n)$$\n\n- Space complexity: $$O(n)$$\n\n\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.next = 1\n self.heap = []\n\n def reserve(self) -> int:\n if self.heap and self.heap[0] < self.next:\n return heapq.heappop(self.heap)\n\n self.next += 1 \n return self.next - 1\n\n def unreserve(self, seatNumber: int) -> None:\n heapq.heappush(self.heap, seatNumber)\n\n```\n```javascript []\nclass SeatManager {\n constructor(n) {\n this.next = 1;\n this.heap = [];\n }\n\n reserve() {\n if (this.heap.length > 0 && this.heap[0] < this.next) {\n return this.heap.shift();\n }\n\n this.next += 1;\n return this.next - 1;\n }\n\n unreserve(seatNumber) {\n this.enqueueWithPriority(this.heap, seatNumber);\n }\n\n enqueueWithPriority(queue, value) {\n let i = 0;\n while (i < queue.length && queue[i] < value) {\n i++;\n }\n queue.splice(i, 0, value);\n }\n}\n```\n```java []\nclass SeatManager {\n\n private int next;\n private PriorityQueue<Integer> heap;\n\n public SeatManager(int n) {\n next = 1;\n heap = new PriorityQueue<>();\n }\n\n public int reserve() {\n if (!heap.isEmpty() && heap.peek() < next) {\n return heap.poll();\n }\n\n next++;\n return next - 1;\n }\n\n public void unreserve(int seatNumber) {\n heap.offer(seatNumber);\n }\n}\n\n/**\n * Your SeatManager object will be instantiated and called as such:\n * SeatManager obj = new SeatManager(n);\n * int param_1 = obj.reserve();\n * obj.unreserve(seatNumber);\n */\n```\n```C++ []\nclass SeatManager {\n\nprivate:\n int next;\n priority_queue<int, vector<int>, greater<int>> heap;\n\npublic:\n SeatManager(int n) {\n next = 1;\n }\n\n int reserve() {\n if (!heap.empty() && heap.top() < next) {\n int reservedSeat = heap.top();\n heap.pop();\n return reservedSeat;\n }\n\n next++;\n return next - 1;\n }\n\n void unreserve(int seatNumber) {\n heap.push(seatNumber);\n }\n};\n\n/**\n * Your SeatManager object will be instantiated and called as such:\n * SeatManager* obj = new SeatManager(n);\n * int param_1 = obj->reserve();\n * obj->unreserve(seatNumber);\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:04` Heap solution I came up with at first\n`2:38` Two key points with O(n) solution for Eliminate Maximum Number of Monsters\n`2:59` Explain the first key point\n`5:08` Explain the second key point\n`6:19` How we can eliminate monsters that are out of bounds\n`8:48` Let\'s see another case\n`9:52` How we can calculate eliminated numbers\n`10:56` Coding\n`13:03` 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` Basic idea to solve this question\n`1:04` How do you operate each number from the steam of integers?\n`3:34` What operation we need for the two patterns\n`5:17` Coding\n`6:37` Time Complexity and Space Complexity
94,624
Seat Reservation Manager
seat-reservation-manager
Design a system that manages the reservation state of n seats that are numbered from 1 to n. Implement the SeatManager class:
Design,Heap (Priority Queue)
Medium
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations.
16,730
90
# Intuition\nWhen we think about reserving and unreserving seats, our first thought is that we need to keep track of the available seats in an ordered fashion. We should be able to reserve the smallest available seat quickly and also be able to unreserve any seat efficiently. This leads us to think of data structures like sorted lists or heaps.\n\n# Live Coding & More\n\n\n# Approach\nThe approach we\'ve taken is a combination of a **Counter and Min-Heap** strategy.\n\n1. **Counter (`last`)**: This keeps track of the latest continuous seat that\'s been reserved. For example, if seats 1, 2, and 3 are reserved and no unreservations have been made, `last` will be 3.\n \n2. **Min-Heap (`pq`)**: This is used to keep track of seats that have been unreserved and are out of the continuous sequence. For instance, if someone reserves seats 1, 2, and 3, and then unreserves seat 2, then seat 2 will be added to the min-heap.\n\nThe logic for the `reserve` and `unreserve` functions is as follows:\n\n- `reserve`:\n - If the min-heap is empty, simply increment the `last` counter and return it.\n - If the min-heap has seats (i.e., there are unreserved seats), pop the smallest seat from the heap and return it.\n\n- `unreserve`:\n - If the seat being unreserved is the last seat in the continuous sequence, decrement the `last` counter.\n - Otherwise, add the unreserved seat to the min-heap.\n\n# Complexity\n- **Time complexity**:\n - `reserve`: Average $O(1)$ (when using the counter), but $O(\\log n)$ (when using the min-heap).\n - `unreserve`: $O(\\log n)$ (due to the min-heap operation).\n\n- **Space complexity**: $O(n)$. This is the worst-case scenario where all seats have been reserved and then unreserved, filling up the min-heap.\n\n# Code\n``` Python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.last = 0\n self.pq = []\n\n def reserve(self) -> int:\n if not self.pq:\n self.last += 1\n return self.last\n return heapq.heappop(self.pq)\n\n def unreserve(self, seatNumber: int) -> None:\n if seatNumber == self.last:\n self.last -= 1\n else:\n heapq.heappush(self.pq, seatNumber)\n```\n``` Java []\npublic class SeatManager {\n private int last;\n private PriorityQueue<Integer> pq;\n\n public SeatManager(int n) {\n this.last = 0;\n this.pq = new PriorityQueue<>();\n }\n\n public int reserve() {\n if (pq.isEmpty()) {\n return ++last;\n } else {\n return pq.poll();\n }\n }\n\n public void unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.offer(seatNumber);\n }\n }\n}\n```\n``` C++ []\nclass SeatManager {\nprivate:\n int last;\n std::priority_queue<int, std::vector<int>, std::greater<int>> pq;\n\npublic:\n SeatManager(int n) : last(0) {}\n\n int reserve() {\n if (pq.empty()) {\n return ++last;\n } else {\n int seat = pq.top();\n pq.pop();\n return seat;\n }\n }\n\n void unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.push(seatNumber);\n }\n }\n};\n```\n``` C# []\npublic class SeatManager {\n private int last;\n private SortedSet<int> pq;\n\n public SeatManager(int n) {\n this.last = 0;\n this.pq = new SortedSet<int>();\n }\n\n public int Reserve() {\n if (!pq.Any()) {\n return ++last;\n } else {\n int seat = pq.Min;\n pq.Remove(seat);\n return seat;\n }\n }\n\n public void Unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.Add(seatNumber);\n }\n }\n}\n```\n``` Go []\npackage main\n\nimport (\n\t"container/heap"\n)\n\ntype SeatManager struct {\n\tlast int\n\tpq IntHeap\n}\n\nfunc Constructor(n int) SeatManager {\n\treturn SeatManager{\n\t\tlast: 0,\n\t\tpq: make(IntHeap, 0),\n\t}\n}\n\nfunc (this *SeatManager) Reserve() int {\n\tif len(this.pq) == 0 {\n\t\tthis.last++\n\t\treturn this.last\n\t}\n\treturn heap.Pop(&this.pq).(int)\n}\n\nfunc (this *SeatManager) Unreserve(seatNumber int) {\n\tif seatNumber == this.last {\n\t\tthis.last--\n\t} else {\n\t\theap.Push(&this.pq, seatNumber)\n\t}\n}\n\ntype IntHeap []int\n\nfunc (h IntHeap) Len() int { return len(h) }\nfunc (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }\nfunc (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *IntHeap) Push(x interface{}) {\n\t*h = append(*h, x.(int))\n}\n\nfunc (h *IntHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n```\n``` Rust []\nuse std::collections::BinaryHeap;\nuse std::cmp::Reverse;\n\nstruct SeatManager {\n last: i32,\n pq: BinaryHeap<Reverse<i32>>,\n}\n\nimpl SeatManager {\n fn new(n: i32) -> Self {\n SeatManager {\n last: 0,\n pq: BinaryHeap::new(),\n }\n }\n\n fn reserve(&mut self) -> i32 {\n if self.pq.is_empty() {\n self.last += 1;\n self.last\n } else {\n let seat = self.pq.pop().unwrap().0;\n seat\n }\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n if seat_number == self.last {\n self.last -= 1;\n } else {\n self.pq.push(Reverse(seat_number));\n }\n }\n}\n```\n``` JavaScript []\nclass SeatManager {\n constructor(n) {\n this.last = 0;\n this.pq = [];\n }\n\n reserve() {\n if (this.pq.length === 0) {\n return ++this.last;\n } else {\n this.pq.sort((a, b) => a - b);\n return this.pq.shift();\n }\n }\n\n unreserve(seatNumber) {\n if (seatNumber === this.last) {\n this.last--;\n } else {\n this.pq.push(seatNumber);\n }\n }\n}\n```\n``` PHP []\n<?php\nclass SeatManager {\n private $last;\n private $pq;\n\n function __construct($n) {\n $this->last = 0;\n $this->pq = new SplPriorityQueue();\n }\n\n function reserve() {\n if ($this->pq->isEmpty()) {\n return ++$this->last;\n } else {\n return $this->pq->extract();\n }\n }\n\n function unreserve($seatNumber) {\n if ($seatNumber == $this->last) {\n $this->last--;\n } else {\n $this->pq->insert($seatNumber, -$seatNumber);\n }\n }\n}\n?>\n```\n\n# Performance\n\n| Language | Execution Time (ms) | Memory Usage (MB) |\n|----------|---------------------|-------------------|\n| Java | 29 | 91.1 |\n| Rust | 55 | 28.2 |\n| C++ | 260 | 142.2 |\n| Go | 288 | 30.2 |\n| PHP | 324 | 63.6 |\n| Python3 | 361 | 42.5 |\n| C# | 434 | 108.7 |\n| JavaScript | 589 | 120.4 |\n\n![v111.png]()\n\n\n# Why does it work?\nThe approach works because we are always prioritizing the smallest available seat. The counter (`last`) ensures that if we are in a continuous sequence of reservations, we avoid any complex operations and simply increment a value. The min-heap ensures that once seats are unreserved and out of sequence, we can still reserve the smallest available seat efficiently.\n\n# What optimization was made?\nThe major optimization here is the introduction of the `last` counter. Instead of always relying on a heap or list operation (which can be log-linear or linear in time), we often use a constant-time operation when the seats are reserved in sequence.\n\n# What did we learn?\nUsing a combination of simple counters and more complex data structures like heaps can offer a balance between simplicity and efficiency. The counter handles the common case (continuous seat reservation), and the heap handles the edge case (out-of-sequence unreservations). This ensures that our solution is both fast and handles all possible scenarios.
94,628
Seat Reservation Manager
seat-reservation-manager
Design a system that manages the reservation state of n seats that are numbered from 1 to n. Implement the SeatManager class:
Design,Heap (Priority Queue)
Medium
You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations.
4,255
43
Here\'s a general approach to solving this problem:\n\n1. Initialize a data structure to efficiently track available seats. You could use a min-heap, a priority queue, or a custom data structure that can efficiently provide the smallest available seat.\n\n2. In the reserve method, fetch the smallest available seat from your data structure, mark it as reserved, and return its number. You will need to remove it from the data structure so that it\'s not considered for the next reservation.\n\n3. In the unreserve method, unreserve the specified seat by marking it as available again in your data structure.\n\n4. Ensure that your implementation respects the constraints and handles edge cases effectively.\n\n>A "time limit exceeded" error typically indicates that your code is taking too long to execute and hasn\'t completed within the allowed time limit. It doesn\'t necessarily mean there is a logical error in your code; instead, it\'s a performance issue. Your code might be correct in terms of the algorithm and logic, but it may not be efficient enough to run within the specified time constraints.\n\n# 1st Method :- Min Heap\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe `SeatManager` class is designed to manage seat reservations in a system with a specific number of seats, denoted as \'n.\' It maintains a priority queue (min-heap) to keep track of seat availability. When a user requests to reserve a seat, the class provides the smallest unreserved seat, and when a user unreserves a seat, the seat becomes available again. The goal is to efficiently allocate seats and maintain availability.\n\n\n## Approach \uD83D\uDE80\n1. **Initialization (Constructor):** In the constructor, the `SeatManager` class is initialized with the total number of seats \'n.\' It creates a priority queue (`PriorityQueue<Integer> seats`) to keep track of available seats. The queue is initialized with seat numbers from 1 to \'n,\' ensuring that all seats are initially available.\n\n2. **Reserving a Seat (`reserve` method):** When a user requests to reserve a seat, the `reserve` method is called. It checks if there are available seats in the priority queue (`!seats.isEmpty()`). If there are available seats, it retrieves the smallest seat number by using `seats.poll()`, which removes and returns the smallest element from the priority queue. This reserved seat number is returned to the user. If there are no available seats, it returns -1 to indicate that no seat is available.\n\n3. **Unreserving a Seat (`unreserve` method):** When a user unreserves a seat, the `unreserve` method is called, and the seat number that needs to be unreserved is provided as an argument. This method adds the seat number back to the priority queue using `seats.offer(seatNumber)`, effectively making the seat available again.\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass SeatManager {\n private PriorityQueue<Integer> seats; // Declare a priority queue to manage seat reservations.\n\n // Constructor to initialize the SeatManager with \'n\' seats.\n public SeatManager(int n) {\n seats = new PriorityQueue<>();\n // Initialize the priority queue with seat numbers from 1 to \'n\'.\n for (int i = 1; i <= n; i++) {\n seats.offer(i);\n }\n }\n\n // Reserve a seat.\n public int reserve() {\n if (!seats.isEmpty()) { // Check if there are available seats in the priority queue.\n int reservedSeat = seats.poll(); // Get the smallest seat number from the queue.\n return reservedSeat; // Return the reserved seat number.\n } else {\n return -1; // Return -1 to indicate that there are no available seats.\n }\n }\n\n // Unreserve a seat.\n public void unreserve(int seatNumber) {\n seats.offer(seatNumber); // Add the unreserved seat back to the priority queue.\n }\n}\n```\n``` C++ []\nclass SeatManager {\nprivate:\n std::priority_queue<int, std::vector<int>, std::greater<int>> seats; // Declare a min-heap to manage seat reservations.\n\npublic:\n // Constructor to initialize the SeatManager with \'n\' seats.\n SeatManager(int n) {\n // Initialize the min-heap with seat numbers from 1 to \'n\'.\n for (int i = 1; i <= n; i++) {\n seats.push(i);\n }\n }\n\n // Reserve a seat.\n int reserve() {\n if (!seats.empty()) { // Check if there are available seats in the min-heap.\n int reservedSeat = seats.top(); // Get the smallest seat number from the heap.\n seats.pop(); // Remove the reserved seat from the heap.\n return reservedSeat; // Return the reserved seat number.\n } else {\n return -1; // Return -1 to indicate that there are no available seats.\n }\n }\n\n // Unreserve a seat.\n void unreserve(int seatNumber) {\n seats.push(seatNumber); // Add the unreserved seat back to the min-heap.\n }\n};\n\n```\n``` Python []\nclass SeatManager:\n def __init__(self, n):\n self.seats = [] # Initialize an empty list to manage seat reservations.\n self.n = n\n\n # Initialize the list with seat numbers from 1 to \'n\'.\n for i in range(1, n + 1):\n heapq.heappush(self.seats, i)\n\n # Reserve a seat.\n def reserve(self):\n if self.seats: # Check if there are available seats in the list.\n reserved_seat = heapq.heappop(self.seats) # Get the smallest seat number from the list.\n return reserved_seat # Return the reserved seat number.\n else:\n return -1 # Return -1 to indicate that there are no available seats.\n\n # Unreserve a seat.\n def unreserve(self, seat_number):\n if 1 <= seat_number <= self.n:\n heapq.heappush(self.seats, seat_number) # Add the unreserved seat back to the list.\n\n```\n``` JavaScript []\nvar SeatManager = function(n) {\n this.seats = Array.from({ length: n }, (_, index) => index + 1);\n};\n\n\nSeatManager.prototype.reserve = function() {\n if (this.seats.length > 0) {\n // Get the smallest seat number and remove it from the array.\n const reservedSeat = this.seats.shift();\n return reservedSeat;\n } else {\n return -1; // No available seats.\n }\n};\n\nSeatManager.prototype.unreserve = function(seatNumber) {\n // Add the unreserved seat back to the array.\n this.seats.push(seatNumber);\n // Ensure the array remains sorted (optional but efficient).\n this.seats.sort((a, b) => a - b);\n};\n\n```\n``` C# []\n// Error :- Time Limit Exceeded\npublic class SeatManager {\n private Queue<int> seats;\n\n public SeatManager(int n) {\n seats = new Queue<int>();\n for (int i = 1; i <= n; i++) {\n seats.Enqueue(i);\n }\n }\n\n public int Reserve() {\n if (seats.Count > 0) {\n // Get the smallest seat number and remove it from the queue.\n int reservedSeat = seats.Dequeue();\n return reservedSeat;\n } else {\n return -1; // No available seats.\n }\n }\n\n public void Unreserve(int seatNumber) {\n // Add the unreserved seat back to the queue.\n seats.Enqueue(seatNumber);\n // Ensure the queue remains sorted (optional but efficient).\n List<int> sortedSeats = new List<int>(seats);\n sortedSeats.Sort();\n seats = new Queue<int>(sortedSeats);\n }\n}\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: \n1. `SeatManager` Constructor (`SeatManager(int n)`):\n - Time Complexity: $$O(n * log n)$$\n - The constructor initializes the priority queue with seat numbers from 1 to \'n,\' which requires inserting \'n\' elements into the priority queue. Each insertion operation takes $$O(log n)$$ time in a priority queue, resulting in a total time complexity of $$O(n * log n)$$.\n\n2. `reserve` Method:\n - Time Complexity: $$O(log n)$$\n - The `reserve` method performs a single operation on the priority queue, which is either polling the smallest element $$(O(log n))$$ or checking if the queue is empty $$(O(1))$$. In the worst case, it is $$O(log n)$$.\n\n3. `unreserve` Method:\n - Time Complexity: $$O(log n)$$\n - The `unreserve` method performs a single operation on the priority queue, which is adding an element (seat number) back to the queue using `offer()`. This operation takes $$O(log n)$$ time in the worst case.\n\n### \uD83C\uDFF9Space complexity:\n1. `SeatManager` Constructor (`SeatManager(int n)`):\n - Space Complexity: $$O(n)$$\n - The space complexity of the constructor is determined by the size of the priority queue. It stores \'n\' seat numbers, resulting in a space complexity of $$O(n)$$.\n\n2. `reserve` Method:\n - Space Complexity: $$O(1)$$\n - The `reserve` method does not allocate any additional space that scales with the input \'n.\' It only returns the seat number, so it has a constant space complexity.\n\n3. `unreserve` Method:\n - Space Complexity: $$O(1)$$\n - Similar to the `reserve` method, the `unreserve` method does not require additional space that scales with \'n.\' It simply adds a seat number back to the priority queue.\n\n\n![vote.jpg]()\n\n\n---\n\n# 2nd Method :- Bitmask / Bit manipulation\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe SeatManager class is designed to manage the reservation state of seats, specifically tracking which seats are reserved and which ones are available. It uses a BitSet to represent the seat reservation status, where each bit in the BitSet corresponds to a seat. A set bit (1) indicates that the seat is reserved, and a clear bit (0) indicates that the seat is available.\n\n## Approach \uD83D\uDE80\n1. **Initialization (SeatManager Constructor):** When you create a SeatManager object with `new SeatManager(n)`, it initializes a BitSet with `n` bits, representing the `n` seats available. Initially, all bits are clear (0), indicating that all seats are available.\n\n2. **Reserving a Seat (reserve Method):** When you call the `reserve` method, it finds the first unset (0) bit in the BitSet, which represents the lowest-numbered available seat. It does this using `seats.nextClearBit(0)`. The index of this unset bit corresponds to the seat number to be reserved. It sets this bit to 1 to mark the seat as reserved and returns the seat number. Since seat numbers are typically 1-based, you add 1 to the index to get the correct seat number.\n\n3. **Unreserving a Seat (unreserve Method):** When you call the `unreserve` method with a seat number, it converts the seat number to a 0-based index by subtracting 1. It then checks if the corresponding bit is set (1), indicating that the seat is reserved. If the seat is reserved, it clears (sets to 0) the corresponding bit to mark the seat as unreserved.\n\nThe key idea is to use the BitSet to efficiently track the reservation status of seats. Finding the first unset bit allows you to reserve the lowest-numbered available seat quickly, and unreserving a seat is equally efficient by clearing the corresponding bit. This approach provides a fast and memory-efficient way to manage seat reservations.\n\n\n## \u2712\uFE0FCode\nExcept java all codes faced time limit exceeded\n``` Java []\nclass SeatManager {\n private BitSet seats; // Bitset to track seat reservation status\n\n public SeatManager(int n) {\n seats = new BitSet(n);\n }\n\n public int reserve() {\n int nextAvailableSeat = seats.nextClearBit(0); // Find the first unset (0) bit\n seats.set(nextAvailableSeat); // Reserve the seat (set the bit to 1)\n return nextAvailableSeat + 1; // Seat numbers are 1-based, so add 1\n }\n\n public void unreserve(int seatNumber) {\n // Convert the seat number to a 0-based index\n int seatIndex = seatNumber - 1;\n if (seats.get(seatIndex)) {\n seats.clear(seatIndex); // Mark the seat as unreserved (set the bit to 0)\n }\n }\n}\n```\n``` C++ []\n// time limit exceeded\nclass SeatManager {\n std::vector<bool> seats; // Vector to track seat reservation status\n int nextAvailableSeat; // Index of the next available seat\n\npublic:\n SeatManager(int n) {\n seats.assign(n, false); // Initialize all seats as unreserved (false)\n nextAvailableSeat = 0; // Start with the first seat\n }\n\n int reserve() {\n while (nextAvailableSeat < seats.size() && seats[nextAvailableSeat]) {\n nextAvailableSeat++; // Find the next available seat\n }\n\n if (nextAvailableSeat < seats.size()) {\n seats[nextAvailableSeat] = true; // Reserve the seat (set to true)\n return nextAvailableSeat + 1; // Seat numbers are 1-based, so add 1\n }\n return -1; // No available seats\n }\n\n void unreserve(int seatNumber) {\n if (seatNumber > 0 && seatNumber <= seats.size()) {\n int seatIndex = seatNumber - 1; // Convert the seat number to a 0-based index\n if (seats[seatIndex]) {\n seats[seatIndex] = false; // Mark the seat as unreserved (set to false)\n if (seatIndex < nextAvailableSeat) {\n nextAvailableSeat = seatIndex; // Update nextAvailableSeat if needed\n }\n }\n }\n }\n};\n\n```\n``` Python []\n# time limit exceeded\nclass SeatManager:\n def __init__(self, n):\n self.seats = [0] * n # List to track seat reservation status\n\n def reserve(self):\n next_available_seat = self.seats.index(0) # Find the first unset (0) bit\n self.seats[next_available_seat] = 1 # Reserve the seat (set the bit to 1)\n return next_available_seat + 1 # Seat numbers are 1-based, so add 1\n\n def unreserve(self, seat_number):\n # Convert the seat number to a 0-based index\n seat_index = seat_number - 1\n if self.seats[seat_index] == 1:\n self.seats[seat_index] = 0 # Mark the seat as unreserved (set the bit to 0)\n\n```\n``` JavaScript []\n// time limit exceeded\nvar SeatManager = function(n) {\n this.seats = new Set();\n\n for (let i = 1; i <= n; i++) {\n this.seats.add(i);\n }\n};\n\nSeatManager.prototype.reserve = function() {\n const nextAvailableSeat = Array.from(this.seats).sort((a, b) => a - b)[0]; // Find the smallest available seat\n this.seats.delete(nextAvailableSeat); // Reserve the seat (remove it from the set)\n return nextAvailableSeat;\n};\n\nSeatManager.prototype.unreserve = function(seatNumber) {\n this.seats.add(seatNumber); // Mark the seat as unreserved (add it back to the set)\n};\n```\n``` C# []\npublic class SeatManager {\n private BitArray seats; // BitArray to track seat reservation status\n private int nextAvailableSeat; // Index of the next available seat\n\n public SeatManager(int n) {\n seats = new BitArray(n, false);\n nextAvailableSeat = 0; // Start with the first seat\n }\n\n public int Reserve() {\n while (nextAvailableSeat < seats.Length && seats[nextAvailableSeat]) {\n nextAvailableSeat++; // Find the next available seat\n }\n\n if (nextAvailableSeat < seats.Length) {\n seats[nextAvailableSeat] = true; // Reserve the seat (set the bit to true)\n return nextAvailableSeat + 1; // Seat numbers are 1-based\n }\n\n return -1; // No available seats\n }\n\n public void Unreserve(int seatNumber) {\n if (seatNumber > 0 && seatNumber <= seats.Length) {\n int seatIndex = seatNumber - 1; // Convert the seat number to a 0-based index\n if (seats[seatIndex]) {\n seats[seatIndex] = false; // Mark the seat as unreserved (set the bit to false)\n if (seatIndex < nextAvailableSeat) {\n nextAvailableSeat = seatIndex; // Update nextAvailableSeat if the unreserved seat is at an earlier index\n }\n }\n }\n }\n}\n\n//--------------------------\n// because of time limit exceeded, i gave you above code with little changes\n\npublic class SeatManager {\n private BitArray seats; // BitArray to track seat reservation status\n\n public SeatManager(int n) {\n seats = new BitArray(n);\n }\n\n public int Reserve() {\n int nextAvailableSeat = FindFirstUnsetBit(0); // Find the first unset (false) bit\n seats.Set(nextAvailableSeat, true); // Reserve the seat (set the bit to true)\n return nextAvailableSeat + 1; // Seat numbers are 1-based, so add 1\n }\n\n public void Unreserve(int seatNumber) {\n // Convert the seat number to a 0-based index\n int seatIndex = seatNumber - 1;\n if (seats.Get(seatIndex)) {\n seats.Set(seatIndex, false); // Mark the seat as unreserved (set the bit to false)\n }\n }\n\n private int FindFirstUnsetBit(int startIndex) {\n for (int i = startIndex; i < seats.Length; i++) {\n if (!seats.Get(i)) {\n return i;\n }\n }\n return -1; // No unset bit found, should handle this case accordingly\n }\n}\n\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: \n- `SeatManager(int n)`: The constructor initializes the BitSet with a size of `n`. This operation takes $$O(n)$$ time because it needs to set up the BitSet for all seats.\n- `reserve()`: Finding the next available seat using `nextClearBit(0)` is an efficient operation that typically takes $$O(1)$$ time. Setting the bit to reserve the seat is also $$O(1)$$ time.\n- `unreserve(int seatNumber)`: This operation involves checking and clearing a specific bit, which is also an $$O(1)$$ time operation.\n\nOverall, the time complexity for each of the methods is $$O(1)$$, making them very efficient.\n\n### \uD83C\uDFF9Space complexity: \n- The space complexity is determined by the BitSet used to track seat reservation status. It requires space proportional to the number of seats, which is $$O(n)$$. Therefore, the space complexity of this implementation is $$O(n)$$.\n\n\n---\n# 3rd Method :- TreeSet\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe SeatManager class uses a TreeSet to maintain the available seats in a sorted order. When a seat is reserved, it removes the smallest available seat (the first element in the TreeSet). When a seat is unreserved, it adds that seat number back to the TreeSet. This ensures that the seats are always sorted in ascending order.\n\n## Approach \uD83D\uDE80\n1. **Constructor (SeatManager):**\n - The constructor takes an integer parameter `n`, representing the total number of seats.\n - It checks if `n` is a valid value (greater than 0). If `n` is not valid, it throws an `IllegalArgumentException`.\n - It initializes a TreeSet called `seats` to store available seat numbers.\n - It populates the `seats` TreeSet with seat numbers from 1 to `n`.\n\n2. **Reserve (reserve method):**\n - The `reserve` method is called to reserve a seat.\n - If the `seats` TreeSet is empty (no available seats), it returns -1 to indicate that no seats are available.\n - Otherwise, it removes and returns the smallest available seat number by calling `pollFirst()` on the `seats` TreeSet.\n\n3. **Unreserve (unreserve method):**\n - The `unreserve` method is called to unreserve a seat.\n - It takes a parameter `seatNumber`, representing the seat to be unreserved.\n - It checks if `seatNumber` is greater than 0 to ensure it\'s a valid seat number.\n - If `seatNumber` is valid, it adds the `seatNumber` back to the `seats` TreeSet, making it available again.\n\nThe TreeSet data structure ensures that seat numbers are always sorted in ascending order, making it efficient to find the smallest available seat for reservation and add seats back when unreserved.\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass SeatManager {\n private TreeSet<Integer> seats;\n\n public SeatManager(int n) {\n if (n <= 0) {\n throw new IllegalArgumentException("Invalid value of n.");\n }\n\n seats = new TreeSet<>();\n for (int i = 1; i <= n; ++i) {\n seats.add(i);\n }\n }\n\n public int reserve() {\n if (seats.isEmpty()) {\n return -1; // No available seats.\n }\n return seats.pollFirst();\n }\n\n public void unreserve(int seatNumber) {\n if (seatNumber > 0) {\n seats.add(seatNumber);\n }\n }\n}\n\n```\n``` C++ []\n\nclass SeatManager {\nprivate:\n std::set<int> seats; // Use a set to store available seats.\n\npublic:\n SeatManager(int n) {\n if (n <= 0) {\n throw std::invalid_argument("Invalid value of n.");\n }\n\n // Initialize available seats from 1 to n.\n for (int i = 1; i <= n; ++i) {\n seats.insert(i);\n }\n }\n\n int reserve() {\n if (seats.empty()) {\n return -1; // No available seats.\n }\n \n int reservedSeat = *seats.begin(); // Get the smallest available seat.\n seats.erase(reservedSeat); // Remove the seat from available seats.\n return reservedSeat;\n }\n\n void unreserve(int seatNumber) {\n if (seatNumber > 0) {\n seats.insert(seatNumber); // Add the seat back to available seats.\n }\n }\n};\n\n```\n``` Python []\nclass SeatManager:\n def __init__(self, n):\n if n <= 0:\n raise ValueError("Invalid value of n.")\n \n self.seats = list(range(1, n + 1)) # Initialize available seats from 1 to n.\n\n def reserve(self):\n if not self.seats:\n return -1 # No available seats.\n \n reserved_seat = heapq.heappop(self.seats) # Get the smallest available seat.\n return reserved_seat\n\n def unreserve(self, seat_number):\n if seat_number > 0:\n heapq.heappush(self.seats, seat_number) # Add the seat back to available seats.\n\n```\n``` JavaScript []\n// Time Limit Exceeded\nvar SeatManager = function(n) {\n if (n <= 0) {\n throw new Error("Invalid value of n.");\n }\n\n this.seats = new Set();\n for (let i = 1; i <= n; ++i) {\n this.seats.add(i);\n }\n};\n\nSeatManager.prototype.reserve = function() {\n if (this.seats.size === 0) {\n return -1; // No available seats.\n }\n const reservedSeat = Math.min(...this.seats);\n this.seats.delete(reservedSeat);\n return reservedSeat;\n};\n\nSeatManager.prototype.unreserve = function(seatNumber) {\n if (seatNumber > 0) {\n this.seats.add(seatNumber);\n }\n};\n```\n``` C# []\npublic class SeatManager {\n private SortedSet<int> seats;\n\n public SeatManager(int n) {\n if (n <= 0) {\n throw new ArgumentException("Invalid value of n.");\n }\n\n seats = new SortedSet<int>();\n for (int i = 1; i <= n; ++i) {\n seats.Add(i);\n }\n }\n\n public int Reserve() {\n if (seats.Count == 0) {\n return -1; // No available seats.\n }\n int reservedSeat = seats.Min;\n seats.Remove(reservedSeat);\n return reservedSeat;\n }\n\n public void Unreserve(int seatNumber) {\n if (seatNumber > 0) {\n seats.Add(seatNumber);\n }\n }\n}\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: \n1. Constructor (`SeatManager(int n)`):\n - Time Complexity: $$O(n * log(n))$$ due to the loop where seats are added to the TreeSet. Insertion into a TreeSet has a time complexity of $$O(log(n))$$, and the loop runs for \'n\' seats.\n\n2. `reserve()` Method:\n - Time Complexity: $$O(log(n))$$ to find and reserve the smallest available seat using `pollFirst()` from the TreeSet.\n\n3. `unreserve(int seatNumber)` Method:\n - Time Complexity: $$O(log(n))$$ to add a seat number back to the TreeSet using `add()`.\n\n### \uD83C\uDFF9Space complexity: \n1. Constructor (`SeatManager(int n)`):\n - Space Complexity: $$O(n)$$ for the TreeSet to store available seats. In the worst case, it will store all seat numbers from 1 to \'n\'.\n\n2. `reserve()` Method:\n - Space Complexity: $$O(1)$$ as no additional space is used.\n\n3. `unreserve(int seatNumber)` Method:\n - Space Complexity: $$O(1)$$ as no additional space is used.\n\n![upvote.png]()\n\n# Up Vote Guys\n
94,648
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
Array,Greedy,Sorting
Medium
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
1,851
44
# Intuition\nSort input array at first.\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`0:19` Important condition\n`0:56` Demonstrate how it works\n`3:08` What if we have a lot of the same numbers in input array?\n`4:10` Coding\n`4:55` 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,110\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\n## How we think about a solution\n\nWe have 2 types of operations.\n\n**Decrease**\nthe value of any element of arr to a smaller positive integer.\n\n**Rearrange**\nthe elements of arr to be in any order.\n\nSince we cannot increase input numbers, it\'s good idea to sort with ascending order to handle numbers from small to large.\n\n---\n\n\u2B50\uFE0F Points\n\nSort input array to handle numbers from small to large\n\n---\n\nThe description says "The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, `abs(arr[i] - arr[i - 1]) <= 1`".\n\nBut we don\'t have to care about relation betweeen 2 adjacenet numbers too much because we can decrease any input numbers to smaller positive integer. \n\nAll we have to do is just to find larger number than current number we need.\n\nLet\'s see a concrete example.\n\n```\nInput: arr = [100,3,5,5,1000]\n```\nFirst of all, we sort input array.\n```\n[3,5,5,100,1000]\n```\n\nWe consider the first number(= 3) as 1, because we can decrease the numbers to smaller positive numbers and 1 is minimum possible number, so we can expand possibility to get large max value as a result. Let\'s say `max_val`.\n\nIterate through input numbers one by one.\n```\nindex: 0\n\nreal: [3,5,5,100,1000]\nvirtual: [1,5,5,100,1000]\n\nmax_val = 1\n\n\u203B We don\'t need to create virtual array in the solution code.\nThis is just for visualization.\n```\nAt index 1, what number do we need? it\'s `2`, because we consider index 0(= 3) as `1`, so\n```\nabs(arr[i] - arr[i - 1]) <= 1\nif case 2, abs(2 - 1) <= 1 \u2192 true\nif case 3, abs(3 - 1) <= 1 \u2192 false\n``` \nAt index 1, since we can decrease any large number to smaller positive number. we consider `5` as `2`. \n\nIf current number(= 5) is larger than current `max_val`(= 1), we can decrease `5` to `2`.\n\nSo formula is very simple.\n```\nif arr[i] > max_val:\n max_val += 1\n```\nSo\n```\nif arr[i] > max_val:\nif 5 > 1 \u2192 true\n```\n```\nindex: 1\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,5,100,1000]\n\nmax_val = 2\n```\n\nI\'ll speed up. At index 2, we need `3`, because current `max_val` is `2`. so\n```\nif arr[i] > max_val:\nif 5 > 2 \u2192 true\n```\n```\nindex: 2\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,100,1000]\n\nmax_val = 3\n```\nAt index 3, we need `4`, so\n```\nif arr[i] > max_val:\nif 100 > 3 \u2192 true\n```\n```\nindex: 3\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,4,1000]\n\nmax_val = 4\n```\nAt index 4, we need `5`, so\n```\nif arr[i] > max_val:\nif 1000 > 4 \u2192 true\n```\n```\nindex: 4\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,4,5]\n\nmax_val = 5\n```\nThis `max_val` should be the maximum possible value of an element in input array after performing operations.\n```\nOutput: 5\n```\n\n### What if we have a lot of the same number in input array?\n\nLet\'s think about this quickly\n\n```\nInput: arr = [1,2,2,2,2]\n```\n```\nindex 0\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 1\n```\nAt index 1, we need 2\n```\nindex 1\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\nAt index 2 we need 3, but the number at index 2 is smaller than the number we need, so skip.\n```\nindex 2\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\nAt index 3 and 4, it\'s the same as index 2.\n```\nindex 3, index 4\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\n```\nOutput: 2\n```\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm!\n\n---\n\n\n### Algorithm Overview:\n\n1. Sort the Array\n2. Iterate Through the Sorted Array\n3. Update Maximum Value\n\n### Detailed Explanation\n\n1. **Sort the Array**:\n ```python\n arr.sort()\n ```\n - The array `arr` is sorted in ascending order using the `sort()` method.\n\n2. **Iterate Through the Sorted Array**:\n ```python\n for i in range(1, len(arr)):\n ```\n - A `for` loop is used to iterate through the array, starting from index 1.\n\n3. **Update Maximum Value**:\n ```python\n if arr[i] > max_val:\n max_val += 1\n ```\n - For each element in the sorted array, if it is greater than the current `max_val`, then `max_val` is incremented by 1.\n\n4. **Return Maximum Value**:\n ```python\n return max_val\n ```\n - The final maximum value is returned as the result.\n\nIn summary, this algorithm ensures that after sorting the array, each element is compared with the current maximum value, and if it is greater, the maximum value is updated. The final maximum value is then returned.\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n\n- Space complexity: $$O(log n)$$ or $$O(n)$$, depends on language you use.\n\n\n```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n max_val = 1\n\n for i in range(1, len(arr)):\n if arr[i] > max_val:\n max_val += 1\n\n return max_val\n```\n```javascript []\nvar maximumElementAfterDecrementingAndRearranging = function(arr) {\n arr.sort((a, b) => a - b);\n let maxVal = 1;\n\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \n};\n```\n```java []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n int maxVal = 1;\n\n for (int i = 1; i < arr.length; i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(), arr.end());\n int maxVal = 1;\n\n for (int i = 1; i < arr.size(); i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \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` Explain a key point of the question\n`1:39` Why you need to iterate through input array with len(nums) + 1?\n`2:25` Coding\n`3:56` Explain part of my solution code.\n`3:08` What if we have a lot of the same numbers in input array?\n`6:11` 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:00` Read the question of Unique Length-3 Palindromic Subsequences\n`1:03` Explain a basic idea to solve Unique Length-3 Palindromic Subsequences\n`4:48` Coding\n`8:01` Summarize the algorithm of Unique Length-3 Palindromic Subsequences\n\n
94,674
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
Array,Greedy,Sorting
Medium
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
1,881
14
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSort the `arr` at once.\nSet `arr[0]=1`. Then iterate the `arr`.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInside of the loop just do one thing\n```\nif (arr[i]-arr[i-1]>1)\n arr[i]=arr[i-1]+1;\n```\nAt final\n```\nreturn arr.back()\n```\nHave you ever seen `"[209,209,209,....209]"`? The answer is `210`! strange! I think it should be `209`. I am sure there is no `210` hidden in this array.\nAfter carefully checking there is one `"10000"` hidden in this array.\nProblem solved!\n\nYou can decrease the numbers, sort, must begin with 1, but there is no way to increase the numbers\n# Using frequency count needs only O(n) time\n\nThe maximal value for the answer can not exceed over $n=len(arr)$ (Think about the extreme case `[1,2, 3,..., n]`)\n\nUse a container array `freq` to store the number of occurrencies.\nAdd the count of elements with value i to the accumulated sum. \n`acc += freq[i];`\nIf the accumulated sum exceeds the current value of i, update the accumulated sum to i.\n`\nif (i < acc) \n acc = i;\n`\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)->O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n2nd approach $O(n)$.\n# Code C++ runtime 45ms beats 100%\n\n```C++ []\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) \n {\n sort(arr.begin(), arr.end());\n \n int n=arr.size();\n arr[0]=1;\n #pragma unroll\n for(int i=1; i<n ; i++){\n if (arr[i]-arr[i-1]>1)\n arr[i]=arr[i-1]+1;\n }\n return arr.back();\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```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n ans=1\n for x in arr[1:]:\n ans=min(x, ans+1)\n return ans\n \n```\n# Code using frequency count TC: O(n)\n```\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) \n {\n int freq[100001]={0};\n int n=arr.size();\n #pragma unroll\n for(int& x:arr)\n freq[min(n, x)]++;// if x>n, set x=n\n int acc=0, j=1;\n #pragma unroll\n for(int i=1; i<=n; i++){\n acc += freq[i];\n if (i < acc) \n acc = i;\n }\n return acc;\n }\n};\n```\n\n
94,675
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
Array,Greedy,Sorting
Medium
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
7,737
42
#### Intuition/Flow chart\nThe first element of the sorted array is set to 1, satisfying the first condition of our question.\n\nFor the remaining elements, beginning with the second one, ensure that each next element is at least one more than the previous element. This will ensure that the absolute difference between consecutive elements is at most 1.\n\nFinally, return the last element in this modified array, representing the maximum possible value.\n\n```CSS\n+------------------+\n| Sort array |\n| in ascending |\n| order |\n+------------------+\n |\n v\n+------------------+\n| Set first |\n| element to 1 |\n+------------------+\n |\n v\n+------------------+\n| For each element |\n| from the second |\n| one to the end: |\n| +--------------+|\n| | Check if ||\n| | |abs diff| ||\n| | | > 1 | ||\n| +--------------+|\n| | |\n| v |\n| +--------------+|\n| | Adjust ||\n| | current elem ||\n| | to be at ||\n| | least one ||\n| | more than ||\n| | previous ||\n| | element ||\n| +--------------+|\n| | |\n| v |\n+------------------+\n| Return last elem |\n| of modified array|\n+------------------+\n```\n\n### CPP\n\n```cpp\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(),arr.end());\n arr[0] = 1; // first condition\n\n for (int i = 1; i < arr.size(); ++i) {\n if (abs(arr[i] - arr[i - 1]) <= 1) continue; // purposely wrote for understanding\n else arr[i] = arr[i - 1] + 1; // second condition \n }\n\n return arr.back(); // returns a reference to the last element\n }\n};\n```\n\n### Java\n\n```java\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n arr[0] = 1; // first condition\n\n for (int i = 1; i < arr.length; ++i) {\n if (Math.abs(arr[i] - arr[i - 1]) <= 1) {\n continue; // purposely wrote for understanding\n } else {\n arr[i] = arr[i - 1] + 1; // second condition\n }\n }\n\n return arr[arr.length - 1]; \n }\n}\n```\n\n### Python\n\n```py\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr):\n arr.sort()\n arr[0] = 1 # first condition\n\n for i in range(1, len(arr)):\n if abs(arr[i] - arr[i - 1]) <= 1:\n continue # purposely wrote for understanding\n else:\n arr[i] = arr[i - 1] + 1 # second condition\n\n return arr[-1] \n```\n
94,676
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
Array,Greedy,Sorting
Medium
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
3,980
29
\n**UPVOTE IF HELPFuuL**\n\n# Key Points\n- First element is always ```1```\n- Array is always ascending [ increasing order ]\n- Element equal or greater than ```1``` is possible in final array from previous element.\n\n\n# Approach\nIt is defined that the first element always remains one and array is sorted in ascending manner.\nAlso the next element cannot be greater than ```1``` more than its previous element.\nAlso to minimise the number of ```decreasing``` operations we need to keep the element as ```MAX``` as possible.\n - If element is equal to its predessor -> ```a[i] == a[i-1]```, then no decrement is required.\n - Else we perform decreament operations, such that ```a[i] == a[i-1] + 1```\n\nNow we only need the last value of this sorted array, which can be stored using a variable.\nBelow is implementation of this logic.\n\n# Complexity\n- Time complexity: O(N * logN)\nN log N -> foor sorting\n\n- Space complexity: O(1) -> Constant Extra space required\n\n\n**UPVOTE IF HELPFuuL**\n\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(),arr.end());\n int res = 1;\n for(int i=1; i<arr.size(); i++){\n if(arr[i] > res)\n res = res + 1;\n }\n return res;\n }\n};\n```\n```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n res = 1\n for i in range(1,len(arr)):\n if (arr[i] > res):\n res += 1\n return res\n```\n```JAVA []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n int res = 1;\n for (int i = 1; i < arr.length; ++i) {\n if (arr[i] > res) {\n ++res;\n }\n }\n return res;\n }\n}\n```\n\n![IMG_3740.JPG]()\n\n
94,686
Maximum Element After Decreasing and Rearranging
maximum-element-after-decreasing-and-rearranging
You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions: There are 2 types of operations that you can perform any number of times: Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.
Array,Greedy,Sorting
Medium
Sort the Array. Decrement each element to the largest integer that satisfies the conditions.
240
8
# Complexity\n- Time complexity:\n $$O(N\'logN )$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n arr[0]=1\n for i in range(1,len(arr)):\n if arr[i]-arr[i-1]>1:arr[i]=arr[i-1]+1\n return arr[-1]\n```
94,705
Maximum Ice Cream Bars
maximum-ice-cream-bars
It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. Return the maximum number of ice cream bars the boy can buy with coins coins. Note: The boy can buy the ice cream bars in any order.
Array,Greedy,Sorting
Medium
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
4,046
10
## Logic\n- To buy The maximum amount of icecream, we need to buy the cheapest ones first.\n## Approach\n1. Sort costs from cheapest to most expensive.\n2. Buy the cheapest icecream & Update Coins `coins -= cost`\n3. Repeat until ``coins <= 0`` OR all icecreams are bought.(\u02F5 \u0361\xB0 \u035C\u0296 \u0361\xB0\u02F5)\n\n[+] Update coins while comparing it with cost\n\n instead of :\n coins -= costs[i]\n if(coins < 0) Break\n Do :\n if( (coins-= costs[i]) <0 ) Break\n## Explained Code\n```c++ []\n int maxIceCream(vector<int>& costs, int coins) {\n sort(costs.begin(),costs.end()); // Sort Costs\n\n for(int i=0 ;i<costs.size(); ++i)\n if( (coins-=costs[i])<0) //Update && check\n return i; \n\n //if we still have coins after buying all the icecream :\n return costs.size(); \n }\n```\n```java []\n public int maxIceCream(int[] costs, int coins) {\n Arrays.sort(costs); // Sort costs\n\n for(int i=0 ;i<costs.length;++i)\n if( (coins-=costs[i])<0) // Update && check\n return i; \n\n //if we still have coins after buying all the icecream :\n return costs.length;\n }\n```\n```C []\nint comparator(const void *p, const void *q) // used in qsort\n {return (*(int*)p-*(int*)q);} \n\nint maxIceCream(int* costs, int size, int coins){\n qsort((void*)costs, size, sizeof(costs[0]), comparator);\n\n for(int i=0 ;i<size; ++i)\n if((coins-=costs[i])<0) return i;\n return size;\n}\n```\n```Python3 []\n def maxIceCream(self, costs: List[int], coins: int) -> int:\n costs.sort()\n for i in range(len(costs)):\n coins -= costs[i] # Buy the ith iceream\n if coins < 0: # check if we can afford more\n return i\n #if we bought all icecreams and still got coins\n return len(costs)\n```\n```python []\n def maxIceCream(self, costs, coins):\n costs.sort()\n for i in range(len(costs)):\n coins -= costs[i] # Buy the ith iceream\n if coins < 0: # check if we can afford more\n return i\n #if we bought all icecreams and still got coins\n return len(costs)\n```\n## Raw Code\n```c++ []\n int maxIceCream(vector<int>& costs, int coins) {\n sort(costs.begin(),costs.end()); \n for(int i=0 ;i<costs.size(); ++i)\n if( (coins-=costs[i])<0) return i; \n return costs.size(); \n }\n```\n```java []\n public int maxIceCream(int[] costs, int coins) {\n Arrays.sort(costs);\n for(int i=0 ;i<costs.length;++i)\n if( (coins-=costs[i])<0) return i;\n return costs.length;\n }\n```\n```C []\nint comparator(const void *p, const void *q)\n {return (*(int*)p-*(int*)q);} \n\nint maxIceCream(int* costs, int size, int coins){\n qsort((void*)costs, size, sizeof(costs[0]), comparator);\n\n for(int i=0 ;i<size; ++i)\n if((coins-=costs[i])<0) return i;\n return size;\n}\n```\n```Python3 []\n def maxIceCream(self, costs: List[int], coins: int) -> int:\n costs.sort()\n for i in range(len(costs)):\n coins -= costs[i]\n if coins < 0: \n return i\n return len(costs)\n```\n```python []\n def maxIceCream(self, costs, coins):\n costs.sort()\n for i in range(len(costs)):\n coins -= costs[i]\n if coins < 0:\n return i\n return len(costs)\n```\nTime Complexity : $$O(nlogn)$$\nSpace Complexity : $$O(1)$$\n\n![image.png]()\n
94,827
Maximum Ice Cream Bars
maximum-ice-cream-bars
It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. Return the maximum number of ice cream bars the boy can buy with coins coins. Note: The boy can buy the ice cream bars in any order.
Array,Greedy,Sorting
Medium
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
746
7
# Code\n```\nclass Solution:\n def maxIceCream(self, costs: List[int], coins: int) -> int:\n return sum(1 for icecream in sorted(costs) if (coins:= coins-icecream) >= 0)\n```\n![ alt text for screen readers]( "Text to show on mouseover")
94,830
Single-Threaded CPU
single-threaded-cpu
You are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing. You have a single-threaded CPU that can process at most one task at a time and will act in the following way: Return the order in which the CPU will process the tasks.
Array,Sorting,Heap (Priority Queue)
Medium
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
929
8
```\ndef getOrder(self, tasks: List[List[int]]) -> List[int]:\n arr = []\n prev = 0\n output = [] \n tasks= sorted((tasks,i) for i,tasks in enumerate(tasks))\n for (m,n), i in tasks:\n while arr and prev < m:\n p,j,k = heappop(arr)\n prev = max(k,prev)+p\n output.append(j)\n heappush(arr,(n,i,m))\n return output+[i for _, i, _ in sorted(arr)]\n```
94,920
Find XOR Sum of All Pairs Bitwise AND
find-xor-sum-of-all-pairs-bitwise-and
The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element. You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers. Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length. Return the XOR sum of the aforementioned list.
Array,Math,Bit Manipulation
Hard
Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum.
454
7
```\nPlease consider upvoting if found helpful! :)\n```\n\n"^" = Logical XOR\n"+" = Logical OR\n"." = Logical AND\n\nAs per Boolean Algebra, we know that A^B = A\'.B + A.B\'\n\nProof:\n\nLHS = (a&b) ^ (a&c)\n= (a.b) ^ (a.c)\n\t = A^B . . . . . . . . . . . . . .(A = a.b, B = a.c)\n\t = A\'B | AB\'\n\t\t= (a . b)\' . (a . c) + (a . b) . (a . c)\'\n\t\t= (a\' + b\') . (a . c) + (a . b) . (a\' + c\')\n\t = (a\' . a . c + b\' . a . c) + (a . b . a\' + a . b . c\')\n\t\t= ( 0 + a.b\'.c) + ( 0 + a.b.c\') . . . . . . . . . . . . . . . . (becoz a . a\' = 0 (null) )\n\t\t= a.b\'.c + a.b.c\'\n\t\t= a.(b\'c + b.c\')\n\t\t= a.(b^c)\n\t\t= a&(b^c) = RHS
94,941
Sum of Digits in Base K
sum-of-digits-in-base-k
Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
Math
Easy
Convert the given number into base k. Use mod-10 to find what each digit is after the conversion and sum the digits.
822
5
```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n output_sum = 0\n while (n > 0) :\n rem = n % k\n output_sum = output_sum + rem \n n = int(n / k)\n return output_sum\n```
95,005
Sum of Digits in Base K
sum-of-digits-in-base-k
Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k. After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.
Math
Easy
Convert the given number into base k. Use mod-10 to find what each digit is after the conversion and sum the digits.
1,949
13
\n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n ans = 0\n while n: \n n, x = divmod(n, k)\n ans += x\n return ans \n```
95,007
Frequency of the Most Frequent Element
frequency-of-the-most-frequent-element
The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the maximum possible frequency of an element after performing at most k operations.
Array,Binary Search,Greedy,Sliding Window,Sorting,Prefix Sum
Medium
Note that you can try all values in a brute force manner and find the maximum frequency of that value. To find the maximum frequency of a value consider the biggest elements smaller than or equal to this value
11,944
85
\n# 1st Method :- Two Pointers / Sliding Window\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe goal of the problem is to find the maximum frequency of an element in an array after performing certain operations. The operations involve adding or subtracting a given value `k` to elements in the array. To achieve this, the code uses a sliding window approach.\n\nThe intuition behind the sliding window is to maintain a valid subarray (window) that satisfies the given condition. By adjusting the window based on the sum of elements and the condition, the code efficiently explores different subarrays to find the maximum frequency.\n\n## Approach \uD83D\uDE80\n\n1. **Sorting:**\n - The array `nums` is sorted in ascending order. Sorting is crucial for the sliding window approach, as it allows us to efficiently adjust the window based on the current element.\n\n2. **Sliding Window:**\n - Two pointers, `left` and `right`, are used to define the subarray. The `right` pointer is advanced to include elements in the current subarray, while the `left` pointer is adjusted to maintain a valid subarray.\n\n3. **Subarray Sum and Adjustments:**\n - `currentSum` represents the sum of elements in the current subarray. The code adds the current element (`nums[right]`) to this sum.\n - A while loop checks if the current subarray violates the condition (`sum + k < nums[right] * length`). If it does, the code adjusts the subarray by removing the leftmost element and updating the sum. This ensures that the condition is satisfied.\n\n4. **Update Maximum Frequency:**\n - The maximum frequency (`maxFrequency`) is updated by comparing it with the length of the current subarray (`right - left + 1`). The length represents the number of elements in the valid subarray.\n\n5. **Return Result:**\n - The final result is the maximum frequency found after processing the entire array.\n\nIn summary, the approach involves efficiently exploring different subarrays using a sliding window and adjusting the window based on the sum of elements and the given condition. Sorting the array is a key step to simplify the sliding window process. The code efficiently finds the maximum frequency by maintaining a valid subarray and updating the frequency as the window moves through the array.\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n int maxFrequency = 0; // Initialize the maximum frequency\n long currentSum = 0; // Initialize the current sum of the subarray elements\n\n Arrays.sort(nums); // Sort the array in ascending order\n\n for (int left = 0, right = 0; right < nums.length; ++right) {\n currentSum += nums[right]; // Include the current element in the subarray sum\n\n // Check if the current subarray violates the condition (sum + k < nums[right] * length)\n while (currentSum + k < (long) nums[right] * (right - left + 1)) {\n currentSum -= nums[left]; // Adjust the subarray sum by removing the leftmost element\n left++; // Move the left pointer to the right\n }\n\n // Update the maximum frequency based on the current subarray length\n maxFrequency = Math.max(maxFrequency, right - left + 1);\n }\n\n return maxFrequency;\n }\n}\n\n```\n``` C++ []\nclass Solution {\npublic:\n int maxFrequency(vector<int>& nums, int k) {\n int maxFrequency = 0; // Initialize the maximum frequency\n long currentSum = 0; // Initialize the current sum of the subarray elements\n\n std::sort(nums.begin(), nums.end()); // Sort the array in ascending order\n\n for (int left = 0, right = 0; right < nums.size(); ++right) {\n currentSum += nums[right]; // Include the current element in the subarray sum\n\n // Check if the current subarray violates the condition (sum + k < nums[right] * length)\n while (currentSum + k < static_cast<long>(nums[right]) * (right - left + 1)) {\n currentSum -= nums[left]; // Adjust the subarray sum by removing the leftmost element\n left++; // Move the left pointer to the right\n }\n\n // Update the maximum frequency based on the current subarray length\n maxFrequency = std::max(maxFrequency, right - left + 1);\n }\n\n return maxFrequency;\n }\n};\n\n```\n``` Python []\nclass Solution(object):\n def maxFrequency(self, nums, k):\n maxFrequency = 0 # Initialize the maximum frequency\n currentSum = 0 # Initialize the current sum of the subarray elements\n\n nums.sort() # Sort the array in ascending order\n\n left = 0\n for right in range(len(nums)):\n currentSum += nums[right] # Include the current element in the subarray sum\n\n # Check if the current subarray violates the condition (sum + k < nums[right] * length)\n while currentSum + k < nums[right] * (right - left + 1):\n currentSum -= nums[left] # Adjust the subarray sum by removing the leftmost element\n left += 1 # Move the left pointer to the right\n\n # Update the maximum frequency based on the current subarray length\n maxFrequency = max(maxFrequency, right - left + 1)\n\n return maxFrequency\n\n```\n``` JavaScript []\nvar maxFrequency = function(nums, k) {\n let maxFrequency = 0; // Initialize the maximum frequency\n let currentSum = 0; // Initialize the current sum of the subarray\n\n nums.sort((a, b) => a - b); // Sort the array in ascending order\n\n for (let left = 0, right = 0; right < nums.length; ++right) {\n currentSum += nums[right]; // Include the current element in the subarray sum\n\n // Check if the current subarray violates the condition (sum + k < nums[right] * length)\n while (currentSum + k < nums[right] * (right - left + 1)) {\n currentSum -= nums[left]; // Adjust the subarray sum by removing the leftmost element\n left++; // Move the left pointer to the right\n }\n\n // Update the maximum frequency based on the current subarray length\n maxFrequency = Math.max(maxFrequency, right - left + 1);\n }\n\n return maxFrequency;\n};\n\n```\n``` C# []\npublic class Solution {\n public int MaxFrequency(int[] nums, int k) {\n int maxFrequency = 0; // Initialize the maximum frequency\n long currentSum = 0; // Initialize the current sum of the subarray\n\n Array.Sort(nums); // Sort the array in ascending order\n\n for (int left = 0, right = 0; right < nums.Length; ++right) {\n currentSum += nums[right]; // Include the current element in the subarray sum\n\n // Check if the current subarray violates the condition (sum + k < nums[right] * length)\n while (currentSum + k < (long)nums[right] * (right - left + 1)) {\n currentSum -= nums[left]; // Adjust the subarray sum by removing the leftmost element\n left++; // Move the left pointer to the right\n }\n\n // Update the maximum frequency based on the current subarray length\n maxFrequency = Math.Max(maxFrequency, right - left + 1);\n }\n\n return maxFrequency;\n }\n}\n\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(n log n)\n- The code sorts the array, which has a time complexity of O(n log n), where n is the length of the input array `nums`.\n- The main loop iterates through each element in the sorted array once, so it has a time complexity of O(n), where n is the length of the input array.\n- Overall, the dominant factor is the sorting operation, making the time complexity O(n log n).\n\n### \uD83C\uDFF9Space complexity: O(1)\n- The space complexity is O(1) because the code uses a constant amount of extra space, regardless of the size of the input array. The additional space is used for variables like `maxFrequency`, `currentSum`, and loop variables (`left` and `right`), and it does not depend on the input size. Hence, the space complexity is constant.\n\n\n![vote.jpg]()\n\n---\n# 2nd Method :- Sliding Window & Greedy\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe goal of the problem is to find the maximum frequency of any element in a subarray after performing operations on the array. The operations involve adjusting the subarray by removing elements to minimize the difference between the product of the element and the length of the subarray and the sum of the subarray.\n\n## Approach \uD83D\uDE80\n\n1. **Counting Sort:**\n - The initial step involves sorting the array in non-decreasing order using counting sort. This step ensures that elements are processed in ascending order during the main iteration.\n\n2. **Sliding Window:**\n - The code uses a sliding window approach with two pointers (`start` and `i`) to define the current subarray.\n - `start` represents the leftmost index of the subarray, and `i` represents the rightmost index.\n\n3. **Product and Sum Calculation:**\n - For each element in the sorted array, the code calculates the product of the element and the length of the current subarray (`subarrayProduct = nums[i] * subarrayLength`).\n - It also maintains the sum of elements in the current subarray (`subarraySum += nums[i]`).\n\n4. **Adjustment of Subarray:**\n - If the difference between the product and the sum of the subarray exceeds the given limit (`k`), the subarray is adjusted.\n - The adjustment involves removing elements from the left of the subarray (`subarraySum -= nums[start]`) and updating the subarray length until the condition is satisfied.\n\n5. **Update Maximum Frequency:**\n - The code updates the maximum frequency (`maxFrequency`) by comparing it with the length of the current subarray.\n - The length of the subarray represents the frequency of the current element in the subarray.\n\n6. **Iteration Through Array:**\n - The iteration through the array continues until all elements are processed.\n\n7. **Return Result:**\n - The final result returned is the maximum frequency found after processing the entire array.\n\n### Summary:\n\nThe approach involves maintaining a sliding window and adjusting it as needed to satisfy the given condition. The code efficiently finds the maximum frequency by considering the product of elements and the length of the subarray, with counting sort aiding in sorting the array initially. The sliding window adjusts to minimize the difference between the product and the sum of the subarray, ensuring an optimal solution to the problem.\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n countingSort(nums); // Sort the array using counting sort\n int start = 0; // Start index of the current subarray\n int subarraySum = 0; // Sum of elements in the current subarray\n int maxFrequency = 1; // Initialize the maximum frequency to 1\n\n // Iterate through the sorted array\n for (int i = 0; i < nums.length; i++) {\n int subarrayLength = i - start + 1; // Length of the current subarray\n int subarrayProduct = nums[i] * subarrayLength; // Product of element and subarray length\n subarraySum += nums[i]; // Add the current element to the subarray sum\n\n // Adjust the subarray to satisfy the condition (product - sum <= k)\n while (subarrayProduct - subarraySum > k) {\n subarraySum -= nums[start]; // Remove the leftmost element from the subarray\n start++; // Move the start index to the right\n subarrayLength--; // Decrease the length of the subarray\n subarrayProduct = nums[i] * subarrayLength; // Recalculate the product\n }\n\n // Update the maximum frequency based on the current subarray length\n maxFrequency = Math.max(maxFrequency, subarrayLength);\n }\n\n return maxFrequency; // Return the final result\n }\n\n // Counting Sort to sort the array in non-decreasing order\n private void countingSort(int[] nums) {\n int maxElement = Integer.MIN_VALUE;\n\n // Find the maximum element in the array\n for (int num : nums) {\n maxElement = Math.max(maxElement, num);\n }\n\n // Create an array to store the count of each element\n int[] countMap = new int[maxElement + 1];\n\n // Count the occurrences of each element in the array\n for (int num : nums) {\n countMap[num]++;\n }\n\n int index = 0;\n\n // Reconstruct the sorted array\n for (int i = 0; i <= maxElement; i++) {\n while (countMap[i]-- > 0) {\n nums[index++] = i;\n }\n }\n }\n}\n\n```\n``` C++ []\nclass Solution {\npublic:\n int maxFrequency(std::vector<int>& nums, int k) {\n countingSort(nums); // Sort the array using counting sort\n int start = 0; // Start index of the current subarray\n long long subarraySum = 0; // Sum of elements in the current subarray\n int maxFrequency = 1; // Initialize the maximum frequency to 1\n\n // Iterate through the sorted array\n for (int i = 0; i < nums.size(); i++) {\n int subarrayLength = i - start + 1; // Length of the current subarray\n long long subarrayProduct = (long long)nums[i] * subarrayLength; // Use long long to avoid overflow\n subarraySum += nums[i]; // Add the current element to the subarray sum\n\n // Adjust the subarray to satisfy the condition (product - sum <= k)\n while (subarrayProduct - subarraySum > k) {\n subarraySum -= nums[start]; // Remove the leftmost element from the subarray\n start++; // Move the start index to the right\n subarrayLength--; // Decrease the length of the subarray\n subarrayProduct = (long long)nums[i] * subarrayLength; // Recalculate the product\n }\n\n // Update the maximum frequency based on the current subarray length\n maxFrequency = std::max(maxFrequency, subarrayLength);\n }\n\n return maxFrequency; // Return the final result\n }\n\nprivate:\n // Counting Sort to sort the array in non-decreasing order\n void countingSort(std::vector<int>& nums) {\n int maxElement = INT_MIN;\n\n // Find the maximum element in the array\n for (int num : nums) {\n maxElement = std::max(maxElement, num);\n }\n\n // Create an array to store the count of each element\n std::vector<int> countMap(maxElement + 1, 0);\n\n // Count the occurrences of each element in the array\n for (int num : nums) {\n countMap[num]++;\n }\n\n int index = 0;\n\n // Reconstruct the sorted array\n for (int i = 0; i <= maxElement; i++) {\n while (countMap[i]-- > 0) {\n nums[index++] = i;\n }\n }\n }\n};\n\n```\n``` Python []\nclass Solution:\n def maxFrequency(self, nums, k):\n self.countingSort(nums) # Sort the array using counting sort\n start = 0 # Start index of the current subarray\n subarray_sum = 0 # Sum of elements in the current subarray\n max_frequency = 1 # Initialize the maximum frequency to 1\n\n # Iterate through the sorted array\n for i in range(len(nums)):\n subarray_length = i - start + 1 # Length of the current subarray\n subarray_product = nums[i] * subarray_length # Product of element and subarray length\n subarray_sum += nums[i] # Add the current element to the subarray sum\n\n # Adjust the subarray to satisfy the condition (product - sum <= k)\n while subarray_product - subarray_sum > k:\n subarray_sum -= nums[start] # Remove the leftmost element from the subarray\n start += 1 # Move the start index to the right\n subarray_length -= 1 # Decrease the length of the subarray\n subarray_product = nums[i] * subarray_length # Recalculate the product\n\n # Update the maximum frequency based on the current subarray length\n max_frequency = max(max_frequency, subarray_length)\n\n return max_frequency # Return the final result\n\n # Counting Sort to sort the array in non-decreasing order\n def countingSort(self, nums):\n max_element = max(nums)\n\n # Create an array to store the count of each element\n count_map = [0] * (max_element + 1)\n\n # Count the occurrences of each element in the array\n for num in nums:\n count_map[num] += 1\n\n index = 0\n\n # Reconstruct the sorted array\n for i in range(max_element + 1):\n while count_map[i] > 0:\n nums[index] = i\n index += 1\n count_map[i] -= 1\n\n\n```\n``` JavaScript []\nvar maxFrequency = function(nums, k) {\n countingSort(nums); // Sort the array using counting sort\n let start = 0; // Start index of the current subarray\n let subarraySum = 0; // Sum of elements in the current subarray\n let maxFrequency = 1; // Initialize the maximum frequency to 1\n\n // Iterate through the sorted array\n for (let i = 0; i < nums.length; i++) {\n let subarrayLength = i - start + 1; // Length of the current subarray\n let subarrayProduct = nums[i] * subarrayLength; // Product of element and subarray length\n subarraySum += nums[i]; // Add the current element to the subarray sum\n\n // Adjust the subarray to satisfy the condition (product - sum <= k)\n while (subarrayProduct - subarraySum > k) {\n subarraySum -= nums[start]; // Remove the leftmost element from the subarray\n start++; // Move the start index to the right\n subarrayLength--; // Decrease the length of the subarray\n subarrayProduct = nums[i] * subarrayLength; // Recalculate the product\n }\n\n // Update the maximum frequency based on the current subarray length\n maxFrequency = Math.max(maxFrequency, subarrayLength);\n }\n\n return maxFrequency; // Return the final result\n}\n\n/**\n * Counting Sort to sort the array in non-decreasing order.\n * @param {number[]} nums - The input array of numbers.\n */\nfunction countingSort(nums) {\n const maxElement = Math.max(...nums); // Find the maximum element in the array\n const countMap = Array(maxElement + 1).fill(0); // Create an array to store the count of each element\n let index = 0;\n\n // Count the occurrences of each element in the array\n for (const num of nums) {\n countMap[num]++;\n }\n\n // Reconstruct the sorted array\n for (let i = 0; i <= maxElement; i++) {\n while (countMap[i]-- > 0) {\n nums[index++] = i;\n }\n }\n}\n\n```\n``` C# []\npublic class Solution {\n public int MaxFrequency(int[] nums, int k) {\n CountingSort(nums); // Sort the array using counting sort\n int start = 0; // Start index of the current subarray\n int subarraySum = 0; // Sum of elements in the current subarray\n int maxFrequency = 1; // Initialize the maximum frequency to 1\n\n // Iterate through the sorted array\n for (int i = 0; i < nums.Length; i++) {\n int subarrayLength = i - start + 1; // Length of the current subarray\n int subarrayProduct = nums[i] * subarrayLength; // Product of element and subarray length\n subarraySum += nums[i]; // Add the current element to the subarray sum\n\n // Adjust the subarray to satisfy the condition (product - sum <= k)\n while (subarrayProduct - subarraySum > k) {\n subarraySum -= nums[start]; // Remove the leftmost element from the subarray\n start++; // Move the start index to the right\n subarrayLength--; // Decrease the length of the subarray\n subarrayProduct = nums[i] * subarrayLength; // Recalculate the product\n }\n\n // Update the maximum frequency based on the current subarray length\n maxFrequency = Math.Max(maxFrequency, subarrayLength);\n }\n\n return maxFrequency; // Return the final result\n }\n\n // Counting Sort to sort the array in non-decreasing order\n private void CountingSort(int[] nums) {\n int maxElement = int.MinValue;\n\n // Find the maximum element in the array\n foreach (int num in nums) {\n maxElement = Math.Max(maxElement, num);\n }\n\n int[] countMap = new int[maxElement + 1]; // Create an array to store the count of each element\n int index = 0;\n\n // Count the occurrences of each element in the array\n foreach (int num in nums) {\n countMap[num]++;\n }\n\n // Reconstruct the sorted array\n for (int i = 0; i <= maxElement; i++) {\n while (countMap[i]-- > 0) {\n nums[index++] = i;\n }\n }\n }\n\n}\n\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(N + K)\n- **Counting Sort (sorting step):** O(N + K), where N is the length of the input array `nums`, and K is the range of values (maximum element in `nums`).\n - Counting sort has a linear time complexity because it iterates through the input array once to count the occurrences of each element and then reconstructs the sorted array.\n\n- **Main Loop (sliding window):** O(N), where N is the length of the input array `nums`.\n - The main loop iterates through each element of the sorted array once.\n\nThe overall time complexity is dominated by the counting sort step, making the total time complexity O(N + K).\n\n### \uD83C\uDFF9Space complexity: O(K)\n- **Counting Sort (sorting step):** O(K), where K is the range of values (maximum element in `nums`).\n - The space required for counting sort is proportional to the range of values in the input array.\n\n- **Other Variables:** O(1).\n - The space required for variables such as `start`, `subarraySum`, `maxFrequency`, etc., is constant and does not depend on the input size.\n\nThe overall space complexity is O(K), where K is the range of values in the input array.\n\nNote: The space complexity of the counting sort step dominates the overall space complexity. If the range of values (K) is significantly smaller than the length of the input array (N), the space complexity can be considered linear (O(N)).\n\n![vote.jpg]()\n\n---\n# 3rd Method :- Binary Search with Prefix Sum\uD83D\uDD25\n## The least efficient approach\n\n## Intuition \uD83D\uDE80\nThe problem requires finding the maximum frequency of an element in a subarray after performing certain operations. The operations involve changing the elements in the subarray to make the difference between the maximum and minimum elements within a specified limit (k). The provided solution tackles this problem using a binary search approach.\n\n## Approach \uD83D\uDE80\n\n1. **Sort the Array:**\n - The array is sorted in ascending order. Sorting simplifies the calculation of differences between adjacent elements.\n\n2. **Calculate Differences and Prefix Sums:**\n - Differences between adjacent elements are calculated and stored in the `differences` array.\n - Prefix sums of the differences are calculated and stored in the `prefixSums` array. This aids in efficiently computing the sum of differences in subarrays.\n\n3. **Binary Search for Maximum Frequency:**\n - A binary search is employed to find the maximum frequency that satisfies the given conditions.\n - The search space is narrowed down by adjusting the low and high pointers.\n\n4. **isPossible Function:**\n - The `isPossible` function checks if it\'s possible to achieve a certain frequency with the allowed difference `k`.\n - It initializes the `times` variable based on the frequency and the last element in the subarray.\n - It iterates through the array, updating the `times` variable by considering the difference in prefix sums and new differences.\n - The minimum `times` is tracked, and the function returns true if the minimum `times` is within the allowed difference `k`.\n\n### Explanation of Binary Search:\nThe binary search in this context is applied to find the maximum frequency efficiently. The search space is the potential frequencies that we can achieve. The `isPossible` function checks whether it\'s possible to achieve a given frequency with the allowed difference. The binary search updates the search space based on the result of this check until it finds the maximum frequency.\n\n### Overall:\nThe approach leverages sorting, prefix sums, and binary search to efficiently find the maximum frequency of an element in a subarray while considering the allowed difference. The `isPossible` function plays a crucial role in determining the feasibility of achieving a certain frequency. The binary search optimally explores the space of potential frequencies.\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n // Sort the array in ascending order\n Arrays.sort(nums);\n\n int length = nums.length;\n\n // Calculate the differences between adjacent elements\n long[] differences = new long[length];\n for (int i = 1; i < length; i++)\n differences[i] = (long) nums[i] - (long) nums[i - 1];\n\n // Calculate the prefix sums of the differences\n long[] prefixSums = new long[length];\n for (int i = 1; i < length; i++)\n prefixSums[i] = prefixSums[i - 1] + differences[i];\n\n int low = 1, high = length;\n\n // Binary search for the maximum frequency\n while (low < high) {\n int mid = (high - low + 1) / 2 + low;\n\n // Check if it\'s possible to achieve the given frequency with the allowed difference\n if (isPossible(nums, differences, prefixSums, mid, k))\n low = mid;\n else\n high = mid - 1;\n }\n\n return low;\n }\n\n // Function to check if it\'s possible to achieve the given frequency with the allowed difference\n public boolean isPossible(int[] nums, long[] differences, long[] prefixSums, int freq, int k) {\n int length = differences.length;\n\n long times = 0;\n\n // Calculate the initial times based on the frequency and the last element in the subarray\n for (int i = freq - 2; i >= 0; i--)\n times += (long) nums[freq - 1] - (long) nums[i];\n\n long minTimes = times;\n\n // Iterate from freq-th element to the end of the array\n for (int i = freq; i < length; i++) {\n // Update times by considering the difference in prefix sums and new differences\n times = times - (prefixSums[i - 1] - prefixSums[i - freq]) + differences[i] * (freq - 1);\n minTimes = Math.min(minTimes, times);\n }\n\n // Check if the minimum times is within the allowed difference (k)\n return minTimes <= (long) k;\n }\n}\n\n```\n``` C++ []\nclass Solution {\npublic:\n int maxFrequency(std::vector<int>& nums, int k) {\n // Sort the array in ascending order\n std::sort(nums.begin(), nums.end());\n\n int length = nums.size();\n\n // Calculate the differences between adjacent elements\n std::vector<long> differences(length);\n for (int i = 1; i < length; i++)\n differences[i] = static_cast<long>(nums[i]) - static_cast<long>(nums[i - 1]);\n\n // Calculate the prefix sums of the differences\n std::vector<long> prefixSums(length);\n for (int i = 1; i < length; i++)\n prefixSums[i] = prefixSums[i - 1] + differences[i];\n\n int low = 1, high = length;\n\n // Binary search for the maximum frequency\n while (low < high) {\n int mid = (high - low + 1) / 2 + low;\n\n // Check if it\'s possible to achieve the given frequency with the allowed difference\n if (isPossible(nums, differences, prefixSums, mid, k))\n low = mid;\n else\n high = mid - 1;\n }\n\n return low;\n }\n\nprivate:\n // Function to check if it\'s possible to achieve the given frequency with the allowed difference\n bool isPossible(const std::vector<int>& nums, const std::vector<long>& differences, const std::vector<long>& prefixSums, int freq, int k) {\n int length = differences.size();\n\n long times = 0;\n\n // Calculate the initial times based on the frequency and the last element in the subarray\n for (int i = freq - 2; i >= 0; i--)\n times += static_cast<long>(nums[freq - 1]) - static_cast<long>(nums[i]);\n\n long minTimes = times;\n\n // Iterate from freq-th element to the end of the array\n for (int i = freq; i < length; i++) {\n // Update times by considering the difference in prefix sums and new differences\n times = times - (prefixSums[i - 1] - prefixSums[i - freq]) + differences[i] * (freq - 1);\n minTimes = std::min(minTimes, times);\n }\n\n // Check if the minimum times is within the allowed difference (k)\n return minTimes <= static_cast<long>(k);\n }\n};\n\n```\n``` Python []\nclass Solution:\n def maxFrequency(self, nums, k):\n # Sort the array in ascending order\n nums.sort()\n\n length = len(nums)\n\n # Calculate the differences between adjacent elements\n differences = [0] * length\n for i in range(1, length):\n differences[i] = nums[i] - nums[i - 1]\n\n # Calculate the prefix sums of the differences\n prefix_sums = [0] * length\n for i in range(1, length):\n prefix_sums[i] = prefix_sums[i - 1] + differences[i]\n\n low, high = 1, length\n\n # Binary search for the maximum frequency\n while low < high:\n mid = (high - low + 1) // 2 + low\n\n # Check if it\'s possible to achieve the given frequency with the allowed difference\n if self.isPossible(nums, differences, prefix_sums, mid, k):\n low = mid\n else:\n high = mid - 1\n\n return low\n\n def isPossible(self, nums, differences, prefix_sums, freq, k):\n length = len(differences)\n\n times = 0\n\n # Calculate the initial times based on the frequency and the last element in the subarray\n for i in range(freq - 2, -1, -1):\n times += nums[freq - 1] - nums[i]\n\n min_times = times\n\n # Iterate from freq-th element to the end of the array\n for i in range(freq, length):\n # Update times by considering the difference in prefix sums and new differences\n times = times - (prefix_sums[i - 1] - prefix_sums[i - freq]) + differences[i] * (freq - 1)\n min_times = min(min_times, times)\n\n # Check if the minimum times is within the allowed difference (k)\n return min_times <= k\n\n```\n``` JavaScript []\nvar maxFrequency = function(nums, k) {\n/**\n * Function to find the maximum frequency of an element in a subarray\n * after performing certain operations.\n * @param {number[]} nums - The input array of numbers.\n * @param {number} k - The allowed difference for operations.\n * @returns {number} - The maximum frequency.\n */\n // Sort the array in ascending order\n nums.sort((a, b) => a - b);\n\n const length = nums.length;\n\n // Calculate the differences between adjacent elements\n const differences = new Array(length).fill(0);\n for (let i = 1; i < length; i++)\n differences[i] = nums[i] - nums[i - 1];\n\n // Calculate the prefix sums of the differences\n const prefixSums = new Array(length).fill(0);\n for (let i = 1; i < length; i++)\n prefixSums[i] = prefixSums[i - 1] + differences[i];\n\n let low = 1, high = length;\n\n // Binary search for the maximum frequency\n while (low < high) {\n const mid = Math.floor((high - low + 1) / 2) + low;\n\n // Check if it\'s possible to achieve the given frequency with the allowed difference\n if (isPossible(nums, differences, prefixSums, mid, k))\n low = mid;\n else\n high = mid - 1;\n }\n\n return low;\n}\n\n/**\n * Function to check if it\'s possible to achieve the given frequency with the allowed difference.\n * @param {number[]} nums - The input array of numbers.\n * @param {number[]} differences - The array of differences between adjacent elements.\n * @param {number[]} prefixSums - The array of prefix sums of differences.\n * @param {number} freq - The current frequency being considered.\n * @param {number} k - The allowed difference for operations.\n * @returns {boolean} - True if the given frequency is possible; otherwise, false.\n */\nfunction isPossible(nums, differences, prefixSums, freq, k) {\n const length = differences.length;\n\n let times = 0;\n\n // Calculate the initial times based on the frequency and the last element in the subarray\n for (let i = freq - 2; i >= 0; i--)\n times += nums[freq - 1] - nums[i];\n\n let minTimes = times;\n\n // Iterate from freq-th element to the end of the array\n for (let i = freq; i < length; i++) {\n // Update times by considering the difference in prefix sums and new differences\n times = times - (prefixSums[i - 1] - prefixSums[i - freq]) + differences[i] * (freq - 1);\n minTimes = Math.min(minTimes, times);\n }\n\n // Check if the minimum times is within the allowed difference (k)\n return minTimes <= k;\n}\n\n\n```\n``` C# []\nusing System;\n\npublic class Solution {\n public int MaxFrequency(int[] nums, int k) {\n // Sort the array in ascending order\n Array.Sort(nums);\n\n int length = nums.Length;\n\n // Calculate the differences between adjacent elements\n long[] differences = new long[length];\n for (int i = 1; i < length; i++)\n differences[i] = nums[i] - nums[i - 1];\n\n // Calculate the prefix sums of the differences\n long[] prefixSums = new long[length];\n for (int i = 1; i < length; i++)\n prefixSums[i] = prefixSums[i - 1] + differences[i];\n\n int low = 1, high = length;\n\n // Binary search for the maximum frequency\n while (low < high) {\n int mid = (high - low + 1) / 2 + low;\n\n // Check if it\'s possible to achieve the given frequency with the allowed difference\n if (IsPossible(nums, differences, prefixSums, mid, k))\n low = mid;\n else\n high = mid - 1;\n }\n\n return low;\n }\n\n // Function to check if it\'s possible to achieve the given frequency with the allowed difference\n public bool IsPossible(int[] nums, long[] differences, long[] prefixSums, int freq, int k) {\n int length = differences.Length;\n\n long times = 0;\n\n // Calculate the initial times based on the frequency and the last element in the subarray\n for (int i = freq - 2; i >= 0; i--)\n times += nums[freq - 1] - nums[i];\n\n long minTimes = times;\n\n // Iterate from freq-th element to the end of the array\n for (int i = freq; i < length; i++) {\n // Update times by considering the difference in prefix sums and new differences\n times = times - (prefixSums[i - 1] - prefixSums[i - freq]) + differences[i] * (freq - 1);\n minTimes = Math.Min(minTimes, times);\n }\n\n // Check if the minimum times is within the allowed difference (k)\n return minTimes <= k;\n }\n\n}\n\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(n log n)\n1. **Sorting:**\n - The initial sorting of the array takes O(n log n) time, where n is the length of the array.\n\n2. **Differences and Prefix Sums:**\n - Calculating differences and prefix sums involves iterating through the array once, which takes O(n) time.\n\n3. **Binary Search:**\n - The binary search iterates log(n) times.\n\n4. **isPossible Function:**\n - The `isPossible` function iterates through the array once, making it O(n).\n\nThe overall time complexity is dominated by the sorting step, making it O(n log n).\n\n### \uD83C\uDFF9Space complexity: O(n)\n\n1. **Differences and Prefix Sums:**\n - Additional space is used to store the arrays `differences` and `prefixSums`, each of size n. Therefore, the space complexity for these arrays is O(n).\n\n2. **Other Variables:**\n - Other variables like `low`, `high`, `mid`, `times`, and `minTimes` use constant space.\n\nThe overall space complexity is O(n) due to the additional arrays created for differences and prefix sums.\n\n\n\n\n\n\n![upvote.png]()\n\n# Up Vote Guys\n\n\n\n\n\n\n
95,027
Frequency of the Most Frequent Element
frequency-of-the-most-frequent-element
The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the maximum possible frequency of an element after performing at most k operations.
Array,Binary Search,Greedy,Sliding Window,Sorting,Prefix Sum
Medium
Note that you can try all values in a brute force manner and find the maximum frequency of that value. To find the maximum frequency of a value consider the biggest elements smaller than or equal to this value
2,665
45
# Intuition\nSorting input array and use slinding window technique.\n\n---\n\n# Solution Video\n\n\n\n\u203B Since I recorded that video last year, there might be parts that could be unclear. If you have any questions, feel free to leave a comment.\n\n\u25A0 Timeline of the video\n\n`0:00` Read the question of Frequency of the Most Frequent Element\n`1:11` Explain a basic idea to solve Frequency of the Most Frequent Element\n`11:48` Coding\n`14:21` Summarize the algorithm of Frequency of the Most Frequent Element\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,139\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\n## How we think about a solution\n\nLet\'s think about this case.\n\n```\nInput = [1,3,3,5,5] k = 4\n```\n\nI already sorted input array. Sorting is good idea because sorting makes it easier to group similar magnitudes next to each other, facilitating the creation of identical numbers.\n\nFor example, we try to make 3 three times. Let\'s compare sorted array and unsorted array.\n```\nSorted: [1,3,3,5,5]\u2192[3,3,3,5,5]\nUnsroted: [1,5,3,5,3]\u2192[3,5,3,5,3]\n```\nSeems like sorted array is easier to find numbers we should increase. In addition to that, there is no order constraints for this question.\n\nTo check adjacent numbers after sorting the input array, we use sliding window technique.\n\n**Basically, we are trying to make all the numbers same in the window.**\n\nWe are allowed to increase numbers `k` times. when we try to make all numbers same in the window, simply \n\n---\n\n\u2B50\uFE0F Points\n\n```\ncurrent number * range of window > current window total + k\n```\n\nIf we meet the condition, we need to shorten window size, because we cannot change all numbers in window to the same number.\n\nFor example, \n```\ninput = [1,3,3,5,5], k = 1\n```\nLet\'s say we are now at `index 1` and try to make two `3` from `index 0` to `index 1`.\n\nIn that case, we need `6` to make all numbers `3`.(= `3`(current number) * `2`(range of window)), but current window total is `4`(= `1` + `3`). we perform `1` time, so we can deal with up to `5`.\n\nOne time short. That\'s why we need to shorten window size.\n\n- What if `k = 2`?\n\nWith the formula, `6` > `6`. it\'s false. In that case, we can expand window size, because if we add `2` to `index 0`, we can create `[3,3,3,5,5]`.\n\nIn other words, we can consider window size as maximum possible frequency of an element.\n\n---\n\nLet\'s see one by one.\n\nWe use two pointers `left` and `right` starging from index `0`.\n```\n[1,3,3,5,5] k = 4\n L\n R\n\nwindow total = 1 (= between left and right)\n```\nNow window total is `1`. Let\'s decide window size with the formula.\n\n```\ncurrent number * range of window > current window total + k\n\ncurrent number: 1(= right number)\nrange of window: 0(= right) - 0(= left) + 1\ncurrent window total: 1\nk: 4\n\n1 * 1 > 1 + 4\n1 > 5\n\u2192 false\n\n```\n`1 * 1` means total number in the window if we make all numbers same.\n`1 + 4` means maximum number after we perform increament.\n\nIt\'s false, just compare current window size with current maximum window size and take a large size. \n\n```\nmax(res, right - left + 1)\n= 0 vs 1\n\nres = 1\n```\nLet\'s move next.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 4 (= between left and right)\nres = 1 (= max window size = maximum possible frequency of an element)\n```\nDecide window size with the formula\n\n```\ncurrent number * range of window > current window total + k\n= 3 * 2 > 4 + 4\n\u2192 false\n\n6 is total number in window if we make all numbers 3 in window.\nWe can deal with up to 8.\n\nWe can expand the window size\n\nres = 2 (1(= res) vs 1(= right) - 0(= left) + 1)\n```\nLet\'s move next.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 7\nres = 2\n```\nDecide window size with the formula\n```\ncurrent number * range of window > current window total + k\n= 3 * 3 > 7 + 4\n\u2192 false\n\nWe can expand the window size\n\nres = 3 (= 2 vs 2 - 0 + 1)\n```\n\nLet\'s move next.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 12\nres = 3\n```\nDecide window size with the formula\n```\ncurrent number * range of window > current window total + k\n= 5 * 4 > 12 + 4\n\u2192 true\n\nWe cannot make all numbers 5 in the window.\nWe will shorten window size\n```\nMove `left` pointer to next and subtract current left number(= 1) from window total, because it will be out of bounds from the window.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 11\nres = 3\n```\nDecide window size with the formula again.\n```\ncurrent number * range of window > current window total + k\n= 5 * 3 > 11 + 4\n\u2192 false\n\nWe can make all numbers 5 in the window.\n\nCalculate window size\nres = 3 (= 3 vs 3 - 1 + 1)\n```\nLet\'s move next.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 16\nres = 3\n```\nDecide window size with the formula\n```\ncurrent number * range of window > current window total + k\n= 5 * 4 > 16 + 4\n\u2192 false\n\nWe can expand the window size\n\nres = 4 (= 3 vs 4 - 1 + 1)\n```\nThen finish iteration.\n```\nOutput: 4\n```\nLet\'s check.\n```\n[1,3,3,5,5] k = 4\n L R\n\nAdd 2 to index 1.\n[1,5,3,5,5] k = 2\n L R\n\nAdd 2 to index 2.\n[1,5,5,5,5] k = 0\n L R\n```\nWe can create four 5 in the window.\n\nLet\'s see a real algorithm!\n\n\n---\n\n\n\n### Algorithm Overview\n\nThe algorithm aims to find the maximum frequency of an element that can be obtained by performing at most `k` operations on the array.\n\n### Detailed Explanation\n\n1. **Sort the input array:**\n - **Code:**\n ```python\n nums.sort()\n ```\n - **Explanation:**\n Sorts the input array in ascending order. Sorting is essential for grouping similar magnitudes together, facilitating subsequent operations.\n\n2. **Initialize variables:**\n - **Code:**\n ```python\n left = right = res = total = 0\n ```\n - **Explanation:**\n Initializes variables to keep track of the current window (`left` and `right` pointers), the maximum frequency (`res`), and the total sum (`total`) within the window.\n\n3. **Sliding Window Approach:**\n - **Code:**\n ```python\n while right < len(nums):\n total += nums[right]\n\n while nums[right] * (right - left + 1) > total + k:\n total -= nums[left]\n left += 1\n \n res = max(res, right - left + 1)\n right += 1\n ```\n - **Explanation:**\n - The outer loop (`while right < len(nums)`) iterates through the array, expanding the window to the right.\n - The inner loop (`while nums[right] * (right - left + 1) > total + k`) contracts the window from the left if the current window violates the condition specified by `k`.\n - Updates the maximum frequency (`res`) with the size of the current window.\n - Moves the right pointer to expand the window.\n\n4. **Return the result:**\n - **Code:**\n ```python\n return res\n ```\n - **Explanation:**\n Returns the maximum frequency obtained after performing at most `k` operations.\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(log n)$$ or $$O(n)$$\nDepends on language you use. Sorting need some extra space.\n\n```python []\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n \n nums.sort()\n left = right = res = total = 0\n\n while right < len(nums):\n total += nums[right]\n\n while nums[right] * (right - left + 1) > total + k:\n total -= nums[left]\n left += 1\n \n res = max(res, right - left + 1)\n right += 1\n \n return res\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b);\n let left = 0, right = 0, res = 0, total = 0;\n\n while (right < nums.length) {\n total += nums[right];\n\n while (nums[right] * (right - left + 1) > total + k) {\n total -= nums[left];\n left += 1;\n }\n\n res = Math.max(res, right - left + 1);\n right += 1;\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n Arrays.sort(nums);\n int left = 0, right = 0;\n long res = 0, total = 0;\n\n while (right < nums.length) {\n total += nums[right];\n\n while (nums[right] * (right - left + 1L) > total + k) {\n total -= nums[left];\n left += 1;\n }\n\n res = Math.max(res, right - left + 1L);\n right += 1;\n }\n\n return (int) res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxFrequency(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int left = 0, right = 0;\n long res = 0, total = 0;\n\n while (right < nums.size()) {\n total += nums[right];\n\n while (nums[right] * static_cast<long>(right - left + 1) > total + k) {\n total -= nums[left];\n left += 1;\n }\n\n res = max(res, static_cast<long>(right - left + 1));\n right += 1;\n }\n\n return static_cast<int>(res); \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` Try to find a solution pattern\n`1:44` What if we have the same numbers in input array?\n`5:37` Why it works when we skip reduction\n`7:22` Coding\n`8:52` 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` Explain how we can solve Minimize Maximum Pair Sum in Array\n`2:21` Check with other pair combinations\n`4:12` Let\'s see another example!\n`5:37` Find Common process of the two examples\n`6:45` Coding\n`7:55` Time Complexity and Space Complexity
95,032
Frequency of the Most Frequent Element
frequency-of-the-most-frequent-element
The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the maximum possible frequency of an element after performing at most k operations.
Array,Binary Search,Greedy,Sliding Window,Sorting,Prefix Sum
Medium
Note that you can try all values in a brute force manner and find the maximum frequency of that value. To find the maximum frequency of a value consider the biggest elements smaller than or equal to this value
247
7
\nThis algorithm uses a sliding window approach to efficiently find the maximum frequency while considering the constraints on the number of operations.\n\n# Approach\nTo solve this problem, you can follow these steps:\n\n1. Sort the input array `nums` in ascending order.\n2. Initialize a variable `left` to 0 to represent the left boundary of the window, and initialize a variable `maxFreq` to 0 to store the maximum frequency.\n3. Iterate through the array with a variable `right` representing the right boundary of the window.\n4. Calculate the total number of operations needed to make all elements in the current window equal. This can be done by multiplying the difference between the current element and the previous element by the distance between the current and previous elements.\n5. If the total operations exceed `k`, move the left boundary of the window to the right.\n6. Update the maximum frequency based on the current window size.\n7. Continue this process until you reach the end of the array.\n\n\n# Code\n```\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n \n nums.sort()\n left = 0\n maxFreq = 0\n operations = 0\n \n for right in range(len(nums)):\n operations += (nums[right] - nums[right - 1]) * (right - left)\n \n while operations > k:\n operations -= nums[right] - nums[left]\n left += 1\n \n maxFreq = max(maxFreq, right - left + 1)\n \n return maxFreq\n\n\n```\n# **PLEASE DO UPVOTE!!!**
95,069
Frequency of the Most Frequent Element
frequency-of-the-most-frequent-element
The frequency of an element is the number of times it occurs in an array. You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1. Return the maximum possible frequency of an element after performing at most k operations.
Array,Binary Search,Greedy,Sliding Window,Sorting,Prefix Sum
Medium
Note that you can try all values in a brute force manner and find the maximum frequency of that value. To find the maximum frequency of a value consider the biggest elements smaller than or equal to this value
789
6
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Sliding Window)***\n1. Sort the `nums` array in ascending order to ensure that the elements are in non-decreasing order.\n\n1. Initialize two pointers, `left` and `right`, both starting at the beginning (0) of the sorted array. `left` represents the `left` end of the subarray, and `right` represents the `right` end.\n\n1. Initialize two variables, `ans` (for storing the maximum subarray length) and `curr` (for storing the sum of elements in the current subarray).\n\n1. Iterate through the `nums` array with the `right` pointer, starting from index 0 and moving to the end of the array.\n\n1. For each element `target` at index `right`, add it to the `curr` sum to represent the addition of the element to the subarray.\n\n1. Use a while loop to adjust the subarray size while maintaining the condition that increasing all elements in the subarray (from `left` to `right`) by at most k should result in a strictly increasing subarray. The condition being checked is `(right - left + 1) * target - curr > k`.\n\n - If this condition is met, it means that the current subarray doesn\'t satisfy the requirement of increasing each element by at most `k`. In this case, reduce the subarray size by removing the element at the `left` pointer. This is done by subtracting `nums[left]` from `curr` and incrementing `left`.\n1. In each iteration, update `ans` by taking the maximum of the current `ans` and the length of the subarray from `left` to `right`, which is `right - left + 1`.\n\n1. Continue iterating through the array, adjusting the subarray size as necessary, and updating `ans` until you reach the end of the array.\n\n1. After the loop finishes, `ans` will contain the maximum length of a subarray that satisfies the condition of increasing each element by at most `k`.\n\n1. Return `ans` as the result.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(logn)$$ or $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxFrequency(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int left = 0;\n int ans = 0;\n long curr = 0;\n \n for (int right = 0; right < nums.size(); right++) {\n long target = nums[right];\n curr += target;\n \n while ((right - left + 1) * target - curr > k) {\n curr -= nums[left];\n left++;\n }\n \n ans = max(ans, right - left + 1);\n }\n \n return ans;\n }\n};\n\n```\n\n```C []\n\nint maxFrequency(int* nums, int numsSize, int k) {\n // Sort the nums array in ascending order\n qsort(nums, numsSize, sizeof(int), cmp);\n \n int left = 0;\n int ans = 0;\n long curr = 0;\n \n for (int right = 0; right < numsSize; right++) {\n long target = nums[right];\n curr += target;\n \n while ((right - left + 1) * target - curr > k) {\n curr -= nums[left];\n left++;\n }\n \n ans = fmax(ans, right - left + 1);\n }\n \n return ans;\n}\n\n\n```\n\n```Java []\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n Arrays.sort(nums);\n int left = 0;\n int ans = 0;\n long curr = 0;\n \n for (int right = 0; right < nums.length; right++) {\n int target = nums[right];\n curr += target;\n \n while ((right - left + 1) * target - curr > k) {\n curr -= nums[left];\n left++;\n }\n \n ans = Math.max(ans, right - left + 1);\n }\n \n return ans;\n }\n}\n\n```\n\n```python3 []\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n left = 0\n ans = 0\n curr = 0\n \n for right in range(len(nums)):\n target = nums[right]\n curr += target\n \n while (right - left + 1) * target - curr > k:\n curr -= nums[left]\n left += 1\n \n ans = max(ans, right - left + 1)\n\n return ans\n```\n\n\n```javascript []\nvar maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b);\n let left = 0;\n let ans = 0;\n let curr = 0;\n\n for (let right = 0; right < nums.length; right++) {\n const target = nums[right];\n curr += target;\n\n while ((right - left + 1) * target - curr > k) {\n curr -= nums[left];\n left++;\n }\n\n ans = Math.max(ans, right - left + 1);\n }\n\n return ans;\n};\n\n```\n\n\n---\n\n#### ***Approach 2( Advanced sliding Window)***\n1. The code sorts the input array in ascending order to make it easier to work with.\n\n1. It uses two pointers, `i` and `j`, to represent the window. The `sum` variable keeps track of the sum of elements within the window, and `maxlen` stores the maximum window length.\n\n1. The outer loop (controlled by `j`) iterates through the array elements and expands the window by adding elements to `sum`.\n\n1. The inner `while` loop adjusts the window size to maximize the window length without exceeding `k`. It does so by removing elements from the left end (incrementing `i`) until the condition is met.\n\n1. The maximum window length is updated whenever a longer window is found.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxFrequency(vector<int>& nums, int k) {\n int n = nums.size();\n sort(nums.begin(), nums.end()); // Sort the input array in ascending order.\n\n int i = 0; // Initialize a pointer i at the beginning of the sorted array.\n long long sum = 0; // Initialize a variable to keep track of the sum of elements within the window.\n int maxlen = 1; // Initialize the maximum window length.\n\n for (int j = 0; j < n; j++) {\n sum += nums[j]; // Add the current element to the sum.\n \n // Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while (1LL * nums[j] * (j - i + 1) > sum + k) {\n sum -= nums[i]; // Remove the element at position i from the window.\n i++; // Increment i to make the window smaller (moving the left end to the right).\n }\n\n maxlen = max(maxlen, j - i + 1); // Update the maximum window length.\n }\n\n return maxlen; // Return the maximum window length.\n }\n};\n\n\n```\n\n```C []\n\nint maxFrequency(int* nums, int numsSize, int k) {\n qsort(nums, numsSize, sizeof(int), compare); // Sort the input array in ascending order.\n\n int i = 0; // Initialize a pointer i at the beginning of the sorted array.\n long long sum = 0; // Initialize a variable to keep track of the sum of elements within the window.\n int maxlen = 1; // Initialize the maximum window length.\n\n for (int j = 0; j < numsSize; j++) {\n sum += nums[j]; // Add the current element to the sum.\n\n // Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while (1LL * nums[j] * (j - i + 1) > sum + k) {\n sum -= nums[i]; // Remove the element at position i from the window.\n i++; // Increment i to make the window smaller (moving the left end to the right).\n }\n\n maxlen = maxlen > (j - i + 1) ? maxlen : (j - i + 1); // Update the maximum window length.\n }\n\n return maxlen; // Return the maximum window length.\n}\n\n\n```\n\n```Java []\npublic int maxFrequency(int[] nums, int k) {\n Arrays.sort(nums); // Sort the input array in ascending order.\n\n int i = 0; // Initialize a pointer i at the beginning of the sorted array.\n long sum = 0; // Initialize a variable to keep track of the sum of elements within the window.\n int maxlen = 1; // Initialize the maximum window length.\n\n for (int j = 0; j < nums.length; j++) {\n sum += nums[j]; // Add the current element to the sum.\n\n // Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while ((long)nums[j] * (j - i + 1) > sum + k) {\n sum -= nums[i]; // Remove the element at position i from the window.\n i++; // Increment i to make the window smaller (moving the left end to the right).\n }\n\n maxlen = Math.max(maxlen, j - i + 1); // Update the maximum window length.\n }\n\n return maxlen; // Return the maximum window length.\n}\n\n\n```\n\n```python3 []\ndef maxFrequency(nums, k):\n nums.sort() # Sort the input array in ascending order.\n\n i = 0 # Initialize a pointer i at the beginning of the sorted array.\n total = 0 # Initialize a variable to keep track of the sum of elements within the window.\n maxlen = 1 # Initialize the maximum window length.\n\n for j in range(len(nums)):\n total += nums[j] # Add the current element to the total sum.\n\n # Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while nums[j] * (j - i + 1) > total + k:\n total -= nums[i] # Remove the element at position i from the window.\n i += 1 # Increment i to make the window smaller (moving the left end to the right).\n\n maxlen = max(maxlen, j - i + 1) # Update the maximum window length.\n\n return maxlen # Return the maximum window length.\n\n```\n\n\n```javascript []\nvar maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b); // Sort the input array in ascending order.\n\n let i = 0; // Initialize a pointer i at the beginning of the sorted array.\n let sum = 0; // Initialize a variable to keep track of the sum of elements within the window.\n let maxlen = 1; // Initialize the maximum window length.\n\n for (let j = 0; j < nums.length; j++) {\n sum += nums[j]; // Add the current element to the sum.\n\n // Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while (nums[j] * (j - i + 1) > sum + k) {\n sum -= nums[i]; // Remove the element at position i from the window.\n i++; // Increment i to make the window smaller (moving the left end to the right).\n }\n\n maxlen = Math.max(maxlen, j - i + 1); // Update the maximum window length.\n }\n\n return maxlen; // Return the maximum window length.\n};\n\n```\n\n\n---\n#### ***Approach 3***\n1. **Sort the Input Array:**\n\n - The function starts by sorting the `nums` array in non-decreasing order. Sorting is essential for implementing the sliding window technique efficiently.\n1. **Sliding Window Approach:**\n\n - The algorithm employs a sliding window approach to find the maximum frequency.\n - It uses pointers `i` and `j` to define a window where the elements can be adjusted by at most `k` operations.\n - `kk` keeps track of the remaining operations available.\n1. **Calculating Frequency:**\n\n - For each `i`, it calculates the total difference required to make the elements within the window equal.\n - The difference is subtracted from `kk`, and the window is adjusted accordingly until `kk` is non-negative.\n1. **Updating Maximum Frequency:**\n\n - At each step, it updates `maxlen` with the maximum window size encountered so far.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n# Code\n```C++ []\nclass Solution {\npublic:\n int maxFrequency(vector<int>& nums, int k) {\n int n = nums.size();\n // Sort the input array in non-decreasing order\n sort(nums.begin(), nums.end());\n int maxlen = 1; // Variable to store the maximum frequency\n\n // Use long long for the operations involving k to prevent overflow\n long long kk = k;\n\n int j = 0; // Left pointer of the sliding window\n\n // Loop through the array starting from the second element\n for (int i = 1; i < n; ++i) {\n // Calculate the total difference needed to make the elements in the window equal\n kk -= static_cast<long long>(nums[i] - nums[i - 1]) * (i - j);\n\n // Adjust the window by moving the left pointer as needed\n while (kk < 0) {\n kk += nums[i] - nums[j];\n ++j;\n }\n\n // Update the maxlen with the maximum window size\n maxlen = max(maxlen, i - j + 1);\n }\n\n return maxlen; // Return the maximum frequency\n }\n};\n\n```\n```C []\n\n\nint maxFrequency(int* nums, int numsSize, int k) {\n // Sort the input array in non-decreasing order\n qsort(nums, numsSize, sizeof(int), cmpfunc);\n int maxlen = 1; // Variable to store the maximum frequency\n\n // Use long long for the operations involving k to prevent overflow\n long long kk = k;\n\n int j = 0; // Left pointer of the sliding window\n\n // Loop through the array starting from the second element\n for (int i = 1; i < numsSize; ++i) {\n // Calculate the total difference needed to make the elements in the window equal\n kk -= (long long)(nums[i] - nums[i - 1]) * (i - j);\n\n // Adjust the window by moving the left pointer as needed\n while (kk < 0) {\n kk += nums[i] - nums[j];\n ++j;\n }\n\n // Update the maxlen with the maximum window size\n maxlen = maxlen > (i - j + 1) ? maxlen : (i - j + 1);\n }\n\n return maxlen; // Return the maximum frequency\n}\n\nint cmpfunc(const void* a, const void* b) {\n return (*(int*)a - *(int*)b);\n}\n\n```\n```java []\n\n\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n Arrays.sort(nums);\n int maxlen = 1;\n long kk = k;\n int j = 0;\n\n for (int i = 1; i < nums.length; ++i) {\n kk -= (long)(nums[i] - nums[i - 1]) * (i - j);\n while (kk < 0) {\n kk += nums[i] - nums[j];\n j++;\n }\n\n maxlen = Math.max(maxlen, i - j + 1);\n }\n\n return maxlen;\n }\n}\n\n```\n```python3 []\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n maxlen = 1\n kk = k\n j = 0\n\n for i in range(1, len(nums)):\n kk -= (nums[i] - nums[i - 1]) * (i - j)\n while kk < 0:\n kk += nums[i] - nums[j]\n j += 1\n\n maxlen = max(maxlen, i - j + 1)\n\n return maxlen\n\n```\n```javascript []\nvar maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b);\n let maxlen = 1;\n let kk = k;\n let j = 0;\n\n for (let i = 1; i < nums.length; ++i) {\n kk -= (nums[i] - nums[i - 1]) * (i - j);\n\n while (kk < 0) {\n kk += nums[i] - nums[j];\n ++j;\n }\n\n maxlen = Math.max(maxlen, i - j + 1);\n }\n\n return maxlen;\n};\n\n```\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
95,072
Longest Substring Of All Vowels in Order
longest-substring-of-all-vowels-in-order
A string is considered beautiful if it satisfies the following conditions: For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful. Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0. A substring is a contiguous sequence of characters in a string.
String,Sliding Window
Medium
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
1,279
10
\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = "aeiou"\n ans = 0\n cnt = prev = -1 \n for i, x in enumerate(word): \n curr = vowels.index(x)\n if cnt >= 0: # in the middle of counting \n if 0 <= curr - prev <= 1: \n cnt += 1\n if x == "u": ans = max(ans, cnt)\n elif x == "a": cnt = 1\n else: cnt = -1 \n elif x == "a": cnt = 1\n prev = curr \n return ans \n```\n\nAlternative implementations\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n ans = 0\n cnt = unique = 1\n for i in range(1, len(word)): \n if word[i-1] <= word[i]: \n cnt += 1\n if word[i-1] < word[i]: unique += 1\n else: cnt = unique = 1\n if unique == 5: ans = max(ans, cnt)\n return ans \n```\n\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n ans = ii = 0\n unique = 1\n for i in range(1, len(word)): \n if word[i-1] > word[i]: \n ii = i \n unique = 1\n elif word[i-1] < word[i]: unique += 1\n if unique == 5: ans = max(ans, i-ii+1)\n return ans \n```
95,088
Longest Substring Of All Vowels in Order
longest-substring-of-all-vowels-in-order
A string is considered beautiful if it satisfies the following conditions: For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful. Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0. A substring is a contiguous sequence of characters in a string.
String,Sliding Window
Medium
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
571
6
```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n d = {}\n d[\'a\'] = {\'a\', \'e\'}\n d[\'e\'] = {\'e\', \'i\'}\n d[\'i\'] = {\'i\', \'o\'}\n d[\'o\'] = {\'o\', \'u\'}\n d[\'u\'] = {\'u\'}\n\t\t\n res, stack = 0, []\n for c in word: \n # If stack is empty, the first char must be \'a\'\n if len(stack) == 0:\n if c == \'a\':\n stack.append(c)\n continue \n \n # If stack is NOT empty,\n # input char should be the same or subsequent to the last char in stack\n # e.g., last char in stack is \'a\', next char should be \'a\' or \'e\'\n # e.g., last char in stack is \'e\', next char should be \'e\' or \'i\'\n # ...\n # e.g., last char in stack is \'u\', next char should be \'u\'\n if c in d[stack[-1]]:\n stack.append(c)\n # If the last char in stack is eventually \'u\', \n # then we have one beautiful substring as candidate, \n # where we record and update max length of beautiful substring (res)\n if c == \'u\':\n res = max(res, len(stack))\n else:\n stack = [] if c != \'a\' else [\'a\']\n \n return res\n```
95,091
Longest Substring Of All Vowels in Order
longest-substring-of-all-vowels-in-order
A string is considered beautiful if it satisfies the following conditions: For example, strings "aeiou" and "aaaaaaeiiiioou" are considered beautiful, but "uaeio", "aeoiu", and "aaaeeeooo" are not beautiful. Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0. A substring is a contiguous sequence of characters in a string.
String,Sliding Window
Medium
Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring.
882
9
```\nfrom itertools import groupby\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n arr = groupby(word)\n \n ans = []\n \n count = 0\n \n for i , j in arr:\n ans.append([i , list(j)])\n \n for i in range(len(ans) - 4):\n if(ans[i][0] == \'a\' and ans[i + 1][0] == \'e\' and ans[i + 2][0] == \'i\' and ans[i + 3][0] == \'o\' and ans[i + 4][0] == \'u\'):\n count = max(count , len(ans[i][1]) + len(ans[i + 1][1]) + len(ans[i + 2][1]) + len(ans[i + 3][1]) + len(ans[i + 4][1])) \n \n \n return count\n```
95,094
Sorting the Sentence
sorting-the-sentence
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence. Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.
String,Sorting
Easy
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
1,192
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKind of searching and sorting question, but easier one as you are only asked to sort 9 numbers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor all 1 to 9 numbers, search for the word consisting the integer and append it to output string.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(1) constant. At most we will loop 81 times, since length of string is maximum 9 words.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nDepends on string. O(len(s)) depends on length of string\n\n# Code\n```\nclass Solution(object):\n def sortSentence(self, s):\n """\n :type s: str\n :rtype: str\n\n Runtime complexity: O(1) constant\n Memory complexity: O(len(s)) depends on length of string\n\n """\n output = ""\n sarray = s.split()\n\n # Loop through all 9 possible position words\n for i in range(1, 10):\n\n # Find ith position word in string\n for word in sarray:\n\n # Insert word to output string\n if word[-1] == str(i):\n output += " " + word[:-1]\n\n return output.strip()\n\n\n\n\n\n\n```
95,208
Incremental Memory Leak
incremental-memory-leak
You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes. Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.
Simulation
Medium
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
3,538
44
Since I didn\'t realize during the contest that the simple brute-force passed all the tests - came up with an O(1) solution. Let\'s assume that the first memory stick is larger than the second one. If it\'s not the case - we can always re-assign variables. \n\nThen we have 2 stages:\n* Memory is used from the first stick until it becomes smaller than the second one. \n* Then memory is used sequentially from: 2nd stick, 1st stick, 2nd stick, 1st stick... \n\nFor each stage the amount of memory removed is a sum of an arithmetic sequence. With step d=1 for the first stage and d=2 for the second one. So to get the number of steps in each stage we have to solve quadratic equations.\n```\nn**2 + i*n = x\n```\nThis is done using a helper function:\n```\ndef solve_quadratic(i,x):\n return floor( (-i + sqrt(i**2+4*x))/2 )\n```\n \nThe full solution is then:\n\n```\n\nclass Solution:\n def memLeak(self, memory1: int, memory2: int) -> List[int]:\n \n inverted = False \n if memory2>memory1:\n memory2, memory1 = memory1, memory2\n inverted = True \n\n\t\t#Compute the number of steps in first stage - 1\n i_start = solve_quadratic(1,2*(memory1-memory2))\n \n\t\t#Memory1 after the end of first stage is computed using the sum of arithmetic sequence\n memory1-= i_start*(i_start+1)//2\n\t\t\n\t\tif memory1 == memory2: #Special case (if we end up with equal numbers after stage - 1 - undo inversion)\n inverted = False \n \n #Compute number of steps in stage - 2\n n_end = solve_quadratic((i_start+1), memory2)\n \n\t\t#Compute sums of respective arithmetic sequences\n i_end_1 = i_start - 1 + 2*n_end\n i_end_2 = i_start + 2*n_end\n \n sum1 = n_end * (i_start+1 + i_end_1)//2\n sum2 = n_end * (i_start+2 + i_end_2)//2\n \n\t\t#Compute updated memories \n memory1-=sum1\n memory2-=sum2\n \n full_cnt=2*n_end+i_start\n \n if memory1>=i_end_2+1: #If we can still make one removal from the first stick - perform it.\n memory1-=(i_end_2+1)\n full_cnt+=1\n \n return [full_cnt+1, memory2, memory1] if inverted else [full_cnt+1, memory1, memory2]\n \n\t\t ```
95,228
Incremental Memory Leak
incremental-memory-leak
You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second. At the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes. Return an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.
Simulation
Medium
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
2,652
29
**Java**\n\n```\nclass Solution {\n public int[] memLeak(int memory1, int memory2) {\n int i = 1;\n while(Math.max(memory1, memory2) >= i){\n if(memory1 >= memory2)\n memory1 -= i;\n else\n memory2 -= i;\n i++;\n }\n return new int[]{i, memory1, memory2};\n }\n}\n```\n\n**C++**\n```\nclass Solution {\npublic:\n vector<int> memLeak(int memory1, int memory2) {\n int i = 1;\n while(max(memory1, memory2) >= i){\n if(memory1 >= memory2)\n memory1 -= i;\n else\n memory2 -= i;\n i++;\n }\n return {i, memory1, memory2};\n }\n};\n```\n\n**Python**\n```\nclass Solution:\n def memLeak(self, memory1: int, memory2: int) -> List[int]:\n i = 1\n while max(memory1, memory2) >= i:\n if memory1 >= memory2:\n memory1 -= i\n else:\n memory2 -= i\n i += 1\n return [i, memory1, memory2]\n```\n\n```\nclass Solution:\n def memLeak(self, m1: int, m2: int) -> List[int]:\n res = [1,m1,m2]\n while 1:\n if res[2] > res[1]:\n mx = 2\n else:\n mx = 1\n if res[0] > res[mx]:\n return res\n else:\n res[mx] -= res[0]\n res[0]+=1\n```
95,229