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
Rotating the Box
rotating-the-box
You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following: The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions. It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box. Return an n x m matrix representing the box after the rotation described above.
Array,Two Pointers,Matrix
Medium
Rotate the box using the relation rotatedBox[i][j] = box[m - 1 - j][i]. Start iterating from the bottom of the box and for each empty cell check if there is any stone above it with no obstacles between them.
658
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe solution first performs a clockwise rotation of the \'box\' by assigning the values from the original matrix box to the new matrix \'res\' in the rotated positions.\n\nNext, the solution iterates through each column of the \'res\' matrix from bottom to top. By keeping track of the start index, the solution simulates gravity by moving stones downwards until they encounter an obstacle or another stone. This is done by swapping the positions of stones and empty spaces in each column.\n\nThe resulting \'res\' matrix represents the \'box\' after the rotation and gravity simulation.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a new matrix res with dimensions n x m to store the rotated box.\n\n2. Iterate through each cell of the original box matrix. For each cell at index (i, j), assign its value to the corresponding cell in the res matrix at index (i, m-1-j). This step performs the clockwise rotation of the box.\n\n3. Iterate through each column of the res matrix and simulate the effect of gravity on the stones. Start from the bottom of each column and move upwards. Keep track of the index start, which represents the position where the next stone should fall.\n\n4. If the current cell contains an obstacle \'*\', update the start index to j-1 to prevent stones from falling further.\n\n5. If the current cell contains a stone \'#\', update the current cell to \'.\', indicating that the stone has fallen, and assign the value \'#\' to the cell at index (start--, i). Decrementing start ensures that the next stone will fall on top of the previous one.\n\n6. Return the resulting res matrix, which represents the box after the rotation and gravity simulation.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(m * n), where m is the number of rows in the box matrix and n is the number of columns.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n The space complexity is O(m * n) as well, as we use an auxiliary space for keeping the result.\n\n---\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {\n int m = box.size();\n int n = box[0].size();\n\n vector<vector<char>> res(n, vector<char>(m));\n // Trasposing the matrix\n for (int i = 0; i < n; i++) {\n for (int j = m - 1; j >= 0; j--) {\n res[i][m - 1 - j] = box[j][i];\n }\n }\n // Applying the gravity\n for (int i = 0; i < m; i++) {\n int start = n - 1;\n for (int j = start; j >= 0; j--) {\n if (res[j][i] == \'*\') {\n start = j - 1;\n } else if (res[j][i] == \'#\') {\n res[j][i] = \'.\';\n res[start][i] = \'#\';\n start--;\n }\n }\n }\n return res;\n }\n};\n\n```\n```python3 []\nclass Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n m, n = len(box), len(box[0])\n\n res = [[\'\'] * m for _ in range(n)]\n # Transposing\n for i in range(n):\n for j in range(m - 1, -1, -1):\n res[i][m - 1 - j] = box[j][i]\n # Applying Gravity\n for i in range(m):\n start = n - 1\n for j in range(start, -1, -1):\n if res[j][i] == \'*\':\n start = j - 1\n elif res[j][i] == \'#\':\n res[j][i] = \'.\'\n res[start][i] = \'#\'\n start -= 1\n\n return res\n\n```\n
95,283
Rotating the Box
rotating-the-box
You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following: The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions. It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box. Return an n x m matrix representing the box after the rotation described above.
Array,Two Pointers,Matrix
Medium
Rotate the box using the relation rotatedBox[i][j] = box[m - 1 - j][i]. Start iterating from the bottom of the box and for each empty cell check if there is any stone above it with no obstacles between them.
2,976
13
**First**, move every stone to the right, (or you can rotate the box first and then drop stones. Both as fine).\nThe current location of stone does not matter. \nWe only need to remember how many stones each interval (seperated by obstacles) has, \nand place the stones before the first seeing obstacle.\n\n**Second**, rotate the box. Same as **Leetcode problem # 48 Rotate Image**. \n```\nclass Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n # move stones to right, row by row\n for i in range(len(box)):\n stone = 0\n for j in range(len(box[0])):\n if box[i][j] == \'#\': # if a stone\n stone += 1\n box[i][j] = \'.\'\n elif box[i][j] == \'*\': # if a obstacle\n for m in range(stone):\n box[i][j-m-1] = \'#\'\n stone = 0\n # if reaches the end of j, but still have stone\n if stone != 0:\n for m in range(stone):\n box[i][j-m] = \'#\'\n \n # rotate box, same as leetcode #48\n box[:] = zip(*box[::-1])\n \n return box\n```
95,285
Minimum Distance to the Target Element
minimum-distance-to-the-target-element
Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x. Return abs(i - start). It is guaranteed that target exists in nums.
Array
Easy
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
730
13
\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n ans = inf\n for i, x in enumerate(nums): \n if x == target: \n ans = min(ans, abs(i - start))\n return ans \n```
95,345
Minimum Distance to the Target Element
minimum-distance-to-the-target-element
Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x. Return abs(i - start). It is guaranteed that target exists in nums.
Array
Easy
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
529
5
Just in case, this code may be explained well for beginners.\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n a = []\n for i in range(len(nums)):\n if nums[i]==target:\n a.append(abs(start-i))\n return min(a)\n```
95,351
Splitting a String Into Descending Consecutive Values
splitting-a-string-into-descending-consecutive-values
You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1. Return true if it is possible to split s​​​​​​ as described above, or false otherwise. A substring is a contiguous sequence of characters in a string.
String,Backtracking
Medium
One solution is to try all possible splits using backtrack Look out for trailing zeros in string
2,703
19
\u2714\uFE0F ***Solution***\n\nWe need to iterate over all possible substrings for each splits. \n\nIf a split gives value equal to **`previous split - 1`**, then continue trying to split for remaining index. Otherwise, try increasing the length of split and check again.\n\nIf you reach the last index and there are more than 1 splits, return true. Otherwise return false.\n\n**C++**\n\nFor C++, you need to handle overflows . For this purpose, I have use *`try...catch`* block in the below solution -\n\n```\nbool splitString(string s) {\n\treturn solve(s, 0, 1, -1);\n}\nbool solve(string& s, int i, int len, long prev, int splits = 0) {\n\t// If we reach the end of string and have made splits >= 2, return true\n\tif(i == size(s) && splits >= 2) return true;\n\twhile(i + len <= size(s)) {\n\t\ttry{\n\t\t\tauto cur = stoll(s.substr(i, len++)); // convert s[i] to s[i + len] into number\n\t\t\tif(prev != -1 && cur != prev - 1) continue; // and check if it is equal to prev - 1 (ignore for first call)\n\t\t\t// if the above condition satisfies, just recurse for the remaining indices\n\t\t\tif(solve(s, i + len - 1, 1, cur, splits + 1)) return true; \n\t\t} catch(...) { continue; } // handling overflows\n\t}\n\treturn false; \n}\n```\n\n---\n\n**Python**\n```\ndef splitString(self, s: str) -> bool:\n\tdef solve(s, i, length, prev, splits):\n\t\t# At last, if you reach the end and have made splits >= 2, we are sure that a split as per requirement is possible\n\t\tif i == len(s) and splits >= 2: \n\t\t\treturn True\n\t\twhile i + length <= len(s):\n\t\t\tcur = int(s[i:i+length]) # convert s[i:i + length] to integer\n\t\t\tlength += 1\n\t\t\t# if above converted integer is not equal to prev - 1, try increasing the length\n\t\t\tif prev != -1 and cur != prev - 1: continue \n\t\t\t# if it is equal to prev - 1, recurse and make splits for remaining index\n\t\t\tif solve(s, i + length - 1, 1, cur, splits + 1):\n\t\t\t\treturn True\n\t\treturn False\n\treturn solve(s, 0, 1, -1, 0)\n```\n\n\n---\n---\n\n\uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47 \n\n---\n---
95,383
Splitting a String Into Descending Consecutive Values
splitting-a-string-into-descending-consecutive-values
You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1. Return true if it is possible to split s​​​​​​ as described above, or false otherwise. A substring is a contiguous sequence of characters in a string.
String,Backtracking
Medium
One solution is to try all possible splits using backtrack Look out for trailing zeros in string
656
5
```\ndef splitString(self, s):\n\n\tdef dfs(start, last):\n\t\tres = False\n\t\tfor k in range(1, len(s)-last+1):\n\t\t\tif (int(s[start:last])-int(s[last:last+k])) == 1:\n\t\t\t\tif dfs(last, last+k):\n\t\t\t\t\treturn True\n\t\t\t\tres = True\n\t\t\telse:\n\t\t\t\tres = False\n\t\treturn res\n\n\tfor i in range(1, len(s)):\n\t\tif dfs(0, i):\n\t\t\treturn True\n\t\t\t\n\treturn False\n```
95,386
Splitting a String Into Descending Consecutive Values
splitting-a-string-into-descending-consecutive-values
You are given a string s that consists of only digits. Check if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1. Return true if it is possible to split s​​​​​​ as described above, or false otherwise. A substring is a contiguous sequence of characters in a string.
String,Backtracking
Medium
One solution is to try all possible splits using backtrack Look out for trailing zeros in string
533
6
This solution adds a default paramater to the given function to avoid having to define a dfs function inside the existing function.\n\n```python\nclass Solution:\n def splitString(self, s: str, last_val: int = None) -> bool:\n # Base case, remaining string is a valid solution\n if last_val and int(s) == last_val - 1:\n return True\n\n\t\t# Iterate through increasingly larger slices of s\n for i in range(1, len(s)):\n cur = int(s[:i])\n\t\t\t# If current slice is equal to last_val - 1, make\n\t\t\t# recursive call with remaining string and updated last_val\n if last_val is None or cur == last_val - 1:\n if self.splitString(s[i:], cur):\n return True\n\n return False\n```
95,393
Minimum Interval to Include Each Query
minimum-interval-to-include-each-query
You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1. Return an array containing the answers to the queries.
Array,Binary Search,Line Sweep,Sorting,Heap (Priority Queue)
Hard
Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?
829
5
## IDEA:\n\uD83D\uDC49 *Sort the intervals by size and the queries in increasing order, then iterate over the intervals.\n\uD83D\uDC49 For each interval (left, right) binary search for the queries (q) that are contained in the interval (left <= q <= right), pop them from the array queries and insert them in the array answers (with size = right - left +1).\n\uD83D\uDC49 Since you\'re looking at the interval from the smallest to the largest, the first answer found is correct.*\n\'\'\'\n\n\tclass Solution:\n def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:\n \n intervals.sort(key = lambda x:x[1]-x[0])\n q = sorted([qu,i] for i,qu in enumerate(queries))\n res=[-1]*len(queries)\n\t\t\n for left,right in intervals:\n ind = bisect.bisect(q,[left])\n while ind<len(q) and q[ind][0]<=right:\n res[q.pop(ind)[1]]=right-left+1\n return res\n\t\t\nFeel free to ask if you have any doubt. \uD83E\uDD17\n**Thanku** and do **Upvote** if you got any help !!\uD83E\uDD1E
95,458
Minimum Adjacent Swaps to Reach the Kth Smallest Number
minimum-adjacent-swaps-to-reach-the-kth-smallest-number
You are given a string num, representing a large integer, and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones. Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer. The tests are generated in such a way that kth smallest wonderful integer exists.
Two Pointers,String,Greedy
Medium
Find the next permutation of the given string k times. Try to move each element to its correct position and calculate the number of steps.
1,444
7
\n```\nclass Solution:\n def getMinSwaps(self, num: str, k: int) -> int:\n num = list(num)\n orig = num.copy()\n \n for _ in range(k): \n for i in reversed(range(len(num)-1)): \n if num[i] < num[i+1]: \n ii = i+1 \n while ii < len(num) and num[i] < num[ii]: ii += 1\n num[i], num[ii-1] = num[ii-1], num[i]\n lo, hi = i+1, len(num)-1\n while lo < hi: \n num[lo], num[hi] = num[hi], num[lo]\n lo += 1\n hi -= 1\n break \n \n ans = 0\n for i in range(len(num)): \n ii = i\n while orig[i] != num[i]: \n ans += 1\n ii += 1\n num[i], num[ii] = num[ii], num[i]\n return ans \n```
95,482
Maximum Population Year
maximum-population-year
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. Return the earliest year with the maximum population.
Array,Counting
Easy
For each year find the number of people whose birth_i ≤ year and death_i > year. Find the maximum value between all years.
5,461
85
```\nclass Solution:\n def maximumPopulation(self, logs: List[List[int]]) -> int:\n dates = []\n for birth, death in logs:\n dates.append((birth, 1))\n dates.append((death, -1))\n \n dates.sort()\n\n population = max_population = max_year = 0\n for year, change in dates:\n population += change\n if population > max_population:\n max_population = population\n max_year = year\n \n return max_year\n```
95,528
Maximum Population Year
maximum-population-year
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. Return the earliest year with the maximum population.
Array,Counting
Easy
For each year find the number of people whose birth_i ≤ year and death_i > year. Find the maximum value between all years.
3,987
35
### Steps\n1. For each log, update an array which stores the population changes in each year. The first index corresponds to the year 1950, and the last to the year 2050. \n1. Then, iterate through the years while updating the running sum, max population and year of that max population.\n1. Return that year.\n\n```\nclass Solution:\n def maximumPopulation(self, logs: List[List[int]]) -> int:\n # the timespan 1950-2050 covers 101 years\n\t\tdelta = [0] * 101\n\n\t\t# to make explicit the conversion from the year (1950 + i) to the ith index\n conversionDiff = 1950 \n\t\t\n for l in logs:\n\t\t\t# the log\'s first entry, birth, increases the population by 1\n delta[l[0] - conversionDiff] += 1 \n\t\t\t\n\t\t\t# the log\'s second entry, death, decreases the population by 1\n delta[l[1] - conversionDiff] -= 1\n \n runningSum = 0\n maxPop = 0\n year = 1950\n\t\t\n\t\t# find the year with the greatest population\n for i, d in enumerate(delta):\n runningSum += d\n\t\t\t\n\t\t\t# since we want the first year this population was reached, only update if strictly greater than the previous maximum population\n if runningSum > maxPop:\n maxPop = runningSum\n year = conversionDiff + i\n\t\t\t\t\n return year\n```\n\nThis idea works because we have a limited number of years (101) to track. If this number were higher, we could instead sort then iterate, for an O(nlogn) complexity with O(n) memory solution.
95,536
Maximum Population Year
maximum-population-year
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. Return the earliest year with the maximum population.
Array,Counting
Easy
For each year find the number of people whose birth_i ≤ year and death_i > year. Find the maximum value between all years.
1,105
5
```\nclass Solution:\n def maximumPopulation(self, logs: List[List[int]]) -> int:\n a,n=[0]*101,len(logs)\n for birth,death in logs:\n a[birth-1950]+=1\n a[death-1950]-=1\n c=m=year=0\n for i in range(101):\n c+=a[i]\n if c>m:\n m=c\n year=i+1950\n return year\n```\n\n**An upvote will be encouraging**
95,542
Maximum Population Year
maximum-population-year
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. Return the earliest year with the maximum population.
Array,Counting
Easy
For each year find the number of people whose birth_i ≤ year and death_i > year. Find the maximum value between all years.
875
7
```\nclass Solution(object):\n def maximumPopulation(self, logs):\n """\n :type logs: List[List[int]]\n :rtype: int\n """\n\t\tbirth_years = sorted([i[0] for i in logs])\n\t\tmax_pop = 0\n\t\toutput = 0\n\n\t\tfor year in birth_years: #It can be easily proved that the answer would be one of the birth years. So we do not need to go over the whole range of years!\n\t\t\tpopulation= 0\n\t\t\tfor dates in logs:\n\t\t\t\tif dates[0]<=year and dates[1]>year: #If the person is born before or the same year, and died after this year\n\t\t\t\t\tpopulation+=1\n\n\t\t\tif population>max_pop:\n\t\t\t\toutput = year\n\t\t\t\tmax_pop = population\n\n\t\treturn output\n```
95,561
Maximum Population Year
maximum-population-year
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. Return the earliest year with the maximum population.
Array,Counting
Easy
For each year find the number of people whose birth_i ≤ year and death_i > year. Find the maximum value between all years.
3,426
9
### Decode the problem\nBeneath the contex of the problem, we are basically given a list of ranges on an axis and we are asked to find the smallest integer with the maximum number of overlapping ranges. This is a populate question pattern. One of the most famous problems is meeting room II: \n\n--- \n\n### Understand the alghorithm\n\nSo how do we approach this kind of problems? We use an alghorithm called [sweep line](). It is more commonly used in computational geometry processing. But the idea holds same here: We are processing all the range edges in a sorted manner and track the state of our interest.\n\nIn the first for loop, we are iterating all the ranges given. And we use an `popluation` array to represent the axis. We are basically doing bucket sort here so all the starting and ending integers will be arranged in sorted order when we iterate it later. Additionally, we are also increment the count when we see starting integer and decrement count when we see ending integer. What we are really repesent here is how many ranges starts / ends at this given year, which is the state of our interest.\n\n*Note in this problem, the range only exist between 1950 - 2050. And most ranges should be in contious fasion. So it makes a lot sense to just do bucket sort. In an open end range problem (imagine there is no limitation of years here) we will need to break up the start and end integers, group them and sort them, which usually requires O(nlogn) time complexity. Otherwise, we will waste a lot of idle meomories just for the bucket sort.*\n\nNow in the second for loop, we are iterating the axis and update the current populations by adding/substracting the # of ranges starts/ends at all the given year. And we just need to keep track of the max Population we got.\n\n##### Time complexity: O(n)\n\n--- \n\n### Full Implementation\n```\nclass Solution(object):\n def maximumPopulation(self, logs):\n """\n :type logs: List[List[int]]\n :rtype: int\n """\n totalYears = 2050 - 1950 + 1\n population = [0] * totalYears\n \n for log in logs:\n birthYear = log[0]\n deathYear = log[1]\n population[birthYear - 1950] += 1\n population[deathYear - 1950] -= 1\n \n currPop = maxPop = result = 0\n for year in range(totalYears):\n currPop += population[year]\n if currPop > maxPop:\n maxPop = currPop\n result = year\n \n return result + 1950\n``` \n
95,562
Maximum Population Year
maximum-population-year
You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person. The population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die. Return the earliest year with the maximum population.
Array,Counting
Easy
For each year find the number of people whose birth_i ≤ year and death_i > year. Find the maximum value between all years.
1,503
9
\n```\nclass Solution:\n def maximumPopulation(self, logs: List[List[int]]) -> int:\n vals = []\n for x, y in logs: \n vals.append((x, 1))\n vals.append((y, -1))\n ans = prefix = most = 0\n for x, k in sorted(vals): \n prefix += k\n if prefix > most: \n ans = x\n most = prefix \n return ans \n```
95,565
Maximum Distance Between a Pair of Values
maximum-distance-between-a-pair-of-values
You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​. Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.
Array,Two Pointers,Binary Search,Greedy
Medium
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1]
8,369
141
Since our arrays are sorted, we can advance `i` while `n1[i]` is bigger than `n2[j]`, and increment `j` otherwise.\n\n**Java**\n```java\npublic int maxDistance(int[] n1, int[] n2) {\n int i = 0, j = 0, res = 0;\n while (i < n1.length && j < n2.length)\n if (n1[i] > n2[j])\n ++i;\n else\n res = Math.max(res, j++ - i);\n return res;\n}\n```\n**C++**\n```cpp\nint maxDistance(vector<int>& n1, vector<int>& n2) {\n int i = 0, j = 0, res = 0;\n while (i < n1.size() && j < n2.size())\n if (n1[i] > n2[j])\n ++i;\n else\n res = max(res, j++ - i);\n return res;\n}\n```\n**Python 3**\n```python\nclass Solution:\n def maxDistance(self, n1: List[int], n2: List[int]) -> int:\n i = j = res = 0\n while i < len(n1) and j < len(n2):\n if n1[i] > n2[j]:\n i += 1\n else:\n res = max(res, j - i)\n j += 1\n return res\n```
95,578
Maximum Distance Between a Pair of Values
maximum-distance-between-a-pair-of-values
You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​. Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.
Array,Two Pointers,Binary Search,Greedy
Medium
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1]
458
6
```\nclass Solution:\n def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:\n length1, length2 = len(nums1), len(nums2)\n i,j = 0,0\n \n result = 0\n while i < length1 and j < length2:\n if nums1[i] > nums2[j]:\n i+=1\n else:\n result = max(result,j-i)\n j+=1\n \n return result\n```
95,588
Maximum Distance Between a Pair of Values
maximum-distance-between-a-pair-of-values
You are given two non-increasing 0-indexed integer arrays nums1​​​​​​ and nums2​​​​​​. A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i​​​​. Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0. An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.
Array,Two Pointers,Binary Search,Greedy
Medium
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1]
891
13
**O ( N LOG N ) \n BINARY SEARCH in C++**\n\n```\nclass Solution {\npublic:\nint maxDistance(vector<int>& n1, vector<int>& n2) {\n\n int ans=0,k=min(n1.size(),n2.size());\n for(int i=0; i<k;i++){\n int l=i,r=n2.size()-1,m;\n while(l<=r){\n m=l+(r-l)/2;\n int t= n1[i];\n if(n2[m]>=t){\n l=m+1;\n if(m-i>ans)ans=m-i;\n } \n else r=m-1;\n } \n }\n return ans;\n }\n};\n```\n\n\n**O ( N ) in PYTHON**\n```\nclass Solution:\n def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:\n i=0\n j=0\n k=0\n while j<len(nums2):\n while i<len(nums1) and nums1[i]>nums2[j]:\n i+=1\n if (i<len(nums1)):\n k=max(k,j-i)\n j+=1\n if i==len(nums1):\n break\n return k\n```\n\n**O ( N ) in C++**\n```\nclass Solution {\npublic:\n int maxDistance(vector<int>& nums1, vector<int>& nums2) {\n int i=0;\n int j=0;\n int k=0;\n while (j<nums2.size()){\n while (i<nums1.size() && nums1[i]>nums2[j]){\n i++;\n }\n k = max(k,j-i);\n j++;\n if (i>=nums1.size()){\n break;\n }\n }\n return k;\n }\n};\n```\n![image]()\n
95,590
Maximum Subarray Min-Product
maximum-subarray-min-product
The min-product of an array is equal to the minimum value in the array multiplied by the array's sum. Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7. Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer. A subarray is a contiguous part of an array.
Array,Stack,Monotonic Stack,Prefix Sum
Medium
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
997
8
This is a intuition of the process\n- We iterate from the largest number to the smallest number.\n- At every iteration, if the adjacent number(s) is larger than the current number, merge it with the adjacent group(s).\n- After every merge, we update the sum of the group and the minimum value of the group. We update the result if applicable.\n\nWe use a disjoint set union to track the group membership. You can get the disjoint set union template from elsewhere.\n\nWe use another dictionary to track the current sum of each group.\n\n```python\nclass DisjointSet:\n # github.com/not522/ac-library-python/blob/master/atcoder/dsu.py\n\n def __init__(self, n: int = 0) -> None:\n self._n = n\n self.parent_or_size = [-1]*n\n\n def union(self, a: int, b: int) -> int:\n x = self.find(a)\n y = self.find(b)\n\n if x == y:\n return x\n\n if -self.parent_or_size[x] < -self.parent_or_size[y]:\n x, y = y, x\n\n self.parent_or_size[x] += self.parent_or_size[y]\n self.parent_or_size[y] = x\n\n return x\n\n def find(self, a: int) -> int:\n parent = self.parent_or_size[a]\n while parent >= 0:\n if self.parent_or_size[parent] < 0:\n return parent\n self.parent_or_size[a], a, parent = (\n self.parent_or_size[parent],\n self.parent_or_size[parent],\n self.parent_or_size[self.parent_or_size[parent]]\n )\n\n return a\n\n def size(self, a: int) -> int:\n return -self.parent_or_size[self.leader(a)]\n\n\nclass Solution:\n def maxSumMinProduct(self, nums: List[int]) -> int:\n \n # we begin from the largest number to the smallest number\n nums = [0] + nums + [0]\n pos = [(x,i) for i,x in enumerate(nums)]\n pos.sort()\n pos.reverse()\n \n # we track the result with this variable\n maxres = 0\n \n # we track the membership of each element\n # d.find(x) == d.find(y) if x and y are in the same group\n d = DisjointSet(len(nums))\n\n # we track the current sum of each group with a dictionary\n # map group_id (which may change over time) to the sum\n segsums = {}\n \n # iterate from the largest to the smallest number and index\n # excluding the two zeros padded at the ends\n for x,i in pos[:-2]:\n minval = x # current value is minimum since we iterate from large to small\n segsum = x\n \n # if the left element is larger\n if nums[i-1] > nums[i]: \n idx = d.find(i-1) # get group index\n segsum += segsums[idx] # include sum of adjacent group\n d.union(i, i-1) # combine groups\n \n # equality because we iterate with decreasing index as well\n if nums[i+1] >= nums[i]:\n idx = d.find(i+1)\n segsum += segsums[idx]\n d.union(i, i+1)\n \n # update sum of group\n segsums[d.find(i)] = segsum \n \n # update the result\n maxres = max(maxres, minval*segsum)\n \n # remember to take modulo\n return maxres%(10**9+7)\n```\n\nThe algorithm runs in O(n log n) due to the sorting.
95,653
Maximum Subarray Min-Product
maximum-subarray-min-product
The min-product of an array is equal to the minimum value in the array multiplied by the array's sum. Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7. Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer. A subarray is a contiguous part of an array.
Array,Stack,Monotonic Stack,Prefix Sum
Medium
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
880
12
\n```\nclass Solution:\n def maxSumMinProduct(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = 0 \n stack = []\n for i, x in enumerate(nums + [-inf]): # append "-inf" to force flush all elements\n while stack and stack[-1][1] >= x: \n _, xx = stack.pop()\n ii = stack[-1][0] if stack else -1 \n ans = max(ans, xx*(prefix[i] - prefix[ii+1]))\n stack.append((i, x))\n return ans % 1_000_000_007\n```
95,654
Maximum Subarray Min-Product
maximum-subarray-min-product
The min-product of an array is equal to the minimum value in the array multiplied by the array's sum. Given an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7. Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer. A subarray is a contiguous part of an array.
Array,Stack,Monotonic Stack,Prefix Sum
Medium
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
912
5
a monotonic stack with index and prefix sum\n\n```\nclass Solution:\n def maxSumMinProduct(self, nums: List[int]) -> int:\n mod=int(1e9+7)\n stack=[] # (index, prefix sum at index)\n rsum=0\n res=0\n \n nums.append(0)\n \n for i, v in enumerate(nums):\n while stack and nums[stack[-1][0]] >= v:\n index, _ = stack.pop()\n\t\t\t\t\n\t\t\t\t# if the stack is empty, the subarray sum is the current prefixsum\n arrSum=rsum\n \n if stack:\n arrSum=rsum-stack[-1][1]\n \n\t\t\t\t# update res with subarray sum\n res=max(res, nums[index]*arrSum)\n \n rsum+=v\n stack.append((i, rsum))\n \n return res%mod
95,664
Largest Color Value in a Directed Graph
largest-color-value-in-a-directed-graph
There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1. You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj. A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.
Hash Table,Dynamic Programming,Graph,Topological Sort,Memoization,Counting
Hard
Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)
11,802
120
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\r\n`Largest Color Value in a Directed Graph` by `Aryan Mittal`\r\n![lc.png]()\r\n\r\n\r\n\r\n# Approach & Intution\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n![image.png]()\r\n\r\n\r\n# Code\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n int largestPathValue(string colors, vector<vector<int>>& edges) {\r\n int n = colors.size();\r\n vector<int> indegrees(n, 0);\r\n vector<vector<int>> graph(n, vector<int>());\r\n for (vector<int>& edge : edges) {\r\n graph[edge[0]].push_back(edge[1]);\r\n indegrees[edge[1]]++;\r\n }\r\n queue<int> zero_indegree;\r\n for (int i = 0; i < n; i++) {\r\n if (indegrees[i] == 0) {\r\n zero_indegree.push(i);\r\n }\r\n }\r\n vector<vector<int>> counts(n, vector<int>(26, 0));\r\n for (int i = 0; i < n; i++) {\r\n counts[i][colors[i] - \'a\']++;\r\n }\r\n int max_count = 0;\r\n int visited = 0;\r\n while (!zero_indegree.empty()) {\r\n int u = zero_indegree.front();\r\n zero_indegree.pop();\r\n visited++;\r\n for (int v : graph[u]) {\r\n for (int i = 0; i < 26; i++) {\r\n counts[v][i] = max(counts[v][i], counts[u][i] + (colors[v] - \'a\' == i ? 1 : 0));\r\n }\r\n indegrees[v]--;\r\n if (indegrees[v] == 0) {\r\n zero_indegree.push(v);\r\n }\r\n }\r\n max_count = max(max_count, *max_element(counts[u].begin(), counts[u].end()));\r\n }\r\n return visited == n ? max_count : -1;\r\n }\r\n};\r\n```\r\n```Java []\r\nclass Solution {\r\n public int largestPathValue(String colors, int[][] edges) {\r\n int n = colors.length();\r\n int[] indegrees = new int[n];\r\n List<List<Integer>> graph = new ArrayList<>();\r\n for (int i = 0; i < n; i++) {\r\n graph.add(new ArrayList<Integer>());\r\n }\r\n for (int[] edge : edges) {\r\n graph.get(edge[0]).add(edge[1]);\r\n indegrees[edge[1]]++;\r\n }\r\n Queue<Integer> zeroIndegree = new LinkedList<>();\r\n for (int i = 0; i < n; i++) {\r\n if (indegrees[i] == 0) {\r\n zeroIndegree.offer(i);\r\n }\r\n }\r\n int[][] counts = new int[n][26];\r\n for (int i = 0; i < n; i++) {\r\n counts[i][colors.charAt(i) - \'a\']++;\r\n }\r\n int maxCount = 0;\r\n int visited = 0;\r\n while (!zeroIndegree.isEmpty()) {\r\n int u = zeroIndegree.poll();\r\n visited++;\r\n for (int v : graph.get(u)) {\r\n for (int i = 0; i < 26; i++) {\r\n counts[v][i] = Math.max(counts[v][i], counts[u][i] + (colors.charAt(v) - \'a\' == i ? 1 : 0));\r\n }\r\n indegrees[v]--;\r\n if (indegrees[v] == 0) {\r\n zeroIndegree.offer(v);\r\n }\r\n }\r\n maxCount = Math.max(maxCount, Arrays.stream(counts[u]).max().getAsInt());\r\n }\r\n return visited == n ? maxCount : -1;\r\n }\r\n}\r\n```\r\n```Python []\r\nfrom typing import List\r\nfrom collections import deque\r\n\r\nclass Solution:\r\n def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:\r\n n = len(colors)\r\n indegrees = [0] * n\r\n graph = [[] for _ in range(n)]\r\n for edge in edges:\r\n graph[edge[0]].append(edge[1])\r\n indegrees[edge[1]] += 1\r\n zero_indegree = deque()\r\n for i in range(n):\r\n if indegrees[i] == 0:\r\n zero_indegree.append(i)\r\n counts = [[0]*26 for _ in range(n)]\r\n for i in range(n):\r\n counts[i][ord(colors[i]) - ord(\'a\')] += 1\r\n max_count = 0\r\n visited = 0\r\n while zero_indegree:\r\n u = zero_indegree.popleft()\r\n visited += 1\r\n for v in graph[u]:\r\n for i in range(26):\r\n counts[v][i] = max(counts[v][i], counts[u][i] + (ord(colors[v]) - ord(\'a\') == i))\r\n indegrees[v] -= 1\r\n if indegrees[v] == 0:\r\n zero_indegree.append(v)\r\n max_count = max(max_count, max(counts[u]))\r\n return max_count if visited == n else -1\r\n```\r\n
95,713
Largest Color Value in a Directed Graph
largest-color-value-in-a-directed-graph
There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1. You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj. A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.
Hash Table,Dynamic Programming,Graph,Topological Sort,Memoization,Counting
Hard
Use topological sort. let dp[u][c] := the maximum count of vertices with color c of any path starting from vertex u. (by JerryJin2905)
4,185
28
# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\nThe problem asks us to find the longest path in the directed graph such that the path contains all the colors from the string in the same order as they appear in the string. We can use dynamic programming and topological sorting to solve this problem.\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\nWe can create a directed graph using the edges given in the input. We can use a list of lists to represent the adjacency list of the graph. We can also maintain an array of arrays to keep track of the count of each color in the path that ends at each vertex. We can use another array to keep track of the in-degree of each vertex in the graph. We can use a queue to perform the topological sort of the graph. We can start by adding all the vertices with zero in-degree to the queue. We can then remove a vertex from the queue, update the count of each color in the path that ends at that vertex, and update the in-degree of all its neighbors. If the in-degree of a neighbor becomes zero after updating, we can add it to the queue. We can repeat this process until the queue becomes empty.\r\n\r\nWe can also maintain a variable to keep track of the maximum count of a color in the path. We can update this variable whenever we update the count of a color in the path that ends at a vertex.\r\n\r\nAt the end of the process, we can check if we have processed all the vertices in the graph. If not, we can return -1 as it means there is a cycle in the graph. If we have processed all the vertices, we can return the maximum count of a color in the path.\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\nTime complexity: O(V+E), where V is the number of vertices in the graph, and E is the number of edges in the graph. We need to process each vertex and edge at most once.\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\nO(V*26), where V is the number of vertices in the graph. We need to maintain an array of size 26 for each vertex to keep track of the count of each color in the path that ends at that vertex. We also need to maintain an adjacency list for the graph, which requires O(E) space.\r\n\r\n\r\n![image.png]()\r\n\r\n\r\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\r\n```\r\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\r\nPlease give my solution an upvote! \uD83D\uDC4D\r\nIt\'s a simple way to show your appreciation and\r\nkeep me motivated. Thank you! \uD83D\uDE0A\r\n```\r\n# Code\r\n```java []\r\nclass Solution {\r\npublic int largestPathValue(String colors, int[][] edges) {\r\n List<List<Integer>> al = new ArrayList<>();\r\n List<int[]> cnt = new ArrayList<>();\r\n int n = colors.length();\r\n for (int i = 0; i < n; i++) {\r\n al.add(new ArrayList<>());\r\n cnt.add(new int[26]);\r\n }\r\n int[] indegrees = new int[n];\r\n for (int[] e : edges) {\r\n al.get(e[0]).add(e[1]);\r\n indegrees[e[1]]++;\r\n }\r\n List<Integer> q = new ArrayList<>();\r\n for (int i = 0; i < n; i++) {\r\n if (indegrees[i] == 0)\r\n q.add(i);\r\n }\r\n int res = 0, processed = 0;\r\n while (!q.isEmpty()) {\r\n List<Integer> q1 = new ArrayList<>();\r\n for (int i : q) {\r\n processed++;\r\n res = Math.max(res, ++cnt.get(i)[colors.charAt(i) - \'a\']);\r\n for (int j : al.get(i)) {\r\n for (int k = 0; k < 26; k++)\r\n cnt.get(j)[k] = Math.max(cnt.get(j)[k], cnt.get(i)[k]);\r\n if (--indegrees[j] == 0)\r\n q1.add(j);\r\n }\r\n }\r\n q = q1;\r\n }\r\n return processed != n ? -1 : res;\r\n}\r\n\r\n}\r\n```\r\n```c++ []\r\nclass Solution {\r\npublic:\r\n int largestPathValue(string cs, vector<vector<int>>& edges) {\r\n vector<vector<int>> al(cs.size()), cnt(cs.size(), vector<int>(26));\r\n vector<int> indegrees(cs.size());\r\n for (auto &e: edges) {\r\n al[e[0]].push_back(e[1]);\r\n ++indegrees[e[1]];\r\n }\r\n vector<int> q;\r\n for (int i = 0; i < cs.size(); ++i)\r\n if (indegrees[i] == 0)\r\n q.push_back(i);\r\n int res = 0, processed = 0;\r\n while (!q.empty()) {\r\n vector<int> q1;\r\n for (auto i : q) {\r\n ++processed;\r\n res = max(res, ++cnt[i][cs[i] - \'a\']);\r\n for (auto j : al[i]) {\r\n for (auto k = 0; k < 26; ++k)\r\n cnt[j][k] = max(cnt[j][k], cnt[i][k]);\r\n if (--indegrees[j] == 0)\r\n q1.push_back(j);\r\n }\r\n }\r\n swap(q, q1);\r\n }\r\n return processed != cs.size() ? -1 : res;\r\n}\r\n};\r\n```\r\n```python []\r\nclass Solution(object):\r\n def largestPathValue(self, colors, edges):\r\n n = len(colors)\r\n al = [[] for _ in range(n)]\r\n cnt = [[0] * 26 for _ in range(n)]\r\n indegrees = [0] * n\r\n \r\n for e in edges:\r\n al[e[0]].append(e[1])\r\n indegrees[e[1]] += 1\r\n \r\n q = []\r\n for i in range(n):\r\n if indegrees[i] == 0:\r\n q.append(i)\r\n \r\n res, processed = 0, 0\r\n while q:\r\n q1 = []\r\n for i in q:\r\n processed += 1\r\n res = max(res, cnt[i][ord(colors[i]) - ord(\'a\')] + 1)\r\n cnt[i][ord(colors[i]) - ord(\'a\')] += 1\r\n for j in al[i]:\r\n for k in range(26):\r\n cnt[j][k] = max(cnt[j][k], cnt[i][k])\r\n indegrees[j] -= 1\r\n if indegrees[j] == 0:\r\n q1.append(j)\r\n q = q1\r\n \r\n return res if processed == n else -1\r\n\r\n```\r\n\r\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\r\n```\r\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\r\n```
95,723
Substrings of Size Three with Distinct Characters
substrings-of-size-three-with-distinct-characters
A string is good if there are no repeated characters. Given a string s​​​​​, return the number of good substrings of length three in s​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string.
Hash Table,String,Sliding Window,Counting
Easy
Try using a set to find out the number of distinct characters in a substring.
4,486
32
Iterative over string and increase the counter if all characters of length 3 string are different.\n\n```\n def countGoodSubstrings(self, s: str) -> int:\n ans=0\n for i in range(len(s)-2):\n if len(set(s[i:i+3]))==3:\n ans+=1\n return ans\n```
95,754
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
1,296
11
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere are 2 different approaches. \nOne is using sort & greedy; using python 1 line & C++ to implement.\nOther is using frequency & 2 pointers, C & C++ solutions which are really fast & beat 100%.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSuppose `nums` is sorted, either by `sort` or by frequency counting & 2-pointers.\nChoose the pairs `(nums[0], nums[n-1])`,$\\cdots$,`(nums[i], nums[n-1-i])`,$\\cdots$,`(nums[n/2-1], nums[n/2])`. Take the maximun among them which is the answer.\n\n# Why Gready works in this way?\nOne can prove it by induction on $n=2k$ which is formal. Here is a brief sketch of proof for $k=2, n=4$.\nLet $x_o\\leq x_1\\leq x_2\\leq x_3$. There are 3 different ways to arrange the pairs:\n$$\nL_0:(x_0, x_1), (x_2, x_3) \\to l_0=x_2+x_3 \\\\\nL_1:(x_0, x_2), (x_1, x_3) \\to l_1=\\max(x_0+x_2,x_1+x_3)\\\\\nL_2:(x_0, x_3), (x_1, x_2) \\to l_2=\\max(x_0+x_3,x_1+x_2)\n$$\nOne obtains $l_2\\leq l_1 \\leq l_0.$\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)$$ vs $O(n+10^5)=O(n)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(1)$ vs $O(10^5)=O(1) $\n# 1st approach Python 1 line\n```python []\nclass Solution:\n def minPairSum(self, nums: List[int]) -> int:\n return nums.sort() or max(nums[i]+nums[-1-i] for i in range((len(nums)>>1)+1))\n``` \n```C++ []\n\nclass Solution {\npublic:\n int minPairSum(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n=nums.size();\n int maxP=0;\n for(int i=0; i<n/2; i++)\n maxP=max(maxP, nums[i]+nums[n-1-i]);\n return maxP;\n }\n};\n```\n# C++ code using freq & 2 pointers 71 ms Beats 100.00%\n```C++ []\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n int minPairSum(vector<int>& nums) {\n int freq[100001]={0};\n #pragma unroll\n for(int x: nums )\n freq[x]++;\n int l=0, r=100000, maxP=0, pairN=1, rN=0, lN=0;\n #pragma unroll\n while (l < r) {\n #pragma unroll\n while (lN < pairN) {\n lN += freq[l++];\n }\n #pragma unroll\n while (rN < pairN) {\n rN += freq[r--];\n }\n maxP = max(maxP, l+r);\n pairN++;\n }\n return maxP;\n }\n};\n```\n\n```C []\n#pragma GCC optimize("O3")\n\nint minPairSum(int* nums, int n){\n int freq[100001]={0};\n int l=100000, r=1;\n #pragma unroll\n for(register i=0; i<n; i++){\n int x=nums[i];\n freq[x]++;\n if (l>x) l=x;\n if (r<x) r=x;\n }\n int maxP=0, rN=0, lN=0, k=n>>1;\n #pragma unroll\n for(register int pairN=1; pairN<=k; pairN++){\n #pragma unroll\n while (lN < pairN) lN += freq[l++];\n \n #pragma unroll\n while (rN < pairN) rN += freq[r--];\n if (l+r>maxP) maxP=l+r;\n }\n return maxP;\n}\n```\n\n\n
95,774
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
545
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI believe many other posts has covered the general method of how to solve this. the ideas is to pair up the smallest number with the largest, 2nd smallest with 2nd largest and so on.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsort the list in nlogn time. split the list in half and reverse one of the halved list. merge the list and take the maximum pair sum.\n\nthe key difference here is that we use a zipped list comprehensive for faster speed in python compared to using a for loop.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\nBeats 99.59%\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def minPairSum(self, nums: List[int]) -> int:\n nums.sort()\n return max([x+y for x,y in zip(nums[:len(nums)//2],nums[len(nums)//2:][::-1])])\n \n```
95,775
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
29
10
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def minPairSum(self, nums):\n nums.sort()\n sum = []\n for num in range(0,len(nums)):\n sum.append(nums[num] + nums[len(nums)-num-1])\n sum.sort(reverse = True)\n return sum[0]\n\n\n \n```
95,777
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
1,005
26
# Intuition\nSort input array.\n\n---\n\n# Solution Video\n\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\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,130\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\n# Approach\n\n## How we think about a solution\n\nWe need to meet these two condtion\n\n\n---\n\n1. Each element of nums is in exactly one pair\n2. The maximum pair sum is minimized.\n\n---\n\nLet\'s think about this input\n```\nInput: [63, 71, 12, 80, 38, 21, 92, 15]\n```\nSince we return minimized maximum pair sum, we create minimum pair of each number, then find the minimized maximum pair sum.\n\nLet\'s start with the biggest number.\n\nIf we use `92`, how do you create minimized maximum pair sum? It\'s simple. Just pairing `92` with the smallest number in the input array.\n\n```\n(92, 12) \n\nrest of numbers\n[63, 71, 80, 38, 21, 15]\n```\nThe next biggest number is `80`. how do you create minimized maximum pair sum? We pair `80` with `15`.\n\nThey are pair of the second biggest number and second smallest number.\n```\n(92, 12) \n(80, 15)\n\nrest of numbers\n[63, 71, 38, 21]\n```\nHow about `71`. If we want to create minimized maximum pair sum, we should choose `21` in the rest of numbers.\n```\n(92, 12) \n(80, 15)\n(71, 21)\n\nrest of numbers\n[63, 38]\n```\nThen we pair `63` and `38`\n```\n(92, 12) = 104\n(80, 15) = 95\n(71, 21) = 92\n(63, 38) = 101\n```\nThese 4 numbers are possible minimized maximum pair sum.\n\nAll we have to do is to return maximum value of the 4 pairs.\n\n```\nOutput: 104\n```\n\nWhat if we create `(80, 12)`?\n```\n(80, 12) = 92\n(92, 15) = 107\n(71, 21) = 92\n(63, 38) = 101\n```\nminimum maximum is now `107` which is greater than `104`. This is not answer.\n\nHow about `(92, 80)`? minimum maximum is now `172` which is greater than `104`. This is not answer.\n\n```\n(92, 80) = 172\n(71, 12) = 83\n(63, 15) = 78\n(38, 21) = 59\n```\n\nHow about `(21, 12)`? minimum maximum is now `134` which is greater than `104`. This is not answer.\n\n```\n(21, 12) = 33\n(92, 15) = 107\n(80, 38) = 118\n(71, 63) = 134\n```\nWe have more other patterns but we cannot create minimum maximum number which is less than `104`.\n\n---\n\n\n### Let\'s see other example quickly\n\nLet\'s see simpler example.\n```\nInput: [1, 70, 80, 100]\n```\n\n```\n(100, 1) = 101\n(80, 70) = 150\n```\nminimum maximum is `150`. We swap the numbers.\n```\n(100, 80) = 180\n(1, 70) = 70\n```\nminimum maximum is `180` which is greater than `150`. This is not answer. \n\n```\n(100, 70) = 170\n(80, 1) = 81\n```\nminimum maximum is `170` which is greater than `150`. This is not answer. \n\nThere are 3 more pair combinations but they just reverse of pairs. For example, `(1, 100)` is equal to `(100, 1)`, so let me skip explanation.\n```\nOutput: 150\n```\n\nLook at these answer pair combinations.\n```\n(92, 12) = 104\n(80, 15) = 95\n(71, 21) = 92\n(63, 38) = 101\n```\n```\n(100, 1) = 101\n(80, 70) = 150\n```\nThe common process of these two is that we pair the biggest number and the smallest number at first. Next, we pair the second biggest number and the second smallest number...\n\nThat\'s why, seems like sorting input array is big help to solve this question.\n\nThen we create pairs with current biggest and smallest number and take maximum value of all pairs.\n\n\n---\n\n\u2B50\uFE0F Points\n\nSort input array and create pairs of current biggest and smallest number. Then take maximum number of all pairs.\n\n---\n\nI felt like this question is tricky. but it\'s very straightforward question.\nLet\'s see a real algorithm!\n\n1. **Sort the array:**\n ```python\n nums.sort()\n ```\n Sorts the input array `nums` in ascending order. Sorting is crucial for pairing smaller and larger numbers efficiently.\n\n2. **Initialize variables:**\n ```python\n n = len(nums)\n min_max_sum = 0\n ```\n Sets `n` to the length of the sorted array and initializes `min_max_sum` to 0. `min_max_sum` will keep track of the maximum pair sum as we iterate through the array.\n\n3. **Iterate through pairs:**\n ```python\n for i in range(n // 2):\n min_max_sum = max(min_max_sum, nums[i] + nums[n - 1 - i])\n ```\n Iterates through the first half of the sorted array. For each iteration, calculates the sum of the current pair `(nums[i], nums[n - 1 - i])`. Updates `min_max_sum` to be the maximum of its current value and the calculated sum.\n\n4. **Return the result:**\n ```python\n return min_max_sum\n ```\n After iterating through all possible pairs, returns the final value of `min_max_sum`.\n\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n\n\n- Space complexity: $$O(log n)$$ or $$O(n)$$\n\n Depends on language you use\n\n\n```python []\nclass Solution:\n def minPairSum(self, nums: List[int]) -> int:\n nums.sort()\n\n n = len(nums)\n min_max_sum = 0\n\n for i in range(n // 2):\n min_max_sum = max(min_max_sum, nums[i] + nums[n - 1 - i])\n\n return min_max_sum \n```\n```javascript []\nvar minPairSum = function(nums) {\n nums.sort((a, b) => a - b);\n\n let n = nums.length;\n let minMaxSum = 0;\n\n for (let i = 0; i < n / 2; i++) {\n minMaxSum = Math.max(minMaxSum, nums[i] + nums[n - 1 - i]);\n }\n\n return minMaxSum; \n};\n```\n```java []\nclass Solution {\n public int minPairSum(int[] nums) {\n Arrays.sort(nums);\n\n int n = nums.length;\n int minMaxSum = 0;\n\n for (int i = 0; i < n / 2; i++) {\n minMaxSum = Math.max(minMaxSum, nums[i] + nums[n - 1 - i]);\n }\n\n return minMaxSum; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minPairSum(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n\n int n = nums.size();\n int minMaxSum = 0;\n\n for (int i = 0; i < n / 2; i++) {\n minMaxSum = max(minMaxSum, nums[i] + nums[n - 1 - i]);\n }\n\n return minMaxSum; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n\u25A0 Twitter\n\n\n### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0: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### 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 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
95,780
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
2,417
33
**First and Foremost, Understanding Minimum Maximum Pair Sum**\n\nFor a given set of elements, you can form pairs by combining two elements. Among all possible pairs, there will be one pair with the largest sum. The largest sum among all pairs is referred to as the maximum pair sum.\n\nNow, the goal is to pair the elements in a way that, among all possible pairings, the largest sum (maximum pair sum) is as small as possible. This is what is meant by minimum maximum pair sum. Read again!\n\n### *Brute Force Approach:* \nWe can try all the pairs and finding the answer among them.\n\n- The issue is TC will inflate, i.e., if there are N elements, there are N(N-1)/2 possible pairs. Thus, the time complexity is O(N^2).\n- The SC depends on how we implement the pairings. If we store all pairs explicitly, the space complexity would be O(N(N-1)/2) for storing the pairs. However, a minor optimization can be made if we are only tracking the minimum maximum pair sum; then, the space complexity will be O(1).\n\n\nThe above brute force is ok but we need a more efficient strategy to increase the probability of finding the answer in less time.\n\n### *Optimal Approach:*\nWe are given an even length of N integers. For example: [3, 5, 2, 3].\n\n- If we pair the smallest integer first and then, in the last, pair the max numbers: (2, 3), (3, 5) = max(5, 8) = 8. \n- This won\'t work because all the larger elements will be in the same pair. What we need is to minimize the impact of the larger elements on the maximum pair sum.\n- Now if we pair the smallest with the greatest and the second smallest with the second greatest: (2, 5), (3, 3) = max(7, 6) = 6.\n\nSo, one thing is sure: the potential workable strategy is pairing the greatest with the smallest and the 2nd greatest with the 2nd smallest, and so on. This strategy is preferred because it creates a potential balance between the pairs, with one element from the greater end and the other element from the lower end.\n\nLet\'s say we have the sorted list A: [a1, a2, ..., an]. The pairing strategy would look like this:\n\n- Pair 1: (a1, an)\n- Pair 2: (a2, an-1)\n- Pair 3: (a3, an-2)\n- ...\n- Pair k: (ak, an-k+1)\n\nThis way, each pair contributes to minimizing the maximum pair sum. The reason this strategy works well is that it distributes the larger elements with the smaller ones, creating a more balanced distribution and minimizing the impact of the larger elements on the maximum pair sum.\n\nOne more note for our strategy to work; we need to know which one is the greatest, smallest, second greatest, second smallest, and so on. Thus, sorting the array will make more sense.\n\n> **In an interview, make sure you first explain the brute force before explaining the optimal. Most of the solutions are directly jumping to optimal without even talking about brute force and this may lead to answering awkward questions during an interview, like how do you know this, have you already solved this? :)))**\n\n# Code\n```cpp\nclass Solution {\npublic:\n int minPairSum(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n \n int minMaxSum = 0;\n for (int i = 0; i < nums.size() / 2; i++) {\n minMaxSum = max(minMaxSum, nums[i] + nums[nums.size() - 1 - i]);\n }\n \n return minMaxSum;\n }\n};\n```\n\n```java\nclass Solution {\n public int minPairSum(int[] nums) {\n Arrays.sort(nums);\n \n int minMaxSum = 0;\n for (int i = 0; i < nums.length / 2; i++) {\n minMaxSum = Math.max(minMaxSum, nums[i] + nums[nums.length - 1 - i]);\n }\n \n return minMaxSum;\n }\n}\n```\n\n```python\nclass Solution:\n def minPairSum(self, nums):\n nums.sort()\n \n min_max_sum = 0\n for i in range(len(nums) // 2):\n min_max_sum = max(min_max_sum, nums[i] + nums[len(nums) - 1 - i])\n \n return min_max_sum\n```\n\n
95,785
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
8,560
74
\n# 1st Method :- Greedy Approach / Two Pointers\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe goal is to minimize the sum of the maximum pairs in the array. Sorting the array helps in pairing the smallest elements with the largest ones. By doing so, we ensure that the maximum pairs are minimized. The approach involves keeping two pointers, one at the beginning and the other at the end of the sorted array. Pairing elements at these pointers provides a way to find the minimized sum of the maximum pairs.\n\n## Approach \uD83D\uDE80\n\n1. **Sort the Array:**\n - Sort the input array in ascending order. This step is crucial for pairing the smallest elements with the largest ones.\n\n2. **Initialize Pointers:**\n - Initialize two pointers, `left` at the start of the array and `right` at the end of the array.\n\n3. **Initialize a Variable:**\n - Create a variable (`minMaxPairSum`) to keep track of the minimum of the maximum pair sums. Initialize it to the smallest possible integer value.\n\n4. **Pairing Elements:**\n - Iterate through the array using a while loop until the `left` pointer is less than the `right` pointer.\n\n5. **Calculate Current Pair Sum:**\n - Calculate the sum of the pair of elements pointed to by the `left` and `right` pointers.\n\n6. **Update Minimum of Maximum Pair Sum:**\n - Update `minMaxPairSum` by taking the maximum value between the current pair sum and the existing `minMaxPairSum`. This ensures that `minMaxPairSum` stores the minimum value encountered during the iteration.\n\n7. **Move Pointers Towards the Center:**\n - Increment the `left` pointer and decrement the `right` pointer to move towards the center of the array.\n\n8. **Return the Result:**\n - After the loop, return the calculated `minMaxPairSum` as the final result.\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public int minPairSum(int[] nums) {\n // Step 1: Sort the array in ascending order\n Arrays.sort(nums);\n\n // Step 2: Initialize pointers at the start and end of the sorted array\n int left = 0, right = nums.length - 1;\n\n // Step 3: Initialize a variable to store the minimum of the maximum pair sum\n int minMaxPairSum = Integer.MIN_VALUE;\n\n // Step 4: Iterate until the pointers meet\n while (left < right) {\n // Step 5: Calculate the current pair sum\n int currentPairSum = nums[left] + nums[right];\n\n // Step 6: Update the minimum of the maximum pair sum\n minMaxPairSum = Math.max(minMaxPairSum, currentPairSum);\n\n // Step 7: Move the pointers towards the center\n left++;\n right--;\n }\n\n // Step 8: Return the minimum of the maximum pair sum\n return minMaxPairSum;\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n int minPairSum(std::vector<int>& nums) {\n // Step 1: Sort the array in ascending order\n std::sort(nums.begin(), nums.end());\n\n // Step 2: Initialize pointers at the start and end of the sorted array\n int left = 0, right = nums.size() - 1;\n\n // Step 3: Initialize a variable to store the minimum of the maximum pair sum\n int minMaxPairSum = INT_MIN;\n\n // Step 4: Iterate until the pointers meet\n while (left < right) {\n // Step 5: Calculate the current pair sum\n int currentPairSum = nums[left] + nums[right];\n\n // Step 6: Update the minimum of the maximum pair sum\n minMaxPairSum = std::max(minMaxPairSum, currentPairSum);\n\n // Step 7: Move the pointers towards the center\n left++;\n right--;\n }\n\n // Step 8: Return the minimum of the maximum pair sum\n return minMaxPairSum;\n }\n};\n\n```\n``` Python []\nclass Solution(object):\n def minPairSum(self, nums):\n # Step 1: Sort the array in ascending order\n nums.sort()\n\n # Step 2: Initialize pointers at the start and end of the sorted array\n left, right = 0, len(nums) - 1\n\n # Step 3: Initialize a variable to store the minimum of the maximum pair sum\n min_max_pair_sum = float(\'-inf\')\n\n # Step 4: Iterate until the pointers meet\n while left < right:\n # Step 5: Calculate the current pair sum\n current_pair_sum = nums[left] + nums[right]\n\n # Step 6: Update the minimum of the maximum pair sum\n min_max_pair_sum = max(min_max_pair_sum, current_pair_sum)\n\n # Step 7: Move the pointers towards the center\n left += 1\n right -= 1\n\n # Step 8: Return the minimum of the maximum pair sum\n return min_max_pair_sum\n\n\n```\n``` JavaScript []\nvar minPairSum = function(nums) {\n // Step 1: Sort the array in ascending order\n nums.sort((a, b) => a - b);\n\n // Step 2: Initialize pointers at the start and end of the sorted array\n let left = 0, right = nums.length - 1;\n\n // Step 3: Initialize a variable to store the minimum of the maximum pair sum\n let minMaxPairSum = Number.MIN_SAFE_INTEGER;\n\n // Step 4: Iterate until the pointers meet\n while (left < right) {\n // Step 5: Calculate the current pair sum\n const currentPairSum = nums[left] + nums[right];\n\n // Step 6: Update the minimum of the maximum pair sum\n minMaxPairSum = Math.max(minMaxPairSum, currentPairSum);\n\n // Step 7: Move the pointers towards the center\n left++;\n right--;\n }\n\n // Step 8: Return the minimum of the maximum pair sum\n return minMaxPairSum;\n};\n```\n``` C# []\npublic class Solution {\n public int MinPairSum(int[] nums) {\n // Step 1: Sort the array in ascending order\n Array.Sort(nums);\n\n // Step 2: Initialize pointers at the start and end of the sorted array\n int left = 0, right = nums.Length - 1;\n\n // Step 3: Initialize a variable to store the minimum of the maximum pair sum\n int minMaxPairSum = int.MinValue;\n\n // Step 4: Iterate until the pointers meet\n while (left < right) {\n // Step 5: Calculate the current pair sum\n int currentPairSum = nums[left] + nums[right];\n\n // Step 6: Update the minimum of the maximum pair sum\n minMaxPairSum = Math.Max(minMaxPairSum, currentPairSum);\n\n // Step 7: Move the pointers towards the center\n left++;\n right--;\n }\n\n // Step 8: Return the minimum of the maximum pair sum\n return minMaxPairSum;\n }\n}\n\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(n log n)\nThe dominant factor in the time complexity is the sorting step, and the array sorting is done using `Arrays.sort(nums)`. The time complexity of the sorting operation is O(n log n), where \'n\' is the length of the array.\n\nTherefore, the overall time complexity of the code is O(n log n).\n\n### \uD83C\uDFF9Space complexity: O(1)\nThe space complexity is determined by the additional variables used in the code. In this case, the only additional space used is for the `minMaxPairSum`, `left`, and `right` variables, which require constant space.\n\nTherefore, the overall space complexity of the code is O(1) (constant space).\n\n![vote.jpg]()\n\n\n---\n# 2nd Method :- Two-pointer approach with frequency counting.\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe goal is to minimize the maximum pair sum in the given array. To achieve this, we want to pair the largest numbers with the smallest numbers. The code uses two pointers (`low` and `high`) to traverse the array, pointing to the smallest and largest numbers respectively. The idea is to pair the numbers at these pointers to minimize the maximum pair sum.\n\n\n## Approach \uD83D\uDE80\n\n1. **Frequency Counting and Finding Min/Max:**\n - Iterate through the given array to calculate the frequency of each number and find the minimum (`minNum`) and maximum (`maxNum`) numbers.\n\n2. **Initialize Pointers and Iterate:**\n - Initialize two pointers, `low` pointing to `minNum` and `high` pointing to `maxNum`.\n - Iterate using a while loop until `low` is less than or equal to `high`.\n\n3. **Adjust Pointers:**\n - If the frequency of the number at `low` is zero, move `low` to the right to find the next valid number.\n - If the frequency of the number at `high` is zero, move `high` to the left to find the next valid number.\n\n4. **Pairing and Updating MaxSum:**\n - If both `low` and `high` pointers point to valid numbers, calculate the sum of the pair (`currentPairSum`).\n - Update the `maxSum` if the `currentPairSum` is greater.\n - Decrease the frequency of the numbers at `low` and `high` pointers.\n\n5. **Return Result:**\n - After the while loop, return the final minimized maximum pair sum stored in `maxSum`.\n\n### Summary:\n\nThe approach involves efficiently pairing the smallest and largest numbers in the array to minimize the maximum pair sum. It uses frequency counting to keep track of the occurrences of each number and adjusts pointers to find valid numbers for pairing. The process continues until the pointers meet, ensuring all numbers are considered. The final result is the minimized maximum pair sum.\n\n\n\n## \u2712\uFE0FCode\n``` Java []\nclass Solution {\n public int minPairSum(int[] nums) {\n int maxSum = Integer.MIN_VALUE; // Variable to store the minimized maximum pair sum\n int minNum = Integer.MAX_VALUE; // Variable to store the minimum number in the array\n int maxNum = Integer.MIN_VALUE; // Variable to store the maximum number in the array\n\n int frequency[] = new int[100001]; // Array to store the frequency of each number in the array\n\n // Iterate through the array to populate frequency array and find min and max numbers\n for (int num : nums) {\n frequency[num]++;\n minNum = Math.min(minNum, num);\n maxNum = Math.max(maxNum, num);\n }\n\n // Initialize pointers for two numbers to form pairs\n int low = minNum;\n int high = maxNum;\n\n // Iterate while low pointer is less than or equal to high pointer\n while (low <= high) {\n // If frequency of the number at low pointer is zero, move low pointer to the right\n if (frequency[low] == 0) {\n low++;\n }\n // If frequency of the number at high pointer is zero, move high pointer to the left\n else if (frequency[high] == 0) {\n high--;\n }\n // Both low and high pointers point to valid numbers\n else {\n // Calculate the sum of the pair at the current pointers\n int currentPairSum = low + high;\n // Update maxSum if the current pair sum is greater\n maxSum = Math.max(maxSum, currentPairSum);\n // Decrease the frequency of the numbers at low and high pointers\n frequency[low]--;\n frequency[high]--;\n }\n }\n\n return maxSum; // Return the minimized maximum pair sum\n }\n}\n\n```\n``` C++ []\n\nclass Solution {\npublic:\n int minPairSum(std::vector<int>& nums) {\n int maxSum = INT_MIN; // Variable to store the minimized maximum pair sum\n int minNum = INT_MAX; // Variable to store the minimum number in the array\n int maxNum = INT_MIN; // Variable to store the maximum number in the array\n\n std::vector<int> frequency(100001, 0); // Vector to store the frequency of each number in the array\n\n // Iterate through the array to populate frequency vector and find min and max numbers\n for (int num : nums) {\n frequency[num]++;\n minNum = std::min(minNum, num);\n maxNum = std::max(maxNum, num);\n }\n\n // Initialize pointers for two numbers to form pairs\n int low = minNum;\n int high = maxNum;\n\n // Iterate while low pointer is less than or equal to high pointer\n while (low <= high) {\n // If frequency of the number at low pointer is zero, move low pointer to the right\n if (frequency[low] == 0) {\n low++;\n }\n // If frequency of the number at high pointer is zero, move high pointer to the left\n else if (frequency[high] == 0) {\n high--;\n }\n // Both low and high pointers point to valid numbers\n else {\n // Calculate the sum of the pair at the current pointers\n int currentPairSum = low + high;\n // Update maxSum if the current pair sum is greater\n maxSum = std::max(maxSum, currentPairSum);\n // Decrease the frequency of the numbers at low and high pointers\n frequency[low]--;\n frequency[high]--;\n }\n }\n\n return maxSum; // Return the minimized maximum pair sum\n }\n};\n\n```\n``` Python []\nclass Solution:\n def minPairSum(self, nums):\n maxSum = float(\'-inf\') # Variable to store the minimized maximum pair sum\n minNum = float(\'inf\') # Variable to store the minimum number in the array\n maxNum = float(\'-inf\') # Variable to store the maximum number in the array\n\n frequency = [0] * 100001 # List to store the frequency of each number in the array\n\n # Iterate through the array to populate frequency list and find min and max numbers\n for num in nums:\n frequency[num] += 1\n minNum = min(minNum, num)\n maxNum = max(maxNum, num)\n\n # Initialize pointers for two numbers to form pairs\n low = minNum\n high = maxNum\n\n # Iterate while low pointer is less than or equal to high pointer\n while low <= high:\n # If frequency of the number at low pointer is zero, move low pointer to the right\n if frequency[low] == 0:\n low += 1\n # If frequency of the number at high pointer is zero, move high pointer to the left\n elif frequency[high] == 0:\n high -= 1\n # Both low and high pointers point to valid numbers\n else:\n # Calculate the sum of the pair at the current pointers\n currentPairSum = low + high\n # Update maxSum if the current pair sum is greater\n maxSum = max(maxSum, currentPairSum)\n # Decrease the frequency of the numbers at low and high pointers\n frequency[low] -= 1\n frequency[high] -= 1\n\n return maxSum # Return the minimized maximum pair sum\n\n```\n``` JavaScript []\nvar minPairSum = function(nums) {\n let maxSum = Number.MIN_SAFE_INTEGER; // Variable to store the minimized maximum pair sum\n let minNum = Number.MAX_SAFE_INTEGER; // Variable to store the minimum number in the array\n let maxNum = Number.MIN_SAFE_INTEGER; // Variable to store the maximum number in the array\n\n const frequency = new Array(100001).fill(0); // Array to store the frequency of each number in the array\n\n // Iterate through the array to populate frequency array and find min and max numbers\n nums.forEach(num => {\n frequency[num]++;\n minNum = Math.min(minNum, num);\n maxNum = Math.max(maxNum, num);\n });\n\n // Initialize pointers for two numbers to form pairs\n let low = minNum;\n let high = maxNum;\n\n // Iterate while low pointer is less than or equal to high pointer\n while (low <= high) {\n // If frequency of the number at low pointer is zero, move low pointer to the right\n if (frequency[low] === 0) {\n low++;\n }\n // If frequency of the number at high pointer is zero, move high pointer to the left\n else if (frequency[high] === 0) {\n high--;\n }\n // Both low and high pointers point to valid numbers\n else {\n // Calculate the sum of the pair at the current pointers\n let currentPairSum = low + high;\n // Update maxSum if the current pair sum is greater\n maxSum = Math.max(maxSum, currentPairSum);\n // Decrease the frequency of the numbers at low and high pointers\n frequency[low]--;\n frequency[high]--;\n }\n }\n\n return maxSum; // Return the minimized maximum pair sum\n};\n\n```\n``` C# []\npublic class Solution {\n public int MinPairSum(int[] nums) {\n int maxSum = int.MinValue; // Variable to store the minimized maximum pair sum\n int minNum = int.MaxValue; // Variable to store the minimum number in the array\n int maxNum = int.MinValue; // Variable to store the maximum number in the array\n\n int[] frequency = new int[100001]; // Array to store the frequency of each number in the array\n\n // Iterate through the array to populate frequency array and find min and max numbers\n foreach (int num in nums) {\n frequency[num]++;\n minNum = Math.Min(minNum, num);\n maxNum = Math.Max(maxNum, num);\n }\n\n // Initialize pointers for two numbers to form pairs\n int low = minNum;\n int high = maxNum;\n\n // Iterate while low pointer is less than or equal to high pointer\n while (low <= high) {\n // If frequency of the number at low pointer is zero, move low pointer to the right\n if (frequency[low] == 0) {\n low++;\n }\n // If frequency of the number at high pointer is zero, move high pointer to the left\n else if (frequency[high] == 0) {\n high--;\n }\n // Both low and high pointers point to valid numbers\n else {\n // Calculate the sum of the pair at the current pointers\n int currentPairSum = low + high;\n // Update maxSum if the current pair sum is greater\n maxSum = Math.Max(maxSum, currentPairSum);\n // Decrease the frequency of the numbers at low and high pointers\n frequency[low]--;\n frequency[high]--;\n }\n }\n\n return maxSum; // Return the minimized maximum pair sum\n }\n}\n\n```\n\n## Complexity \uD83D\uDE81\n### \uD83C\uDFF9Time complexity: O(n)\n- Iterating through the array to populate the frequency array and find min and max numbers: \\(O(n)\\), where \\(n\\) is the length of the array.\n- The while loop iterates until the low pointer is less than or equal to the high pointer. In each iteration, we either increment the low pointer or decrement the high pointer. Since both pointers move towards each other, the total number of iterations is \\(O(n)\\).\n- Each iteration involves constant-time operations (comparison, addition, subtraction), so the overall time complexity is \\(O(n)\\).\n\n### \uD83C\uDFF9Space complexity: O(1)\n- The `frequency` array has a fixed size of 100001. Therefore, the space complexity is \\(O(1)\\) because the size of the array is constant regardless of the input size.\n- Other variables (`maxSum`, `minNum`, `maxNum`, `low`, `high`) are all scalar variables, and their space complexity is constant.\n\n![upvote.png]()\n# Up Vote Guys\n
95,786
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
554
13
# Intuition\nTo minimize the maximum pair sum, a possible approach is to pair the smallest numbers with the largest numbers. By doing so, the maximum sum would be minimized, as adding smaller numbers to larger ones typically results in smaller total sums.\n\n# Approach\n1. Sort the given array of numbers.\n2. Use two pointers, one starting from the beginning (left pointer) and the other from the end (right pointer) of the sorted array.\n3. While the left pointer is less than the right pointer:\n 1. Calculate the sum of the pair formed by elements at the left and right pointers.\n 2. Update the maximum pair sum by comparing it with the current sum.\n 3. Move the pointers inward (increment the left pointer and decrement the right pointer).\n 4. Return the maximum pair sum found.\n# Complexity\nTime complexity: Sorting the array takes O(n log n) time, where n is the number of elements in the array. The iteration through the sorted array takes linear time, so overall time complexity is O(n log n).\n\nSpace complexity: The space complexity is O(1) since the algorithm uses only a constant amount of extra space for variables like pointers and maximum pair sum storage.\n\n# Code\n``` Python []\nclass Solution(object):\n def minPairSum(self, nums):\n nums.sort() # Sort the array\n left, right = 0, len(nums) - 1\n max_pair_sum = float(\'-inf\')\n\n while left < right:\n pair_sum = nums[left] + nums[right]\n max_pair_sum = max(max_pair_sum, pair_sum)\n left += 1\n right -= 1\n\n return max_pair_sum\n```\n```C++ []\nclass Solution { \npublic:\n int minPairSum(vector<int>& nums) {\n std::sort(nums.begin(), nums.end()); // Sort the array\n\n int left = 0, right = nums.size() - 1;\n int maxPairSum = INT_MIN;\n\n while (left < right) {\n int pairSum = nums[left] + nums[right];\n maxPairSum = std::max(maxPairSum, pairSum);\n left++;\n right--;\n }\n\n return maxPairSum;\n \n }\n};\n```\n``` Python []\nclass Solution(object):\n def minPairSum(self, nums):\n max_num = max(nums)\n min_num = min(nums)\n\n freq = [0] * (max_num - min_num + 1)\n\n for num in nums:\n freq[num - min_num] += 1\n\n left = min_num\n right = max_num\n max_pair_sum = float(\'-inf\')\n\n while left <= right:\n while freq[left - min_num] > 0 and freq[right - min_num] > 0:\n pair_sum = left + right\n max_pair_sum = max(max_pair_sum, pair_sum)\n freq[left - min_num] -= 1\n freq[right - min_num] -= 1\n\n while freq[left - min_num] == 0 and left <= right:\n left += 1\n while freq[right - min_num] == 0 and left <= right:\n right -= 1\n\n return max_pair_sum\n```\n```C++ []\n#include <iostream>\n#include <vector>\n#include <climits>\nusing namespace std;\n\nclass Solution {\npublic:\n int minPairSum(vector<int>& nums) {\n int max_num = INT_MIN;\n int min_num = INT_MAX;\n\n for (int num : nums) {\n max_num = max(max_num, num);\n min_num = min(min_num, num);\n }\n\n vector<int> freq(max_num - min_num + 1, 0);\n\n for (int num : nums) {\n freq[num - min_num]++;\n }\n\n int left = min_num;\n int right = max_num;\n int max_pair_sum = INT_MIN;\n\n while (left <= right) {\n while (freq[left - min_num] > 0 && freq[right - min_num] > 0) {\n int pair_sum = left + right;\n max_pair_sum = max(max_pair_sum, pair_sum);\n freq[left - min_num]--;\n freq[right - min_num]--;\n }\n\n while (freq[left - min_num] == 0 && left <= right) {\n left++;\n }\n while (freq[right - min_num] == 0 && left <= right) {\n right--;\n }\n }\n\n return max_pair_sum;\n }\n};\n```\n
95,800
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
240
6
# Intuition\n- something like sorting can hrlp\n\n# Approach\n- 2 -Pointer\n\n# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n $$O(1)$$ \n\n# Code\n```py\nclass Solution:\n def minPairSum(self, nums: List[int]) -> int:\n return nums.sort() or max((nums[i]+nums[-(i+1)]) for i in range(len(nums)//2+1))\n```\n\n![](*0NawC6a8WTCYlNWSLooVTw.png)
95,803
Minimize Maximum Pair Sum in Array
minimize-maximum-pair-sum-in-array
The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs. Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that: Return the minimized maximum pair sum after optimally pairing up the elements.
Array,Two Pointers,Greedy,Sorting
Medium
Would sorting help find the optimal order? Given a specific element, how would you minimize its specific pairwise sum?
494
7
```python []\nclass Solution:\n def minPairSum(self, nums: List[int]) -> int:\n return (x := sorted(nums)) and max(x[-i - 1] + x[i] for i in range(len(x) >> 1))\n\n```
95,804
Minimum XOR Sum of Two Arrays
minimum-xor-sum-of-two-arrays
You are given two integer arrays nums1 and nums2 of length n. The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed). Rearrange the elements of nums2 such that the resulting XOR sum is minimized. Return the XOR sum after the rearrangement.
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
Since n <= 14, we can consider every subset of nums2. We can represent every subset of nums2 using bitmasks.
8,109
109
We have a tight constraint here: n <= 14. Thus, we can just try all combinations.\n\nFor each position `i` in the first array, we\'ll try all elements in the second array that haven\'t been chosen before. We can use a bit mask to represent the chosen elements. \n\nTo avoid re-computing the same subproblem, we memoise the result for each bit mask.\n\n> Thanks [LazyCoder16]() for pointing out that we do not need to memoise for `i`.\n\n**C++**\n```cpp\nint dp[16384] = {[0 ... 16383] = INT_MAX};\nint minimumXORSum(vector<int>& a, vector<int>& b, int i = 0, int mask = 0) {\n if (i >= a.size())\n return 0;\n if (dp[mask] == INT_MAX)\n for (int j = 0; j < b.size(); ++j)\n if (!(mask & (1 << j)))\n dp[mask] = min(dp[mask], (a[i] ^ b[j]) + minimumXORSum(a, b, i + 1, mask + (1 << j)));\n return dp[mask];\n}\n```\n**Java**\n```java\nint dfs(int[] dp, int[] a, int[] b, int i, int mask) {\n if (i >= a.length)\n return 0;\n if (dp[mask] == Integer.MAX_VALUE)\n for (int j = 0; j < b.length; ++j)\n if ((mask & (1 << j)) == 0)\n dp[mask] = Math.min(dp[mask], (a[i] ^ b[j]) + dfs(dp, a, b, i + 1, mask + (1 << j)));\n return dp[mask];\n}\npublic int minimumXORSum(int[] nums1, int[] nums2) {\n int dp[] = new int[1 << nums2.length];\n Arrays.fill(dp, Integer.MAX_VALUE);\n return dfs(dp, nums1, nums2, 0, 0);\n}\n```\n**Python 3**\nNote that here we are inferring `i` by counting bits in `mask`. We can pass `i` as an argument, but it will increase the size of the LRU cache.\n\nThe `min` construction is a courtesy of [lee215]().\n\n> Note that `@cahce` was introduced in Python 3.9, and it\'s a shorthand for `@lru_cache(maxsize=None)`\n\n```python\nclass Solution:\n def minimumXORSum(self, a: List[int], b: List[int]) -> int:\n @cache\n def dp(mask: int) -> int:\n i = bin(mask).count("1")\n if i >= len(a):\n return 0\n return min((a[i] ^ b[j]) + dp(mask + (1 << j)) \n for j in range(len(b)) if mask & (1 << j) == 0)\n return dp(0)\n```
95,826
Get Biggest Three Rhombus Sums in a Grid
get-biggest-three-rhombus-sums-in-a-grid
You are given an m x n integer matrix grid​​​. A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum: Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner. Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.
Array,Math,Sorting,Heap (Priority Queue),Matrix,Prefix Sum
Medium
You need to maintain only the biggest 3 distinct sums The limits are small enough for you to iterate over all rhombus sizes then iterate over all possible borders to get the sums
1,618
6
Don\'t leave the idea of question and if you want more explaination or any example please feel free to ask !!\n## IDEA :\n\uD83D\uDC49 Firstly we will determine all the four vertices of rhombus.\n\uD83D\uDC49 Then we will pass that rhombus to calc function to calculate the score(perimeter).\n\uD83D\uDC49 "expand" flag is used to determine upto what time rhombus will expand then again it will get shrink.\n\uD83D\uDC49 Store that perimeter in heap\n\uD83D\uDC49 length of heap will always be three\n\uD83D\uDC49 Return heap after sorting in reverse order.\n\n\'\'\'\n\t\n\tclass Solution:\n def getBiggestThree(self, grid: List[List[int]]) -> List[int]:\n \n def calc(l,r,u,d):\n sc=0\n c1=c2=(l+r)//2\n expand=True\n for row in range(u,d+1):\n if c1==c2:\n sc+=grid[row][c1]\n else:\n sc+=grid[row][c1]+grid[row][c2]\n \n if c1==l:\n expand=False\n \n if expand:\n c1-=1\n c2+=1\n else:\n c1+=1\n c2-=1\n return sc\n \n \n m=len(grid)\n n=len(grid[0])\n heap=[]\n for i in range(m):\n for j in range(n):\n l=r=j\n d=i\n while l>=0 and r<=n-1 and d<=m-1:\n sc=calc(l,r,i,d)\n l-=1\n r+=1\n d+=2\n if len(heap)<3:\n if sc not in heap:\n heapq.heappush(heap,sc)\n else:\n if sc not in heap and sc>heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap,sc)\n \n heap.sort(reverse=True)\n return heap\n\nThank You\nif you liked please **Upvote** !!
95,888
Sum of All Subset XOR Totals
sum-of-all-subset-xor-totals
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty. Given an array nums, return the sum of all XOR totals for every subset of nums. Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.
Array,Math,Backtracking,Bit Manipulation,Combinatorics
Easy
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
2,812
67
The code calculates the bitwise OR of all numbers in the input list using the bitwise OR operator | and stores it in the variable all_or. It then calculates the total number of possible subsets of nums, which is 2^n where n is the length of the list, using the left bit shift operator << and subtracts 1 from it to get the number of subsets excluding the empty set. Finally, it multiplies all_or with the number of subsets to get the sum of XOR of all subsets.\n\nNote that this code does not actually generate all the subsets and calculate their XORs, which would be a brute force approach with O(2^n) time complexity. Instead, it uses a mathematical property of XOR operation that the XOR of two equal numbers is 0 and XOR of a number with 0 is the number itself, and calculates the answer using a formula. This approach has a time complexity of O(n) and is more efficient for larger inputs.\n\n![image.png]()\n# Please Upvote \uD83D\uDE07\n\n## Python3\n```\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n n=len(nums)\n all_or=0\n for i in range(n):\n all_or|=nums[i]\n return all_or*(1<<(n-1))\n```\n![image.png]()
95,928
Sum of All Subset XOR Totals
sum-of-all-subset-xor-totals
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty. Given an array nums, return the sum of all XOR totals for every subset of nums. Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.
Array,Math,Backtracking,Bit Manipulation,Combinatorics
Easy
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
4,689
41
Subsets recursive\n```\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n def sums(term, idx):\n if idx == len(nums):\n return term \n return sums(term, idx + 1) + sums(term ^ nums[idx], idx + 1)\n \n return sums(0, 0)\n```\nSubsets iterative\n```\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n result = 0\n subsets = [0]\n for n in nums:\n new_subsets = subsets.copy()\n for s in subsets:\n new_subsets.append(s ^ n)\n result += new_subsets[-1]\n subsets = new_subsets\n \n return result\n```\nSubsets bit manipulations\n```\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n result = 0 \n for n in range(1 << len(nums)):\n term = 0\n for i in range(len(nums)):\n if n & 1:\n term ^= nums[i]\n n >>= 1\n result += term\n return result\n```\nMath based one-liner\n```\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n return reduce(operator.or_, nums, 0) * 2**(len(nums) - 1)\n```
95,938
Sum of All Subset XOR Totals
sum-of-all-subset-xor-totals
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty. Given an array nums, return the sum of all XOR totals for every subset of nums. Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.
Array,Math,Backtracking,Bit Manipulation,Combinatorics
Easy
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
1,462
11
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int subsetXORSum(int[] nums) {\n \n int n=nums.length;\n int ogans=0;\n for(int i=0;i<(1<<n);i++){\n int sum=0;\n for(int j=0;j<n;j++){\nint bit=i&(1<<j);\nif (bit!=0){\n sum=sum^nums[j];\n} \n}\n ogans+=sum;\n }\nreturn ogans;\n }\n}\n```\n![6233d50d-1433-4516-8d8e-90fb8e13d32f_1677303191.974716.jpeg]()\n
95,946
Sum of All Subset XOR Totals
sum-of-all-subset-xor-totals
The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty. Given an array nums, return the sum of all XOR totals for every subset of nums. Note: Subsets with the same elements should be counted multiple times. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.
Array,Math,Backtracking,Bit Manipulation,Combinatorics
Easy
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
1,287
14
```\nclass Solution(object):\n \n def subsetXORSum(self, nums):\n res = 0\n for i in range(1, len(nums)+1):\n for arr in itertools.combinations(nums, i):\t \n tmp = functools.reduce(lambda x, y: x ^ y, list(arr))\n res += tmp\n return res\n```
95,961
Minimum Number of Swaps to Make the Binary String Alternating
minimum-number-of-swaps-to-make-the-binary-string-alternating
Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not. Any two characters may be swapped, even if they are not adjacent.
String,Greedy
Medium
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
1,097
9
```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n def countSwaps(ch):\n count = 0\n for c in s[::2]:\n if(c != ch):\n count += 1\n \n return count\n \n c0, c1 = s.count(\'0\'), s.count(\'1\')\n \n if(c0 == c1):\n return min(countSwaps(\'0\'), countSwaps(\'1\'))\n \n if(c0 == c1+1):\n return countSwaps(\'0\')\n \n if(c1 == c0+1):\n return countSwaps(\'1\')\n \n return -1\n```
95,978
Minimum Number of Swaps to Make the Binary String Alternating
minimum-number-of-swaps-to-make-the-binary-string-alternating
Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not. Any two characters may be swapped, even if they are not adjacent.
String,Greedy
Medium
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
1,547
26
\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n ones = s.count("1")\n zeros = len(s) - ones \n if abs(ones - zeros) > 1: return -1 # impossible\n \n def fn(x): \n """Return number of swaps if string starts with x."""\n ans = 0 \n for c in s: \n if c != x: ans += 1\n x = "1" if x == "0" else "0"\n return ans//2\n \n if ones > zeros: return fn("1")\n elif ones < zeros: return fn("0")\n else: return min(fn("0"), fn("1")) \n```
95,991
Minimum Number of Swaps to Make the Binary String Alternating
minimum-number-of-swaps-to-make-the-binary-string-alternating
Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal. For example, the strings "010" and "1010" are alternating, while the string "0100" is not. Any two characters may be swapped, even if they are not adjacent.
String,Greedy
Medium
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
757
10
### Explanation\n- When talking about _**swap**_, it\'s almost always a greedy operation, no easy way around\n- There are only two scenarios, either `010101....` or `101010....`, depends on the length of `s`, you might want to append an extra `0` or `1`\n- Simply count the mismatches and pick the less one, see more explanation in the code comment below\n### Implementation\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n ans = n = len(s)\n zero, one = 0, 0\n for c in s: # count number of 0 & 1s\n if c == \'0\':\n zero += 1\n else:\n one += 1\n if abs(zero - one) > 1: return -1 # not possible when cnt differ over 1 \n if zero >= one: # \'010101....\' \n s1 = \'01\' * (n // 2) # when zero == one\n s1 += \'0\' if n % 2 else \'\' # when zero > one \n cnt = sum(c1 != c for c1, c in zip(s1, s))\n ans = cnt // 2\n if zero <= one: # \'101010....\'\n s2 = \'10\' * (n // 2) # when zero == one\n s2 += \'1\' if n % 2 else \'\' # when one > zero \n cnt = sum(c2 != c for c2, c in zip(s2, s))\n ans = min(ans, cnt // 2)\n return ans\n```
95,995
Finding Pairs With a Certain Sum
finding-pairs-with-a-certain-sum
You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class:
Array,Hash Table,Design
Medium
The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1
648
5
The idea is similar to two sum.\nAs `len(nums1)` is much smaller than `len(nums2)`, we will iterate over `nums1` in `count`.\nStore a sorted version of `nums1` so that we can take advantage of early stopping in `count`.\nFor any number `n` in `nums1` and any positive integer `tot`, in order to quickly get how many times `tot - n` appears in `nums`, we create a hash table beforehand which stores the frequency of all elements in `nums2`.\n\n```\nclass FindSumPairs:\n\n def __init__(self, nums1: List[int], nums2: List[int]):\n self.nums1 = sorted(nums1)\n self.nums2 = nums2\n self.hash2 = defaultdict(int)\n for n in nums2:\n self.hash2[n] += 1\n\n def add(self, index: int, val: int) -> None:\n self.hash2[self.nums2[index]] -= 1\n self.nums2[index] += val\n self.hash2[self.nums2[index]] += 1\n\n def count(self, tot: int) -> int:\n result = 0\n for n in self.nums1:\n if n >= tot:\n break\n result += self.hash2[tot - n]\n return result\n```
96,036
Number of Ways to Rearrange Sticks With K Sticks Visible
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it. Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.
Math,Dynamic Programming,Combinatorics
Hard
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
1,263
23
For every `dp(n, k)`, Always consider the shortest stick at first. That is, we manage to insert the shortest stick to every possbile arragement/permutation of length `n - 1`.\n\nThere are two cases to insert the shortest stick (e.g. `1`) to a existing arrangements (e.g. `2, 3` or `3, 2`).\n\n1. Insert the shortest stick at the beginning of a existing arrangement. The shortest stick will be visible. So `k - 1` more visible sticks are needed in the remaining arrangement of length `n - 1`. It is `1 * dp(n - 1, k - 1)`.\n2. Insert the shortest stick at any position except the beginning of a existing arrangements of length `n - 1`. The shortest stick will be invisible as all sticks before it are longer than itself. Also, because it is shortest, all sticks after it won\'t be affected. There are `n - 1` positions to insert, `k` more visible sticks needed. It is `(n - 1) * dp(n - 1, k)`.\n\nFor `dp(3, 2)`:\n\n`1` can be inserted at the beginning of some a existing arrangements with `k = 2 - 1 = 1` visible sticks (because `1` itself is visible). The only candidate arrangement is `[3, 2]`. So here is `[1, 3, 2]`.\n`1` can be inserted at any position except the beginning of some a existing arrangements with `k = 2` visible sticks. The only candidate is `[2, 3]`. So here are `[2,3,1]` and `[2,1,3]`.\n\nThat is `dp(3, 2) = 1 * dp(3 - 1, 2 - 1) + (3 - 1) * dp(3 - 1, 2)`.\n\n**Code**: \n\n```\nM = 10 ** 9 + 7\n\nfrom functools import cache\n\nclass Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n return dp(n, k)\n\n# consider the shortest\n@cache\ndef dp(n, k):\n if n == k:\n return 1\n if n <= 0 or k <= 0:\n return 0\n return (dp(n - 1, k - 1) + (n - 1) * dp(n - 1, k)) % M \n\n# `dp(n, k)` indicates the number of arrangements of `n` distinct sticks with exactly `k` visible sticks. \n# Those `n` **distinct** sticks does NOT have to be numbered from `1` to `n` consecutively.\n```\n\n**Time complexity**: `O(n * k)`\n\n---\n\nSimilarly, we can also consider the longest stick at first. But it results in a larger time complexity. \n**Code**: \n```\n# from math import comb, perm\n\n@cache\ndef dp(n, k):\n if n == k:\n return 1\n if n <= 0 or k <= 0:\n return 0\n ans = 0\n for l in range(k - 1, n - 1 + 1): # l indicates the number of elements in the left\n ans += comb(n - 1, l) * dp(l, k - 1) * perm(n - 1 - l, n - 1 - l)\n ans %= M\n return ans\n```\n**Time complexity**: `O(n*k*(n-k))` (TLE)
96,081
Longer Contiguous Segments of Ones than Zeros
longer-contiguous-segments-of-ones-than-zeros
Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise. Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.
String
Easy
Check every possible segment of 0s and 1s. Is there a way to iterate through the string to keep track of the current character and its count?
2,614
61
```\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n best_one, best_zero, current_one, current_zero = 0, 0, 0, 0\n \n for i in s:\n if i == "1":\n current_zero = 0\n current_one += 1\n else:\n current_zero += 1\n current_one = 0\n \n best_one = max(best_one, current_one)\n best_zero = max(best_zero, current_zero)\n \n return best_one > best_zero\n```
96,134
Longer Contiguous Segments of Ones than Zeros
longer-contiguous-segments-of-ones-than-zeros
Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise. Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.
String
Easy
Check every possible segment of 0s and 1s. Is there a way to iterate through the string to keep track of the current character and its count?
486
12
```\ndef checkZeroOnes(self, s: str) -> bool:\n one_list = s.split("0")\n zero_list = s.split("1")\n \n one_max = max(one_list, key=len)\n zero_max = max(zero_list, key=len)\n \n if len(one_max) > len(zero_max):\n return True\n else:\n return False\n```
96,139
Longer Contiguous Segments of Ones than Zeros
longer-contiguous-segments-of-ones-than-zeros
Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise. Note that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.
String
Easy
Check every possible segment of 0s and 1s. Is there a way to iterate through the string to keep track of the current character and its count?
814
20
```\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n s1 = s.split(\'0\')\n s0 = s.split(\'1\')\n r1 = max([len(i) for i in s1])\n r0 = max([len(i) for i in s0])\n return r1>r0\n```
96,140
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.
Array,Binary Search
Medium
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
11,791
37
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBy linearly checking from speed 1 to 1^7 we will get tle its better to check by binary search because from binary search we can ignore the range which can not be answer.This will help in finding efficiently.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language) \n\nor link in my profile.Here,you can find any solution in playlists monthwise from June 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ntime=distance/speed;\nif speed increase time will decrease.\n\n1. We will perform a binary search to find Minimum Speed to Arrive on Time .\n\n2. Initialize two pointers, `i` and `j`, where `i` points to the minimum possible speed (1) and `j` points to the maximum possible speed (1e7 or 10^7).\n\n3. In each iteration of the binary search:\n - Calculate the mid-point `mid` between `i` and `j`.\n - Check if it is possible to reach office in time `hour` at the speed `mid`. If yes, update the minimum speed candidate and continue the search in the lower half by updating `j = mid - 1`.\n - If it is not possible to reach office at the current speed i.e taking time more than given hour then increase the speed so time will decrease , continue the search in the upper half by updating `i = mid + 1`.\n\n4. The binary search continues until `i` becomes greater than `j`.\n\n5. The function returns the minimum speed to arrive on time \n\n# Complexity\n- Time complexity:$$O(nlogk)$$\n(where k is 10^7)\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# Code\n``` C++ []\nclass Solution {\npublic:\n bool ispossible(vector<int>& dist,int speed,double hour){\n double ans=0;\n for(int i=0;i<dist.size();i++){\n double d=dist[i]*1.0/speed;\n if(i!=dist.size()-1)\n ans=ans+ceil(d);\n else\n ans+=d;\n if(ans>hour)\n return false;\n }\n if(ans<=hour)\n return true;\n return false;\n }\n int minSpeedOnTime(vector<int>& dist, double hour) {\n int i=1;\n int j=1e7;\n int minspeed=-1;\n while(i<=j){\n int mid=i+(j-i)/2;\n if(ispossible(dist,mid,hour)){\n minspeed=mid;\n j=mid-1;\n }\n else\n i=mid+1;\n }\n return minspeed;\n }\n};\n```\n```java []\n\nclass Solution {\n public boolean isPossible(int[] dist, int speed, double hour) {\n double ans = 0;\n for (int i = 0; i < dist.length; i++) {\n double d = dist[i] * 1.0 / speed;\n if (i != dist.length - 1)\n ans = ans + Math.ceil(d);\n else\n ans += d;\n if (ans > hour)\n return false;\n }\n return ans <= hour;\n }\n\n public int minSpeedOnTime(int[] dist, double hour) {\n int i = 1;\n int j = (int) 1e7;\n int minSpeed = -1;\n while (i <= j) {\n int mid = i + (j - i) / 2;\n if (isPossible(dist, mid, hour)) {\n minSpeed = mid;\n j = mid - 1;\n } else\n i = mid + 1;\n }\n return minSpeed;\n }\n}\n\n```\n```python3 []\n\nclass Solution:\n def isPossible(self, dist: List[int], speed: int, hour: float) -> bool:\n ans = 0\n for i in range(len(dist)):\n d = dist[i] * 1.0 / speed\n if i != len(dist) - 1:\n ans = ans + math.ceil(d)\n else:\n ans += d\n if ans > hour:\n return False\n return ans <= hour\n\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n i, j = 1, int(1e7)\n min_speed = -1\n while i <= j:\n mid = i + (j - i) // 2\n if self.isPossible(dist, mid, hour):\n min_speed = mid\n j = mid - 1\n else:\n i = mid + 1\n return min_speed\n\n```\n\n
96,174
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.
Array,Binary Search
Medium
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
1,343
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLike solving the binary search problem\n[875. Koko Eating Bananas\n]()\n# Approach\n<!-- Describe your approach to solving the problem. -->\n![1870. Minimum Speed to Arrive on Time.png]()\n\nIt is important to know that the function time(speed) is a monotonic (decreasing) function. That is the reason why the binary search can be applied.\n\nTo make the binary search efficient, it is suggested to choose the possible smallest searching range. It can derived as follows\n$$\nhour\\geq time(speed) \\\\\n=\\sum_{i=0}^{n-2}ceil(\\frac{dist[i]}{speed})+\\frac{d[n-1]}{speed}\\\\\n\\geq (n-1)+\\frac{d[n-1]}{speed} , if\\ speed \\geq max_{i=0,\\cdots,n-2} (dist[i])\n$$\nIt implies that\n$$\nspeed\\geq \\frac{dist[n-1]}{hour-n-1}\n$$\nSo we can choose the initial value for right\n```\nright=1+max(*max_element(dist.begin(), dist.end()), int(dist[n-1]/(hour-n+1)))\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n \\log (m))$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(1)$\n# Code\n```\nclass Solution {\npublic:\n int n;\n double time(vector<int>& dist, int speed){\n double sum=0;\n for(int i=0; i<n-1; i++)\n sum+=(dist[i]+speed-1)/speed;//ceiling function\n sum+=(double)dist[n-1]/speed;// last one just normal division\n cout<<"speed="<<speed<<",time="<<sum<<endl;\n return sum;\n }\n int minSpeedOnTime(vector<int>& dist, double hour) {\n n=dist.size();\n \n if (hour<=n-1) return -1;\n long long left=1;\n int right=1+max(*max_element(dist.begin(), dist.end()), int(dist[n-1]/(hour-n+1)));\n // cout<<right<<endl;\n int speed;\n while(left<=right)\n {\n int mid=left+(right-left)/2;\n if (time(dist, mid)<=hour){\n speed=mid;\n right=mid-1;\n } \n else left=mid+1;\n }\n return speed;\n }\n};\n```\n# Python code Beats 97.15%\n```\nclass Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n n=len(dist)\n if hour<=n-1: return -1\n\n def time(speed):\n sum=0\n for x in dist[:n-1]:\n sum+=(x+speed-1)//speed #ceiling function\n sum+=dist[n-1]/speed\n return sum\n \n left=1\n right=1+max(max(dist), int(dist[-1]//(hour-n+1)))\n speed=0\n while left<=right:\n mid=(left+right)//2\n if time(mid)<= hour:\n speed=mid\n right=mid-1\n else:\n left=mid+1\n return speed\n```
96,177
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.
Array,Binary Search
Medium
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
2,393
15
<iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n public int minSpeedOnTime(int[] dist, double hour) {\n if(hour<dist.length-1) return -1;\n int l = 0;\n int r = 10000000;\n int m;\n int ans = -1;\n while(l<=r){\n m = (l+r)/2; \n if(check(dist, hour, m)){\n ans = m;\n r = m-1;\n }else{\n l = m+1;\n }\n }\n return ans;\n }\n\n public boolean check(int [] dist, double hour, double speed){\n \n double time = 0;\n int i = 0;\n while(time<=hour && i<dist.length-1){\n time += Math.ceil(dist[i]/speed);\n i++;\n }\n time +=dist[dist.length-1]/speed;\n return (time<=hour);\n }\n}\n```\n\n```\nclass Solution {\npublic:\n int minSpeedOnTime(vector<int>& dist, double hour) {\n if (hour < dist.size() - 1) return -1;\n int l = 0;\n int r = 10000000;\n int m;\n int ans = -1;\n while (l <= r) {\n m = (l + r) / 2; \n if (check(dist, hour, m)) {\n ans = m;\n r = m - 1;\n } else {\n l = m + 1;\n }\n }\n return ans;\n }\n\n bool check(vector<int>& dist, double hour, int speed) {\n double time = 0;\n int i = 0;\n while (time <= hour && i < dist.size() - 1) {\n time += ceil(static_cast<double>(dist[i]) / speed);\n i++;\n }\n time += static_cast<double>(dist[dist.size() - 1]) / speed;\n return (time <= hour);\n }\n};\n\n```\n\n```\nclass Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n if hour < len(dist) - 1:\n return -1\n\n l, r = 1, 10**7\n ans = -1\n\n while l <= r:\n m = (l + r) // 2\n if self.check(dist, hour, m):\n ans = m\n r = m - 1\n else:\n l = m + 1\n\n return ans\n\n def check(self, dist: List[int], hour: float, speed: int) -> bool:\n time = 0.0\n i = 0\n while time <= hour and i < len(dist) - 1:\n time += math.ceil(dist[i] / speed)\n i += 1\n\n time += dist[-1] / speed\n return time <= hour\n\n```
96,178
Jump Game VII
jump-game-vii
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: Return true if you can reach index s.length - 1 in s, or false otherwise.
Two Pointers,String,Prefix Sum
Medium
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
2,010
18
Before I get into the specifics of each method there are 3 cases I checked which make solving the puzzle easier. First, if the target itself can\'t be landed on then there can\'t be a solution. Second, if minJump and maxJump are the same, then there\'s only 1 possible path through the string, does it work? And finally, if minJump is 1, then we can ignore all repeated 0\'s. In practice though, it\'s been faster for me to remove all leading/trailing 0\'s (except for the source/target). Doing this allows the rest of the code to run faster and with less memory usage in some cases. Since I use this code at the start of all of my solutions, I decided to put it here as its own section to save space later.\n\nEdit: I came up with something better for the case when minJump == 1, where instead of removing 0\'s, we can check if a string of 1\'s with length maxJump exists in the puzzle input, since such a string would be impossible to jump over. I\'ve edited the code here to reflect that change, and included the old version of the code at the end of the post for reference. It might be more efficient to find the length of the longest string of 1\'s in the puzzle input, but I didn\'t feel like the extra complexity in the code was worth it. Technically, checking if a run of maxJump \'1\'s exists in the puzzle will disprove the existance of a path for any puzzle, but it\'s only really worth doing this work when minJump is 1.\n\nTime Complexity: O(1) <= O <= O(n)\nSpace Complexity: O(1) <= O <= O(maxJump)\n\n\'\'\'\n\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n #Check for Easy Cases\n I = len(s) - 1 # there are several places having the last index was convenient, so I compute/store it here\n if s[I] == \'1\':\n #It\'s Impossible to Land on the Target\n return False\n elif minJump == maxJump:\n #There\'s Only 1 Possible Path\n return I%minJump == 0 and all(c == \'0\' for c in s[minJump:I:minJump])\n elif minJump == 1:\n #Check if There\'s an Un-Jumpable String of 1\'s\n return \'1\'*maxJump not in s\n else:\n\t\t\t#Solve the Puzzle Using the Method of Your Choice\n\t\t\t...\n\'\'\'\n\n## Method 1: Best-First Search (Simplified A*)\nThis is the first method I tried, and while it is fairly fast, it\'s memory usage is pretty poor. I prioritized indices in a min heap based on their linear distance to the target (which is equivalent to the negated index). The only interesting thing I really did here was that I cast the string to a character array, allowing me to mark nodes as visited in a way that plays nicely in python. I also computed bounds on indecies which can jump directly to the finish, allowing me to end the search a little faster.\n\nTime Complexity: O(nlogn)\nSpace Complexity: O(n)\nBest Performance: 72 ms/19.6 MB : 100%/22%\n\n\'\'\'\n\n\t\t\t...\n\t\t\t\n\t\t\t#Compute the Bounds for Finishing\n X = I - maxJump\n Y = I - minJump\n \n #Update the Minimum Jump for Convenience\n minJump -= 1\n \n #Do a BFS\n s = list(s)\n queue = [0]\n while queue:\n #Get the Next Index\n i = -heappop(queue)\n \n #Check if a Solution was Found\n if i < X:\n #Add Child Nodes to the Queue\n for j in range(i + maxJump, i + minJump, -1):\n #Check if the Index Can be Jumped to\n if s[j] == \'0\':\n #Add the Index to the Queue\n heappush(queue, -j)\n\n #Mark the Index as Visited\n s[j] = \'2\'\n\t\t\t\telif i <= Y:\n\t\t\t\t\treturn True\n \n #No Solution was Found\n return False\n\'\'\'\n\n## Method 2: Depth-First Search\nThis idea here is basically the same as for my bfs, except that I realized that the heuristic I was using basically just gave me a depth-first search anyway, except that the bfs required more work since heap operations run in O(logn) while stack operations run in O(1). The ordering indices are visited isn\'t identical between this dfs and the bfs in method 1, but it\'s close enough that for this puzzle the faster stack operations outweigh the less optimal index ordering, leading to a small performance gain.\n\nTime Complexity: O(n)\nSpace Complexity: O(n)\nBest Performance: 60 ms/18.9 ms : 100%/31%\n\n\'\'\'\n\n\t\t\t...\n\t\t\t\n\t\t\t#Compute the Bounds for Finishing\n X = I - maxJump\n Y = I - minJump\n \n #Update the Maximum Jump for Convenience\n maxJump += 1\n \n #Do a DFS\n s = list(s)\n stack = [0]\n while stack:\n #Get the Next Index\n i = stack.pop()\n \n #Check if a Solution was Found\n if i < X:\n #Add Child Nodes to the Stack\n for j in range(i + minJump, i + maxJump):\n #Check if the Index Can be Jumped to\n if s[j] == \'0\':\n #Add the Index to the Stack\n stack.append(j)\n\n #Mark the Index as Visited\n s[j] = \'2\'\n\t\t\t\telif i <= Y:\n\t\t\t\t\treturn True\n\t\t\t\n #No Solution was Found\n return False\n\'\'\'\n\n## Method 2.5 : DFS with Backtracking\nThis is a much more recent addition to this post, and it was inspired by \n\nDoing the DFS with backtracking helps keep the stack smaller, and avoids some unnecessary computation when the path is nice! It still explores nodes in the same order as the DFS in method 2 though, making it a very efficient solution! I\'ve also posted a recursive version of this in the comments which I find a little easier to follow, but performs worse due to the recursive overhead.\n\nTime Complexity: O(n)\nSpace Complexity: O(n)\nBest Performance: 40 ms/15.2 ms : 100%/98%\n\n\'\'\'\n\n ...\n\t\t\t\n\t\t\t#Compute the Bounds for Stopping \n X = I - maxJump\n Y = I - minJump\n \n #Update the Min Jump for Convenience\n minJump -= 1\n \n #Do a DFS With Backtracking\n s = list(s[:Y + 1])\n stack = [(maxJump, minJump)]\n while stack:\n #Get the Next Range Off the Stack\n i, j = stack.pop()\n \n #Find the Next Largest Jump\n for i in range(min(i, Y), j, -1):\n #Check if the Square Can be Jumped to\n if s[i] == \'0\':\n #Mark the Square as Visited/Reachable\n s[i] = \'2\'\n\n #Check the Case (if neither condition is true then the finish isn\'t reachable from the current position)\n if i < X:\n #Add the Current Range Back to the Stack (for backtracking)\n\t\t\t\t\t\t\tstack.append((i, j))\n\t\t\t\t\t\t\t\n #Add the Next Range to the Stack\n stack.append((i + maxJump, i + minJump))\n \n #Move on to the Next Range on the Stack\n break\n else:\n #A Solution was Found\n return True\n \n #No Solution is Possible\n return False\n\'\'\'\n\n## Method 3: 2 Pointer\nIn this method I also cast the string to a character array so that I could mark which nodes were reachable. The basic idea is that we want to know if the position at the right pointer (\'i\') is reachable. The right pointer will be reachable if it\'s open (s[i] == \'0\') and if there\'s a different reachable index in the appropriate range. So, assuming it\'s open, we increment a left pointer searching for indices we could jump to position i from (these indices were previously marked as reachable when the right pointer landed on them). Also, if the left pointer ever catches up to the right pointer then we return False since there was a chain of unreachable points too long for any future points to be reached. (I think the memory usage for this method is still O(n) becasue I casted the string to a character array, but it\'s a much smaller O(n) than either my bfs or dfs).\n\nTime Complexity: O(n)\nSpace Complexity: O(n)\nBest Performance: 108 ms/15.6 MB : 100%/95%\n\n\'\'\'\n\t\t\t\n\t\t\t...\n\t\t\t\n\t\t\t#Cast the String to a Character Array\n s = list(s)\n s[0] = \'2\'\n \n #2 Pointer Solution\n j = 0\n for i in range(minJump, len(s)):\n #Check if the Right Pointer is Open\n if s[i] == \'0\':\n #Increment the Left Pointer\n k = i - maxJump\n while j < i and (s[j] != \'2\' or j < k):\n j += 1\n \n #Check if the Right Index is Reachable from the Left Index\n if s[j] == \'2\' and j + minJump <= i:\n\t\t\t\t\t\t#Mark the Right Index as Reachable\n s[i] = \'2\'\n\t\t\t\t\telif i == j:\n\t\t\t\t\t\t#No Solution is Possible\n\t\t\t\t\t\treturn False\n \n #Check if the Final Square is Reachable\n return s[I] == \'2\'\n\'\'\'\n## Method 4: Monotonic Deque\nFor this method I took the 2 pointer method, and replaced the left pointer with a monotonically increasing queue of reachable indices. Essentially, every time an index is found to be reachable it gets added to the end of the queue, and then the front of the queue gets removed as necessary. Compared to the 2 pointer solution, this solution has far fewer unnecessary comparisons at the expense of a little extra memory. Also, it doesn\'t require replacing the string with a character array.\n\nTime Complexity: O(n)\nSpace Complexity: O(maxJump - minJump)\nBest Performance: 72 ms/18.2 MB : 100%/55%\n\n\'\'\'\n\n\t\t\t...\n\t\t\t\n\t\t\t#Monotonic Queue Solution\n queue = deque([0])\n for i in range(minJump, len(s)):\n #Check if the Right Pointer is Open\n if s[i] == \'0\':\n #Work Through Possible Values for the Left Index\n k = i - maxJump\n while queue and queue[0] < k:\n queue.popleft()\n \n #Check if the Right Index is Reachable\n if not queue:\n return False\n elif queue[0] + minJump <= i:\n #Add Index i to the Queue Since it\'s Reachable\n queue.append(i)\n \n #Check if the Final Square is Reachable\n return queue[-1] == I\n\'\'\'\n\n## Method 5: Greedy (Cheating)\nOk, so I can\'t really take credit for this since I got the idea by looking at the sample code for the fastest submission on record when I first solved the puzzle (it solved the puzzle in 116 ms). That being said, I think my code is cleaner, and I did end up beating their time by quite a bit, so I thought I\'d include it here. The basic idea of this method is to start at the end and always take the largest jump backwards possible. Unfortunately, it\'s very easy to craft test cases which beat this algorithm, so it isn\'t actually a solution. There are only 2 cases in LeetCode\'s test set which beat this algorithm though, so they\'re easy to hard-code solutions for.\n\nTime Complexity: O(n)\nMemory Complexity: O(1)\nBest Performance: 40 ms/15 MB : 100%/99%\n\n\'\'\'\n\t\t\t\n\t\t\t...\n\t\t\t\n\t\t\t#Check for Cases Which Break the Algorithm\n\t\t\tif s == "0100100010" and minJump == 3 and maxJump == 4:\n\t\t\t\t#Broken Case #1\n\t\t\t\treturn True\n\t\t\telif s == \'0111000110\' and minJump == 2 and maxJump == 4:\n\t\t\t\t#Broken Case #2\n\t\t\t\treturn True\n\t\t\t\n\t\t\t#Update the Minimum Jump for Convenience\n minJump -= 1\n \n #Work Backwards (Always Taking the Largest Possible Step)\n while I > maxJump:\n #Try Jumping Backwards\n for i in range(I - maxJump, I - minJump):\n #Try to Perform the Jump\n if i > minJump and s[i] == \'0\':\n #Decrement I\n I = i\n \n #Move On\n break\n \n #Check if a Jump was Performed\n if i != I:\n break\n \n #Check if a Solution was Found\n return minJump < I <= maxJump\n\'\'\'\n\n## Notes:\nI say that the bfs is a simplified A* algorithm because paths in this problem don\'t have a cost per say. This means that my priority queue was sorting the paths using only the heuristic function: distance to the target. Because of this, the bfs prioritized searching deeper before searching broader, which is why my dfs searched indices in a similar order to my bfs. Because the dfs only performs as well as it did due to this quirk, it is less adaptable to other similar problems than the bfs. Also, it\'s entirely possible that a different heuristic function could improve the bfs, whereas the dfs is essentially at it\'s optimal performance (unless there\'s simple pruning I\'ve missed).\n\nAlthough the monotonic deque method is only really suitable for 1D graphs with limited motion (i.e. you can only jumpt so far from your current position), it could be modified to include a cost/reward for the path taken relatively easilly, and would likely perform better than a bfs on such a problem since it should be able to run in linear time without too much trouble (I think a bfs could also do such a problem in linear time, but it\'d be trickier, and I don\'t think it\'d be as effective).\n\nSince LeetCode updated the submissions for this puzzle to include mine, only the greedy/cheating solution still achieves 100% faster. \n\n## Old Header Code:\n\nTime Complexity: O(1) <= O <= O(n)\nSpace Complexity: O(1) <= O <= O(n)\n\n\'\'\'\n\n\t\t#Check for Easy Cases\n I = len(s) - 1 # there are several places having the last index was convenient, so I compute/store it here\n if s[I] == \'1\':\n #It\'s Impossible to Land on the Target\n return False\n elif minJump == maxJump:\n #There\'s Only 1 Possible Path\n return I%minJump == 0 and all(c == \'0\' for c in s[minJump:I:minJump])\n else:\n #Check if the Minimum Jump is 1\n if minJump == 1:\n #Remove All Leading/Trailing 0\'s\n s = s.strip(\'0\')\n \n #Check if a Solution Was Found\n I = len(s) + 1\n if s and I >= maxJump:\n #Add 1 \'0\' Back On Each End\n s = \'0\' + s + \'0\'\n else:\n #You Can Reach the End\n return True\n\t\t\t\n\t\t\t#Solve the Puzzle Using the Method of Your Choice\n\t\t\t...\n\'\'\'
96,252
Jump Game VII
jump-game-vii
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: Return true if you can reach index s.length - 1 in s, or false otherwise.
Two Pointers,String,Prefix Sum
Medium
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
588
8
In order to understand the sliding window with partial sum solution, I think it is first helpful to understand the brute force O(n^2) DP solution. Technically, it is O(n * (maxJump - minJump)), but worst case maxJump-minJump could be up to n.\n\n```\nclass Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n\t\t# dp[i] represents whether i is reachable\n dp = [False for _ in s]\n dp[0] = True\n\n for i in range(1, len(s)):\n if s[i] == "1":\n continue\n\n\t\t\t# iterate through the solutions in range [i - maxJump, i - minJump]\n\t\t\t# and if any previous spot in range is reachable, then i is also reachable\n window_start = max(0, i - maxJump)\n window_end = i - minJump\n for j in range(window_start, window_end + 1):\n if dp[j]:\n dp[i] = True\n break\n \n return dp[-1] \n\n```\n\nBelow is the optimized O(n) solution with the partial sum sliding window optimization.\n```\nclass Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n # One pass dynamic programming with sliding window\n #\n # The general idea is the same as the brute force\n # bottom-up dynamic programming solution, but instead of\n # always looping through all the previous reachable spots,\n # we maintain a partial sum that counts the number of previous \n # reachable spots in the sliding window [i - maxJump, i - minJump].\n # \n # O(n) time complexity one pass\n # O(n) space complexity for dp array\n\n # dp[i] represents whether i is reachable\n dp = [False for _ in s]\n dp[0] = True\n\n # num_prev_reachable counts the number of previous spots\n # within the sliding window [i - maxJump, i - minJump]\n # that we can jump from to reach i\n num_prev_reachable = 0\n\n for i in range(1, len(s)):\n # the sliding window left bound is being updated to i - maxJump\n # the sliding window right bound is being updated to i - minJump\n \n # exclude previous reachable spot (prev left bound)\n if i > maxJump and dp[i - maxJump - 1]:\n num_prev_reachable -= 1\n # include new reachable spot (new right bound)\n if i >= minJump and dp[i - minJump]:\n num_prev_reachable += 1\n \n # if we can reach this 0 from prev reachable spots, it is reachable\n if s[i] == "0" and num_prev_reachable > 0:\n dp[i] = True\n\n return dp[-1]\n```
96,259
Jump Game VII
jump-game-vii
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: Return true if you can reach index s.length - 1 in s, or false otherwise.
Two Pointers,String,Prefix Sum
Medium
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
661
5
min_i and max_i are the range of positions that we can reach for the next step. If at some point we find the last index in this range, that means the last index is reachable. If my current index i is greater than max_i, we can\'t reach this position and won\'t be able to continue jumping. We ignore those \'invalid\' position (s[i] == 1 or i < min_i) because we can\'t jump from these positions.\n```\nclass Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n if s[-1] == \'1\':\n return False\n n = len(s)\n min_i = max_i = 0\n for i in range(n-1):\n if s[i] == \'1\' or i < min_i:\n continue\n if i > max_i:\n return False\n min_i = i + minJump\n max_i = min(i + maxJump, n-1)\n if min_i <= n-1 <= max_i:\n return True\n return False\n```
96,266
Jump Game VII
jump-game-vii
You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: Return true if you can reach index s.length - 1 in s, or false otherwise.
Two Pointers,String,Prefix Sum
Medium
Consider for each reachable index i the interval [i + a, i + b]. Use partial sums to mark the intervals as reachable.
429
5
Please upvote if it helps!\n```\nclass Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n if s[-1] == \'1\':\n return False\n n, end = len(s), minJump\n reach = [True] + [False] * (n - 1)\n for i in range(n):\n if reach[i]:\n start, end = max(i + minJump, end), min(i + maxJump + 1, n)\n for j in range(start, end):\n if s[j] == \'0\':\n reach[j] = True\n if end == n:\n return reach[-1]\n return reach[-1]
96,268
Stone Game VIII
stone-game-viii
Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following: The game stops when only one stone is left in the row. The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference. Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.
Array,Math,Dynamic Programming,Prefix Sum,Game Theory
Hard
Let's note that the only thing that matters is how many stones were removed so we can maintain dp[numberOfRemovedStones] dp[x] = max(sum of all elements up to y - dp[y]) for all y > x
3,771
55
Regardless of how the game was played till now, ending a move with stone `i` will add sum of all `[0.. i]` stones to your score. So, we first compute a prefix sum to get scores in O(1); in other words, `st[i]` will be a sum of all stones `[0..i]`.\n\nThe first player can take all stones and call it a day if all values are positive. Since there could be negatives, we may want the other player to pick some stones too. \n\nLet\'s say `dp[i]` represents the maximum score difference if the *first player* ends their *first move* with stone `i` or later. We start from the right, and for `i == n - 1` it will be the sum of all stones.\n\nIf the *first players* ends the move with stone `i - 1`, the difference will be `st[i - 1] - dp[i]`. The reason for that is that `dp[i]` now represents the maximum score difference for the *second player*. If the first player ended the move with stone `i - 1`, the second player can play and end their turn with stone `i` or later.\n\nSo, if the first player picks `i - 1`, the difference will be `st[i - 1] - dp[i]`, or if the player picks some later stone, the difference will be `dp[i]`. Therefore, to maximize the difference, we pick the best of these two choices: `dp[i - 1] = max(dp[i], st[i - 1] - dp[i])`.\n\n#### Approach 1: Top-Down\nThis approach looks kind of similar to Knapsack 0/1. We either stop our turn at the stone `i`, or keep adding stones.\n\n**C++**\n```cpp\nint dp[100001] = { [0 ... 100000] = INT_MIN };\nint dfs(vector<int>& st, int i) {\n if (i == st.size() - 1)\n return st[i];\n if (dp[i] == INT_MIN)\n dp[i] = max(dfs(st, i + 1), st[i] - dfs(st, i + 1));\n return dp[i];\n}\nint stoneGameVIII(vector<int>& st) {\n partial_sum(begin(st), end(st), begin(st));\n return dfs(st, 1);\n}\n```\n\n#### Approach 2: Bottom-Up\nTabulation allows us to achieve O(1) memory complexity. Since we only look one step back, we can use a single variable `res` instead of the `dp` array.\n\n**C++**\n```cpp\nint stoneGameVIII(vector<int>& st) {\n partial_sum(begin(st), end(st), begin(st));\n int res = st.back();\n for (int i = st.size() - 2; i > 0; --i)\n res = max(res, st[i] - res);\n return res;\n}\n```\n**Python 3**\n```python\nclass Solution:\n def stoneGameVIII(self, s: List[int]) -> int:\n s, res = list(accumulate(s)), 0\n for i in range(len(s) - 1, 0, -1):\n res = s[i] if i == len(s) - 1 else max(res, s[i] - res)\n return res\n```
96,277
Check if All the Integers in a Range Are Covered
check-if-all-the-integers-in-a-range-are-covered
You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi. Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise. An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.
Array,Hash Table,Prefix Sum
Easy
Iterate over every integer point in the range [left, right]. For each of these points check if it is included in one of the ranges.
793
6
```\nclass Solution:\n def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n \n \n t=[0]*(60)\n \n for i in ranges:\n \n t[i[0]]+=1\n t[i[1]+1]-=1\n \n for i in range(1,len(t)):\n t[i] += t[i-1]\n \n return min(t[left:right+1])>=1\n \n \n \n \n \n```
96,361
Find the Student that Will Replace the Chalk
find-the-student-that-will-replace-the-chalk
There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again. You are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk. Return the index of the student that will replace the chalk.
Array,Binary Search,Simulation,Prefix Sum
Medium
Subtract the sum of chalk[i] from k until k is less than that sum Now just iterate over the array if chalk[i] is less thank k this is your answer otherwise this i is the answer
590
6
```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n prefix_sum = [0 for i in range(len(chalk))]\n prefix_sum[0] = chalk[0]\n for i in range(1,len(chalk)):\n prefix_sum[i] = prefix_sum[i-1] + chalk[i]\n remainder = k % prefix_sum[-1]\n \n #apply binary search on prefix_sum array, target = remainder \n start = 0\n end = len(prefix_sum) - 1\n while start <= end:\n mid = start + (end - start) // 2\n if remainder == prefix_sum[mid]:\n return mid + 1\n elif remainder < prefix_sum[mid]:\n end = mid - 1\n else:\n start = mid + 1\n return start \n```
96,411
Check if Word Equals Summation of Two Words
check-if-word-equals-summation-of-two-words
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
String
Easy
Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.
995
11
**Python :**\n\n```\ndef isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n\tfirstNum, secondNum, targetNum = "", "", ""\n\n\tfor char in firstWord:\n\t\tfirstNum += str(ord(char) - ord(\'a\'))\n\n\tfor char in secondWord:\n\t\tsecondNum += str(ord(char) - ord(\'a\'))\n\n\tfor char in targetWord:\n\t\ttargetNum += str(ord(char) - ord(\'a\'))\n\n\treturn int(firstNum) + int(secondNum) == int(targetNum)\n```\n\n**Like it ? please upvote !**
96,490
Check if Word Equals Summation of Two Words
check-if-word-equals-summation-of-two-words
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
String
Easy
Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.
1,691
20
Replace letters with corresponding numbers, and then use a standard string-to-number conversion.\n\n> `\'a\' - \'0\' == 49`.\n\n**C++**\n```cpp\nbool isSumEqual(string first, string second, string target) {\n auto op = [](string &s) { for(auto &ch : s) ch -= 49; return s; };\n return stoi(op(first)) + stoi(op(second)) == stoi(op(target));\n}\n```\n\n**Python 3**\n```python\nclass Solution:\n def isSumEqual(self, first: str, second: str, target: str) -> bool:\n def op(s: str): return "".join(chr(ord(ch) - 49) for ch in s)\n return int(op(first)) + int(op(second)) == int(op(target))\n```
96,493
Check if Word Equals Summation of Two Words
check-if-word-equals-summation-of-two-words
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
String
Easy
Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.
2,702
22
\n```\ndef isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n numeric_total = lambda s: int(\'\'.join([str(ord(letter) - ord(\'a\')) for letter in s]))\n return numeric_total(firstWord) + numeric_total(secondWord) == numeric_total(targetWord)\n```\n\nAlternatively, the first line can be made into a separate function that returns the total.
96,494
Check if Word Equals Summation of Two Words
check-if-word-equals-summation-of-two-words
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
String
Easy
Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.
1,081
10
# **Solution**\nCreate a dictionary `mapping` that translates a letter into a number.\n\nThe `decoding` function converts a string to a number.\n\n## **How *lambda* works**\nWe use the `lambda` keyword to declare an anonymous function, which is why we refer to them as "lambda functions". An anonymous function refers to a function declared with no name. \n\nThis code:\n```\nlambda i:mapping[i]\n```\n\nEquivalent to this code:\n```\ndef func(i):\n\treturn mapping[i]\n```\n\nYou can read more about anonymous functions at *[this link]()*.\n\n## **How *map* works**\nMap performs the specified function for each item in the list.\n\nExample:\n```\nlist( map(int, [\'1\',\'2\']) ) #[1, 2]\n```\n\n*[More examples.]()*\n\n## **How *join* works**\nThe `join()` method takes all items in an iterable and joins them into one string.\n```\n\' - \'.join([\'a\',\'b\',\'c\']) # \'a - b - c\'\n```\n\n*[Python Join]()*\n\n## **Code**\n```\nclass Solution:\n def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n mapping = {\n \'a\':\'0\', \'b\':\'1\', \'c\':\'2\', \'d\':\'3\', \'e\':\'4\', \'f\':\'5\', \'g\':\'6\', \'h\':\'7\', \'i\':\'8\', \'j\':\'9\'\n }\n \n def decoding(s):\n nonlocal mapping\n return int(\'\'.join(list(map((lambda i:mapping[i]),list(s)))))\n \n return decoding(firstWord) + decoding(secondWord) == decoding(targetWord)\n```\n![image]()\n\n\n
96,496
Check if Word Equals Summation of Two Words
check-if-word-equals-summation-of-two-words
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
String
Easy
Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.
872
6
\n\t\tdictm = {\'a\': \'0\', \'b\': \'1\', \'c\': \'2\', \'d\': \'3\', \'e\': \'4\', \'f\': \'5\', \'g\': \'6\', \'h\': \'7\', \'i\': \'8\', \'j\': \'9\'}\n\n s1 = \'\'.join([dictm[i] for i in firstWord])\n s2 = \'\'.join([dictm[i] for i in secondWord])\n s3 = \'\'.join([dictm[i] for i in targetWord])\n\n return (int(s1) + int(s2)) == int(s3)\n
96,501
Check if Word Equals Summation of Two Words
check-if-word-equals-summation-of-two-words
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.). The numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer. You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive. Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.
String
Easy
Convert each character of each word to its numerical value. Check if the numerical values satisfies the condition.
477
5
**Approach:**\n\nConsider three strings ans, ans1 and ans2 which stores the corresponding values of characters of firstWord, secondWord and targetWord respectively. After converting the strings to integer, just check the difference of ans and ans1 is equal to ans2 or not.\n\n```\ndef isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n ans=""\n ans1=""\n for i in firstWord:\n ans+=str(ord(i)-97)\n for i in secondWord:\n ans1+=str(ord(i)-97)\n ans2=""\n for i in targetWord:\n ans2+=str(ord(i)-97)\n final=int(ans)+int(ans1)\n return int(ans2)==final\n```
96,507
Maximum Value after Insertion
maximum-value-after-insertion
You are given a very large integer n, represented as a string,​​​​​​ and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number. You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n​​​​​​. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n​​​​​​ after the insertion.
String,Greedy
Medium
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
420
5
```\ndef maxValue(self, n: str, x: int) -> str:\n\tif(n[0] == "-"):\n\t\ti = 1\n\t\twhile(i < len(n) and int(n[i]) <= x):\n\t\t\ti += 1\n\telse:\n\t\ti = 0\n\t\twhile(i < len(n) and int(n[i]) >= x):\n\t\t\ti += 1\n\treturn n[:i]+str(x)+n[i:]\n```
96,543
Maximum Value after Insertion
maximum-value-after-insertion
You are given a very large integer n, represented as a string,​​​​​​ and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number. You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n​​​​​​. You cannot insert x to the left of the negative sign. Return a string representing the maximum value of n​​​​​​ after the insertion.
String,Greedy
Medium
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
932
5
If the number is greater than 0 we will iterate from index 0 if the target is greater than the current element we will add it before that.\n\nElse if the number is less than 0 we will iterate from index 0 if target is less than the current we will replace add it there.\n\nWe will also keep a flag to check if we have placed the taget number or not if the flag was not striked in the end we will simply add the target number in the end.\n\n```\nclass Solution:\n def maxValue(self, n: str, x: int) -> str:\n if int(n)>0:\n ans = ""\n flag = False\n for i in range(len(n)):\n if int(n[i])>=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n else:\n n = n[1:]\n ans = ""\n flag = False\n for i in range(len(n)):\n if int(n[i])<=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n ans = "-"+ans\n \n return ans\n \n```
96,549
Process Tasks Using Servers
process-tasks-using-servers
You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​.
Array,Heap (Priority Queue)
Medium
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
595
8
```\nclass Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n res, unavailable, time = [], [], 0\n available = [(weight, id) for id, weight in enumerate(servers)]\n heapify(available)\n\n for task in tasks:\n while unavailable and unavailable[0][0] == time:\n _, weight, id = heappop(unavailable)\n heappush(available, (weight, id))\n\n if len(available) > 0:\n weight, id = heappop(available)\n heappush(unavailable, (time + task, weight, id))\n res.append(id)\n else:\n finishTime, weight, id = heappop(unavailable)\n heappush(unavailable, (finishTime + task, weight, id))\n res.append(id)\n time +=1\n\n return res\n```
96,575
Process Tasks Using Servers
process-tasks-using-servers
You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​.
Array,Heap (Priority Queue)
Medium
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
1,699
19
Use one heap to keep track of servers available and another heap to keep track of the tasks that are still in progress.\n```\nclass Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n servers_available = [(w, i) for i,w in enumerate(servers)]\n heapify(servers_available)\n tasks_in_progress = []\n res = []\n time = 0\n for j,task in enumerate(tasks):\n time = max(time, j)\n if not servers_available:\n time = tasks_in_progress[0][0]\n while tasks_in_progress and tasks_in_progress[0][0] <= time:\n heappush(servers_available, heappop(tasks_in_progress)[1])\n res.append(servers_available[0][1])\n heappush(tasks_in_progress, (time + task, heappop(servers_available)))\n return res\n```\nRun-time analysis:\n`heapify` takes `O(n)` time. The loop iterates `m` times and both heaps have sizes no more than `n`. Thus, the overall run-time is `O(n + mlogn)`.
96,583
Process Tasks Using Servers
process-tasks-using-servers
You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​.
Array,Heap (Priority Queue)
Medium
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
651
6
## Idea :\nUsing two heap one to store the available server for any task and other to store the servers busy in completing the task.\n\'\'\'\n\t\n\tclass Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n \n # sort the servers in order of weight, keeping index \n server_avail = [(w,i) for i,w in enumerate(servers)]\n heapify(server_avail)\n tasks_in_progress = []\n res = []\n st=0\n for j,task in enumerate(tasks):\n #starting time of task\n st = max(st,j)\n \n # if any server is not free then we can take start-time equal to end-time of task\n if not server_avail:\n st = tasks_in_progress[0][0]\n \n # pop the completed task\'s server and push inside the server avail\n while tasks_in_progress and tasks_in_progress[0][0]<=st:\n heapq.heappush(server_avail,heappop(tasks_in_progress)[1])\n \n # append index of used server in res\n res.append(server_avail[0][1])\n \n # push the first available server in "server_avail" heap to "tasks_in_progress" heap\n heapq.heappush(tasks_in_progress,(st+task,heappop(server_avail)))\n \n return res\n\nif any doubt or want more explaination feel free to ask\uD83E\uDD1E\nThank you!!\nif u got helped from this, u can **Upvote**
96,594
Process Tasks Using Servers
process-tasks-using-servers
You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds. Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty. At second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index. If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above. A server that is assigned task j at second t will be free again at second t + tasks[j]. Build an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to. Return the array ans​​​​.
Array,Heap (Priority Queue)
Medium
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
473
5
**Problem statement in simple words:**\nFor each task given in task list we basically need to return the index of server that is going to process that task.\nCriteria for server assignment is:\nFree server with the smallest weight, and in case of a tie, use smaller index.\n\n**Steps:**\n1. Maintaine 2 minHeaps:\n 1. freeServers (weight,index) - List of free servers to process the task.\n\t 2. busyServers (waitingtime,weight,index) ->After assigning task to server from freeServers list, server gets occupied for certain time and wont be available for other tasks until current task is processed. So this server is moved to BusyServers List. Initally it will be empty. Waiting time is currenttime + time taken to process the task which is task[i]. We need waiting time as key in minheap because server with minm waitingTime will be the first server to be availbale for use.\n\n2. If No servers are available in free servers, update the current time to earlist time at which server will be released from busy server list(first element from busy server list).\n\n3. Before processing tasks first check if we have any free server in busyservers(currentTime > waiting time). if yes move it back to free server list.\n4. Assign server to task from freeServerlist,move server to busylist and add index of it in result.\n\n**Complexity -O(mlogn) ** where m is size of tasks and n is size of server list\nImplementation:\n```\nimport heapq\nclass Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n res=[0]*len(tasks)\n freeServers = [(servers[i],i) for i in range(len(servers)) ] #store as (weight,index)\n busyServers=[]\n currentime=0\n heapq.heapify(freeServers)\n for i in range(len(tasks)):\n # currentime=max(currentime,i) --For cases where tasks have to wait because all servers are busy processing other tasks. In that case it will not be equal to index.\n currentime=max(currentime,i) \n if len(freeServers)==0:\n currentime=busyServers[0][0] #if all servers are busy, we need to update the cuurentime to minm waitingtime from busyServer list. For example current time is 3 and all servers are busy and Min waiting time in busyserverlist is 7 seconds, update current time to 7.\n \n # check if server can be moved to available server heap.it can be moved to available servers heap when waitingtime stored in busyserver heap is less than or equal to current time.\n while busyServers and currentime>=busyServers[0][0]:\n waitingtime,weight,index=heapq.heappop(busyServers) #remove server from busyserver list\n heapq.heappush(freeServers,(weight,index)) # add server to free servers list\n \n weight,index=heapq.heappop(freeServers)#get server with min weight for task to use\n\n res[i]=index #add index of server in result for task[i]\n \n heapq.heappush(busyServers,(currentime+tasks[i],weight,index)) #move server from freeservers to busyservers with waiting time\n return res \n \n \n \n```
96,606
Minimum Skips to Arrive at Meeting On Time
minimum-skips-to-arrive-at-meeting-on-time
You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at. After you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting. However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks. Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.
Array,Dynamic Programming
Hard
Is there something you can keep track of from one road to another? How would knowing the start time for each state help us solve the problem?
731
12
Sometimes division leads to precision error in programming languages: **Eg: 2/3+1/3=1.0000000000001**\nSo, we need to ignore such cases. Happened with me during contest. This can be achieved by subtracting value like ```10^-9``` before taking it\'s ceil. \nLast few test cases were initentionally designed in such a way to restrict solutions without precision handling.\n\nRest the DP logic is we are trying to maitain a dp matrix in which we store that at current dist location ```K``` what are the arrival times if we skip ```0,1,...k-1``` checkpoints. \nWe have to initialize the matrix in the first column which denotes the value where 0 skips are considered.\nAnd in the end we iterate the last row of the matrix to find out what is the minimum number of required skips.\n\n**Time Complexity: O(N^2)\nSpace Complexity: O(N^2)**\n\n```\nfrom math import *\nclass Solution:\n def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:\n n=len(dist)\n\t\t# Error Range 10^-9 can be ignored in ceil, so we will subtract this value before taking ceil \n e=1e-9\n mat=[[0 for i in range(n)]for j in range(n)]\n mat[0][0]=dist[0]/speed\n\t\t# Initialization \n\t\t# Values where 0 skips are considered\n for i in range(1,n):\n mat[i][0]=ceil(mat[i-1][0]-e)+dist[i]/speed\n for i in range(1,n):\n for j in range(1,i):\n mat[i][j]=min(ceil(mat[i-1][j]-e),mat[i-1][j-1])+dist[i]/speed\n mat[i][i]=mat[i-1][i-1]+dist[i]/speed\n for i in range(n):\n if mat[-1][i]<=hoursBefore:\n return i\n return -1\n```\n**PS: This the first time I have posted. If you liked please UPVOTE**
96,631
Determine Whether Matrix Can Be Obtained By Rotation
determine-whether-matrix-can-be-obtained-by-rotation
Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.
Array,Matrix
Easy
What is the maximum number of rotations you have to check? Is there a formula you can use to rotate a matrix 90 degrees?
7,384
93
\n```\nclass Solution:\n def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:\n for _ in range(4): \n if mat == target: return True\n mat = [list(x) for x in zip(*mat[::-1])]\n return False \n```
96,679
Determine Whether Matrix Can Be Obtained By Rotation
determine-whether-matrix-can-be-obtained-by-rotation
Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.
Array,Matrix
Easy
What is the maximum number of rotations you have to check? Is there a formula you can use to rotate a matrix 90 degrees?
2,747
56
Lets take an example - `mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]`\n\nFirst rotate 90 degree::\n```\n mat = [list(x) for x in zip(*mat[::-1])]\n```\nStart processing above statement from right to left.\n\n**Step 1->** Reverse ---> `mat[::-1] --> [ [1,1,1], [0,1,0], [0,0,0] ]`\n**Step 2->** Unpack so that it can be passed as separate positional arguments to zip function ----> `(*mat[::-1]) -->[1,1,1], [0,1,0], [0,0,0]`\n\t\t\tNotice missing outer square brackets from step1. In step1 this was a single arguments -**[** [1,1,1] [0,1,0] [0,0,0] **]** and after unpacking these are 3 arguments - [1,1,1],[0,1,0],[0,0,0].\n**Step 3 ->** zip it ---->`zip(*mat[::-1]) ---->zip( [1,1,1],[0,1,0],[0,0,0] )`\n\t\t\t\tAs per definition -zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. \n\t\t\t\tso zip( [**1**,1,1],[**0**,1,0],[**0**,0,0] ) takes first column value from all 3 arguments and makes tuple-(1, 0, 0)\n\t\t\t\tthen zip( [1,**1**,1],[0,**1**,0],[0,**0**,0] ) takes 2nd column value from all 3 arguments and makes tuple -(1, 1, 0)\n\t\t\t\tthen zip( [1,1,**1**],[0,1,**0**],[0,0,**0**] ) takes 3rd column value from all 3 arguments and makes tuple -(1, 0, 0)\n\t\t\t\tso complete output ---> (1, 0, 0), (1, 1, 0), (1, 0, 0) . \n\t\t\t\tNotice output of step is 3 tuples.\n\t\t\t\t\n **Step 4 -->** convert output of step 3 into the list--->` [list(x) for x in zip(*mat[::-1])]`--->\n "for loop" executes 3 times for 3 tuples in zip - (1, 0, 0), (1, 1, 0), (1, 0, 0) and converts this into list---> **[** [1,0,0], [1,1,0], [1,0,0] **]**\n Now repeate step 1 to 4, four times to check if given output can be obtained by 90 degree roation or 180 degree roation or 270 degree or 360 degree roation.\n\t After step 4 new value of mat = \t [[1,0,0], [1,1,0], [1,0,0]]. \n\t Lets rotate it one more time:\n\t `mat = [list(x) for x in zip(*mat[::-1])]`\n\t` mat[::-1]`--->[ [1, 0, 0], [1, 1, 0], [1, 0, 0] ]\n\t` zip(*mat[::-1])` --->zip( [1, 0, 0 ], [1, 1, 0], [1, 0, 0] )-->(1, 1, 1), (0, 1, 0), (0, 0, 0)\n` [list(x) for x in zip(*mat[::-1])]` --> [ [ 1, 1,1], [0, 1, 0], [0, 0, 0] ]\n \nthis transforms mat to [ [ 1, 1,1], [0, 1, 0], [0, 0, 0] ] which is equal to given target in problem so return `True`.\n\t \n\t \n\n\n\n\n\n\t \n\t \n\t \n\t \n\t \n\t \n\t \n\t \n\t \n\t \n\t \n\t\n\t \n\t \n\t \n\n\n\n\n\n```\nclass Solution:\n def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:\n for _ in range(4): \n if mat == target: return True\n mat = [list(x) for x in zip(*mat[::-1])]\n return False\n```
96,687
Determine Whether Matrix Can Be Obtained By Rotation
determine-whether-matrix-can-be-obtained-by-rotation
Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.
Array,Matrix
Easy
What is the maximum number of rotations you have to check? Is there a formula you can use to rotate a matrix 90 degrees?
1,164
13
```\nAn easy way to Rotate a matrix once by 90 degrees clockwise, \nis to get the **transpose of a matrix and interchange the \'j\'th and \'n-1-j\'th column**, \nfor 0<=j<=n-1 where n is the number of columns in matrix.\n```\n![image]()\n```\nTo get the transpose:\n\t\t\tfor i in range(n):\n for j in range(i+1,n):\n mat[i][j],mat[j][i] = mat[j][i],mat[i][j]\nTo interchange columns:\n\t\t\t for i in range(n):\n for j in range(n//2):\n mat[i][j], mat[i][n-1-j] = mat[i][n-1-j], mat[i][j]\nAs soon as we get that the rotated matrix is equal to target, we simply return true,\nelse we rotate it again(at max 4 times, as we will get the original matrix back after 4th rotation).\n```\n\nThe full code:\n```\ndef findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:\n n = len(mat)\n for times in range(4):\n for i in range(n):\n for j in range(i+1,n):\n mat[i][j],mat[j][i] = mat[j][i],mat[i][j] # swap(mat[i][j],mat[j][i])\n for i in range(n):\n for j in range(n//2):\n mat[i][j], mat[i][n-1-j] = mat[i][n-1-j], mat[i][j] #swap(mat[i][j], mat[i][n-1-j])\n if(mat == target):\n return True\n return False\n```
96,722
Reduction Operations to Make the Array Elements Equal
reduction-operations-to-make-the-array-elements-equal
Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal.
Array,Sorting
Medium
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
1,181
12
\n```\nclass Solution:\n def reductionOperations(self, nums: List[int]) -> int:\n n=len(nums)\n nums.sort(reverse=True)\n ans=0\n for i in range(n-1):\n if nums[i]>nums[i+1]:\n ans+=i+1\n return ans \n```
96,724
Reduction Operations to Make the Array Elements Equal
reduction-operations-to-make-the-array-elements-equal
Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal.
Array,Sorting
Medium
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
1,526
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse Counter(nums) to make nums into a hash table, then sort it by the number, which would also reduce the complexity.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe could make the nums into Counter and sort into an array, we can name it arr. For each element in the arr in the arr, it has [num, cnt]. The num needs to reduce idx times to become the smallest number, where idx is its index in arr. And there\'s cnt numbers, multiple it by cnt. Add them all together, we can get the final answer.\n# Complexity\n- Time complexity:$$O(n + k logk)$$\n<!-- Add your time complexity here, e.g. -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. -->\nk is the number of different numbers.\nThe time complexity would be much better than $$O(n logn)$$ if there\'re a lot of duplicated numbers\n\n# Code\n```\nclass Solution:\n def reductionOperations(self, nums: List[int]) -> int:\n return sum([i*cnt for i, (num, cnt) in enumerate(sorted(Counter(nums).items()))])\n```
96,725
Reduction Operations to Make the Array Elements Equal
reduction-operations-to-make-the-array-elements-equal
Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal.
Array,Sorting
Medium
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
854
8
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n1. **Sorting:**\n\n - The code sorts the input vector nums in non-decreasing order using `sort()`.\n1. **Iterating Through the Sorted Vector:**\n\n - It iterates through the sorted vector and counts the number of unique elements.\n - For each new unique element encountered, it increments the temporary count `temp`.\n1. **Calculating Sum:**\n\n - For each iteration, it adds the `temp` count to the `sum`.\n - `sum` accumulates the total number of operations required for reduction.\n\n\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 reductionOperations(vector<int>& nums) {\n sort(nums.begin(), nums.end()); // Sort the input vector \'nums\' in non-decreasing order\n int n = nums.size(); // Get the size of the input vector\n int sum = 0, temp = 0; // Initialize variables to keep track of sum and temporary count\n\n // Iterate through the sorted vector\n for (int i = 1; i < n; i++) {\n // Check if the current element is different from the previous one\n if (nums[i] != nums[i - 1]) {\n temp++; // Increment temporary count for a new unique element\n }\n sum += temp; // Add the temporary count to the sum for each iteration\n }\n\n return sum; // Return the final sum, which represents the number of operations performed\n }\n};\n\n\n\n```\n```C []\n\nint reductionOperations(int* nums, int numsSize) {\n qsort(nums, numsSize, sizeof(int), compare); // Sort the input array \'nums\' in non-decreasing order\n int sum = 0, temp = 0; // Initialize variables to keep track of sum and temporary count\n\n // Iterate through the sorted array\n for (int i = 1; i < numsSize; i++) {\n // Check if the current element is different from the previous one\n if (nums[i] != nums[i - 1]) {\n temp++; // Increment temporary count for a new unique element\n }\n sum += temp; // Add the temporary count to the sum for each iteration\n }\n\n return sum; // Return the final sum, which represents the number of operations performed\n}\n\n// Comparison function for qsort\nint compare(const void* a, const void* b) {\n return (*(int*)a - *(int*)b);\n}\n\n\n\n```\n\n\nclass Solution {\n public int reductionOperations(int[] nums) {\n Arrays.sort(nums); // Sort the input array \'nums\' in non-decreasing order\n int n = nums.length; // Get the size of the input array\n int sum = 0, temp = 0; // Initialize variables to keep track of sum and temporary count\n\n // Iterate through the sorted array\n for (int i = 1; i < n; i++) {\n // Check if the current element is different from the previous one\n if (nums[i] != nums[i - 1]) {\n temp++; // Increment temporary count for a new unique element\n }\n sum += temp; // Add the temporary count to the sum for each iteration\n }\n\n return sum; // Return the final sum, which represents the number of operations performed\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def reductionOperations(self, nums: List[int]) -> int:\n nums.sort() # Sort the input list \'nums\' in non-decreasing order\n n = len(nums) # Get the size of the input list\n sum_val = 0\n temp = 0\n\n # Iterate through the sorted list\n for i in range(1, n):\n # Check if the current element is different from the previous one\n if nums[i] != nums[i - 1]:\n temp += 1 # Increment temporary count for a new unique element\n sum_val += temp # Add the temporary count to the sum for each iteration\n\n return sum_val # Return the final sum, which represents the number of operations performed\n\n\n```\n\n```javascript []\nvar reductionOperations = function(nums) {\n nums.sort((a, b) => a - b); // Sort the input array \'nums\' in non-decreasing order\n let sum = 0, temp = 0; // Initialize variables to keep track of sum and temporary count\n\n // Iterate through the sorted array\n for (let i = 1; i < nums.length; i++) {\n // Check if the current element is different from the previous one\n if (nums[i] !== nums[i - 1]) {\n temp++; // Increment temporary count for a new unique element\n }\n sum += temp; // Add the temporary count to the sum for each iteration\n }\n\n return sum; // Return the final sum, which represents the number of operations performed\n};\n\n\n```\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
96,728
Reduction Operations to Make the Array Elements Equal
reduction-operations-to-make-the-array-elements-equal
Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal.
Array,Sorting
Medium
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
598
7
# Intuition\nGiven an array, we aim to find the number of operations needed to make all elements equal. To do so, we need to strategically reduce larger elements to the smallest element in the array.\n\n# Approach\n1. Count the frequencies of each number: Create a map or dictionary to store the frequencies of each element in the array.\n2. Sort the elements: Sort the array in descending order to start with the largest elements.\n3. Iterate through the sorted array: As we iterate through the sorted array, keep track of the number of operations required to reduce elements.\n - For each element in the sorted array, increment the count of operations needed to make it equal to the smallest element (which will be at the end after sorting).\n - Accumulate the count of operations.\n4. Return the total count of operations: This count represents the minimum number of operations required to make all elements equal.\n# Complexity Analysis\n- Time Complexity:\n - Counting the frequencies of elements takes O(n) time.\n - Sorting the array takes O(n log n) time.\n - Iterating through the sorted array to count operations takes O(n) time.\n - Therefore, the overall time complexity is O(n log n).\n- Space Complexity:\n - Space required to store the frequencies in a map or dictionary is O(n).\n - Sorting the array in place might take O(log n) extra space due to recursive calls in certain sorting algorithms like quicksort.\n - Therefore, the overall space complexity is O(n).\n\n\n\n\n\n# Code\n``` C++ []\n#include <vector>\n#include <map>\n\nclass Solution {\npublic:\n int reductionOperations(std::vector<int>& nums) {\n std::map<int, int> count;\n int operations = 0;\n\n // Count the frequency of each number\n for (int num : nums) {\n count[num]++;\n }\n\n int prevFreq = 0;\n for (auto it = count.rbegin(); it != count.rend(); ++it) {\n operations += prevFreq;\n prevFreq += it->second;\n }\n\n return operations;\n }\n};\n\n```\n``` Python []\nclass Solution(object):\n def reductionOperations(self, nums):\n max_val = max(nums)\n freq = [0] * (max_val + 1)\n\n for num in nums:\n freq[num] += 1\n\n operations = 0\n current = max_val\n\n while True:\n while current > 0 and freq[current] == 0:\n current -= 1\n \n if current == 0:\n break\n\n next_largest = current - 1\n while next_largest > 0 and freq[next_largest] == 0:\n next_largest -= 1\n\n if next_largest == 0:\n break\n \n operations += freq[current]\n freq[next_largest] += freq[current]\n freq[current] = 0\n\n return operations\n```
96,735
Reduction Operations to Make the Array Elements Equal
reduction-operations-to-make-the-array-elements-equal
Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Return the number of operations to make all elements in nums equal.
Array,Sorting
Medium
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
3,104
31
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to make all elements in the array equal by following a set of operations. The operations involve finding the largest value, determining the next largest value smaller than the current largest, and reducing the corresponding element to the next largest value. The task is to calculate the total number of operations required.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the array in non-decreasing order.\n2. Iterate through the sorted array from the end.\n3. For each unique value encountered, add the difference between the total length of the array and the current index to the result.\n - This accounts for the number of times the current value needs to be reduced to reach the smallest value.\n - Update the total number of operations accordingly.\n\n# Complexity\n- Sorting the array takes O(n log n) time, where n is the length of the array.\n- Iterating through the array once takes O(n) time.\n- Overall time complexity: O(n log n)\n- Space complexity: O(1) (since the sorting is done in-place)\n\n# Code\n## Java\n```\nclass Solution {\n public int reductionOperations(int[] nums) {\n Arrays.sort(nums);\n int si=nums.length;\n int ans=0;\n for(int i=nums.length-1;i>0;i--){\n if(nums[i-1]!=nums[i]){\n ans+=si-i;\n }\n }\n return ans;\n }\n}\n```\n## C++\n```\nclass Solution {\npublic:\n int reductionOperations(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int size = nums.size();\n int ans = 0;\n for (int i = size - 1; i > 0; --i) {\n if (nums[i - 1] != nums[i]) {\n ans += size - i;\n }\n }\n return ans;\n }\n};\n```\n## Python\n```\nclass Solution(object):\n def reductionOperations(self, nums):\n nums.sort()\n size = len(nums)\n ans = 0\n for i in range(size - 1, 0, -1):\n if nums[i - 1] != nums[i]:\n ans += size - i\n return ans\n \n```\n### Summary:\nThe approach efficiently utilizes the sorted nature of the array to calculate the number of operations needed to make all elements equal. The time complexity is reasonable, making it a practical solution for the given problem.\n\n---\n\n![upvote.png]()\n
96,743
Minimum Number of Flips to Make the Binary String Alternating
minimum-number-of-flips-to-make-the-binary-string-alternating
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Return the minimum number of type-2 operations you need to perform such that s becomes alternating. The string is called alternating if no two adjacent characters are equal.
String,Greedy
Medium
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
1,801
36
For me it was quite a tricky question to understand but thanks to some help from Leetcode Discussion and YouTube, I got the main idea of this problem. And Now I feel too dumb to not get it myself xD\n\nAnyways, here is an explanation of what we have to do. \n\nWe are given a binary string and we want to make it alternating. Alternating means each 0 after each 1 and 1 after each 0. e.g. for a binary string of length = 3, we have two valid alternating string -> 101 and 010. In fact, for every length, there are only two valid alternting strings which is obvious because there are only two types of numbers in a binary string - 1 and 0.\n\nFor a moment, forget that type-1 operation exists. Just think that we are given a string and we can flip a bit. We want to find minimum number of flips we can do so that this string is alternating. How will you do it? Will you take each bit, flip it and check if that makes string alternating? Ofcourse not. \n\nBecause we know that for any length, there are only two valid alternating strings, we can simply compare each position with each valid string. And if the number at that position differs, we need to flip. In other words -\n\n\t\tMinimum Number of Flips = Minimum Number of differences between given string and valid strings\n\n\t\tlets say s = "111000"\n\nSince length is 6, what are the valid alternating binary strings of length 6? They are \n\t\t\n\t\t\tvalid1 = "101010"\n\t\t\tvalid2 = "010101"\n\nSo, lets compare s with valid1 first\n\n\t\t\ts = "111000"\n\t\t\tvalid1 = "101010"\n\t\t\t\n\t\t\tFor each position in s, check what is the value at same position in valid1. If they are not same, we need to flip.\n\t\t\t\n\t\t\tSo we get differences = 2\n\t\nNow lets compare s with valid2\n\t\t\t\n\t\t\ts = "111000"\n\t\t\tvalid1 = "010101"\n\t\t\t\t\t\t\n\t\t\tWe get differences = 4\n\t\t\t\nSo that means, we can simply flip 2 bits to make the string alternating such that it starts with 1, instead of flipping 4 bits such that it starts with 0.\n\nNow we add in the type-1 operation. It says that we can take a character from beginning of string "s" and add it to the end of it in order to minimize the flips. What that means?\n\n\tLets say we performed type-1 operation once on s = "111000"\n\tThen the first "1" will be moved to end. So string will become "110001"\n\t\n\tAnd now again, we have to do the same thing as above \n\ti.e., compare it with valid1 and valid2 to see which one results in least difference.\n\t\nWhat is the maximum number of type-1 operations we can do? It is equal to length of string. Why? Because if we take the whole string and append it to itself, that means we get the same string in return.\n\n\ts = "111000" \n\t1 type-1 operation, s = "110001"\n\t2 type-1 operations, s = "100011"\n\t3 type-1 operations, s = "000111"\n\t4 type-1 operations, s = "001110"\n\t5 type-1 operations, s = "011100"\n\t6 type-1 operations, s = "111000" => Back to original\n\t\nSo it makes no sense to go above 6 in this case as we would be doing the same work again. \n\nSo that means, instead of manually taking each character and moving it to end, why not we double the given string "s" .\n\n\ts = "111000" to s + s\n\tsuch that new s => "111000111000"\n\t\n\tAnd now, each window of size = 6 represents each type-1 operation.\n\t\n\tFirst window of size 6 -> "111000"\n\tSecond window of size 6 -> "110001"\n\tThird window of size 6 -> "100011"\n\tFourth window of size 6 -> "000111"\n\tFifth window of size 6 -> "001110"\n\tSixth window of size 6 -> "011100"\n\tSeventh window of size 6 -> "111000" => Back to original\n\t\nSo we had to do no extra work to take each character from beginning and move it to end.\n\nAnd now. Just think how we were comparing the string with valid1 and valid2.\n\n\t\ts = "111000"\n\t\tvalid1 = "101010"\n\t\tDifferences = 2\n\t\t\nWhen we take a character out from "s" and move it to end, then that means, we need to do the same with valid1 right? Because we won\'t be recalculating the whole difference again when only one character has changed. \n\nIn other words, as we slide the window, all that we are doing is just check the one extra character that we added at the end and also before sliding the window remove all the calculations for that character.\n\t\t\nAnd the rest, is a general sliding window template.\n\nYou might be thinking does type-1 operation even helps in minimizing the flips? Because for above example, even if we don\'t do type-1 operation, we get 2 minimum flips. And after doing as well, we get 2. Yes, you are right. For some strings, this doubling of strings is not required at all. That\'s the case with even number of characters in a given string. So, if length of string is even, there is no need to double the string. But when there is an odd number, we may get a minimum value after doing type-1 operation. Try with s = "11100" you will understand.\n\nBecause in "11100" if we take four characters from beginning and append them to end we get "01110\' ANd now, all we need to do is 1 flip for the 1 at the center to make it "01010". So minimum Flips = 1\n\nBut had we not done the type-1 operation at all, then minimum flips would be 2. i.e., flipping the 2nd "1" and last "0" to get "10101"\n\n\n```\ndef minFlips(self, s: str) -> int:\n # Minimum number of flips to return\n minimumFlips = len(s)\n \n # Window Size\n k = len(s)\n \n # For strings of odd length, double them\n # So that we do not have to manually perform type-1 operation \n # that is, taking each bit and moving to end of string\n s = s if k % 2 == 0 else s + s\n \n # There can be only two valid alternating strings as we only have 0 and 1\n # One starts with 0 and other with 1\n # e.g. for a string of length 3 we can have either 010 or 101\n altArr1, altArr2 = [], [] \n for i in range(len(s)):\n altArr1.append("0" if i % 2 == 0 else "1")\n altArr2.append("1" if i % 2 == 0 else "0")\n \n alt1 = "".join(altArr1)\n alt2 = "".join(altArr2)\n \n \n # Minimum Number of operations = Minimum Difference between the string and alt2 and alt3\n diff1, diff2 = 0,0\n \n # Sliding Window Template Begins\n i,j = 0,0\n \n \n while j < len(s):\n if s[j] != alt1[j] : diff1 += 1\n if s[j] != alt2[j] : diff2 += 1\n \n if j - i + 1 < k: j += 1\n else:\n minimumFlips = min(minimumFlips, diff1, diff2)\n if s[i] != alt1[i] : diff1 -= 1\n if s[i] != alt2[i] : diff2 -= 1\n i += 1\n j += 1\n \n return minimumFlips\n```
96,777
Minimum Number of Flips to Make the Binary String Alternating
minimum-number-of-flips-to-make-the-binary-string-alternating
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Return the minimum number of type-2 operations you need to perform such that s becomes alternating. The string is called alternating if no two adjacent characters are equal.
String,Greedy
Medium
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
1,457
8
* **Type-1** operation doesn\'t count. It will only benefit when the length of s is **odd** (will allow one-time two adjacent positions with same value, e.g. moving the first \'1\' of \'110\' to the end, it will become valid \'101\'.\n* We track 4 DP variables to count the # of Type-2 operations:\n\t* **start_1**: final valid string starting with \'1\', e.g. \'1010\'\n\t* **start_0**: the final valid string starting with \'0\', e.g. \'0101\'\n\t* **start_1_odd**: only works when s with odd length. positions after type-1 operation are the same with start_1\n\t* **start_0_odd**: only works when s with odd length. positions after type-1 operation are the same with start_0\n* **prev**: 0 or 1 (initial val as 0, used to track start_1)\n\t* if current **val** == **prev** (conflict with start_1): 1) flip **start_1** (+=1); 2) for odd length s: perform Type-1 operation move current **start_1** to **start_0_odd**, flip **start_1_odd**\n\t* if current **val** != **prev** (conflict with start_0): 1) flip **start_0** (+=1); 2) perform Type-1 operation for odd length s, move current **start_0** to **start_1_odd**, flip **start_0_odd**\n\t* after each iteration, switch the value of prev, i.e. prev = 1- prev\n* In the end, pick the smallest operations from: start_1, start_0, start_1_odd, start_0_odd\n```\nclass Solution:\n def minFlips(self, s: str) -> int:\n prev = 0\n start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize\n odd = len(s)%2\n for val in s:\n val = int(val)\n if val == prev:\n if odd:\n start_0_odd = min(start_0_odd, start_1)\n start_1_odd += 1\n start_1 += 1\n else:\n if odd:\n start_1_odd = min(start_1_odd, start_0)\n start_0_odd += 1\n start_0 += 1\n prev = 1 - prev\n return min([start_1, start_0, start_1_odd, start_0_odd])\n```
96,802
Minimum Number of Flips to Make the Binary String Alternating
minimum-number-of-flips-to-make-the-binary-string-alternating
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Return the minimum number of type-2 operations you need to perform such that s becomes alternating. The string is called alternating if no two adjacent characters are equal.
String,Greedy
Medium
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
1,427
6
* so first of all basic idea is that we add s at the back because for every possible s that is a n length piece\n* we try to see what no changes it req for that we make it 2n length now we make to dummty strings s1 and s2 as only two alternative are available .... one starts with one 10101 and another starts with 01010101 \n* . so now start for loop with i if s1[i]!=s[i] then we want a change so we increase ans1 by + 1 now if we reach n-1 index we have a n lenrtgh string so we check with ans what if we got a min answer so ans1 ans2 and ans are compared and minimum value stored in ans\n* ....now we go to n th index now we remove the first index i=0 from s but we check if that index was earlier if changed \n* then we did ans-=1 so as to nullify its effect in ans so wo a new ans1 and ans2\nfor this n len string from index 1 to n and so on we go to n+1 then we remove 2 nd index element ...and so on and \n* we return ans at end which is min of all iterations\n**if u like the explanation plz do upvote it ..**\n\n```py\nclass Solution(object):\n def minFlips(self, s):\n n=len(s) # we save this length as it is length of window\n s+=s #we add this string because we can have any possibility like s[0]->s[n-1] or s[2]->s[n+1]meaning is that any continous variation with n length ... \n ans=sys.maxint #assiging the answer max possible value as want our answer to be minimum so while comparing min answer will be given \n ans1,ans2=0,0#two answer variables telling amount of changes we require to make it alternative\n s1=""#dummy string like 10010101\n s2=""#dummy string like 01010101\n for i in range(len(s)):\n if i%2==0:\n s1+="1"\n s2+="0"\n else :\n s1+="0"\n s2+="1"\n for i in range(len(s)):\n if s[i]!=s1[i]:#if they dont match we want a change so ++1\n ans1+=1\n if s[i]!=s2[i]:\n ans2+=1\n \n if i>=n:\n if s[i-n]!=s1[i-n]:#now we have gone ahead so removing the intial element but wait if that element needed a change we added ++ earlier but now he is not our part so why we have his ++ so to nullify its ++ we did a -- in string\n ans1-=1\n if s[i-n]!=s2[i-n]:\n ans2-=1\n if i>=n-1#when i reaches n-1 we have n length so we check answer first time and after that we always keep seeing if we get a less answer value and after the loop we get \n ans=min([ans,ans1,ans2])\n return ans \n
96,804
Minimum Space Wasted From Packaging
minimum-space-wasted-from-packaging
You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box. The package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces. You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes. Return the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.
Array,Binary Search,Sorting,Prefix Sum
Hard
Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?
659
5
\n```\nclass Solution:\n def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:\n packages.sort()\n prefix = [0]\n for x in packages: prefix.append(prefix[-1] + x)\n \n ans = inf \n for box in boxes: \n box.sort()\n if packages[-1] <= box[-1]: \n kk = val = 0 \n for x in box: \n k = bisect_right(packages, x)\n val += (k - kk) * x - (prefix[k] - prefix[kk])\n kk = k\n ans = min(ans, val)\n return ans % 1_000_000_007 if ans < inf else -1 \n```\n\nEdited on 6/6/2021\nIt turns out that we don\'t need prefix sum (per @lee215). \n\n```\nclass Solution:\n def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:\n packages.sort()\n \n ans = inf \n for box in boxes: \n box.sort()\n if packages[-1] <= box[-1]: \n kk = val = 0 \n for x in box: \n k = bisect_right(packages, x)\n val += (k - kk) * x\n kk = k\n ans = min(ans, val)\n return (ans - sum(packages)) % 1_000_000_007 if ans < inf else -1 \n```
96,836
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
7,083
78
![image]()\n\nThe Full Code:\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n indx = -1\n count = 0\n n = len(nums)\n \n # count the number of non-increasing elements\n for i in range(n-1):\n if nums[i] >= nums[i+1]:\n indx = i\n count += 1\n \n #the cases explained above\n if count==0:\n return True\n \n if count == 1:\n if indx == 0 or indx == n-2:\n return True\n if nums[indx-1] < nums[indx+1] or(indx+2 < n and nums[indx] < nums[indx+2]):\n return True\n \n return False\n```\nTime: O(n) for counting the number of non-increasing elements.\nSpace = O(1).
96,880
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
1,155
10
Similar to [665. Non-decreasing Array]()\n\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n isRemove = False\n for i in range(1, len(nums)):\n if nums[i] <= nums[i-1]:\n if isRemove: return False\n if i > 1 and nums[i] <= nums[i-2]:\n nums[i] = nums[i-1]\n else:\n nums[i-1] = nums[i]\n isRemove = True\n\n return True \n```
96,883
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
325
6
# Approach\nStarting from the second element of the array we check if it is less or equal to the previous one. In this case the array is not strictly increasing and we need to fix it and we have two way to do this:\n - if `nums[i-2] < nums[i] < nums[i-1]` ( e.g 2, 10, 5 (i), 6 ) remove `i-1` (10) fix the situation.\n - If `nums[i] < nums[i-1] and nums[i] <= nums[i-2]` (e.g 2, 3, 2(i), 4(j), 5 ) we need to remove `i` to fix the situation.\n \nSince we compare always the `i` value with `i-1` value the first case does not alter the algorithm. This is not true for the second case, because at the next iteration we should compare the position `j=i+1` with the position `i-1` (because we have removed the `i` position). To avoid this issue we are going to copy the `i-1` element in `i` position. \n\nIn each case we keep track of the removal using a variable `removed_once`. If we found another element that is not strictly increasing we return `False`.\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# Code\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n removed_once = False\n \n for i in range(1, len(nums)):\n if nums[i] <= nums[i-1]:\n if removed_once:\n return False\n if i > 1 and nums[i] <= nums[i-2]:\n nums[i] = nums[i-1]\n\n removed_once = True\n \n return True\n```
96,889
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
571
5
```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n for i in range(len(nums)):\n temp=nums[:i]+nums[i+1:]\n if temp==sorted(set(temp)):\n return True\n return False\n```\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n flag=False\n for i in range(1,len(nums)):\n if nums[i]<=nums[i-1]:\n if flag:\n return False\n if i>1 and nums[i]<=nums[i-2]:\n nums[i]=nums[i-1]\n else:\n nums[i-1]=nums[i]\n flag=True\n return True\n```\n# please upvote me it would encourage me alot\n
96,898
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
722
5
class Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n for i in range(len(nums)):\n res=nums.copy()\n #res.remove(nums[i])\n res.pop(i)\n if res == sorted(set(res)):\n return True\n else:\n continue\n return False\n \n \n \n \n\n \n \n \n \n
96,902
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
2,174
14
**Time Complexity : O(n)**\n**Java**\n```\nclass Solution {\n public boolean canBeIncreasing(int[] nums) {\n int count = 0;\n for(int i=1; i<nums.length; i++){\n if(nums[i] <= nums[i-1]){ \n count++;\n if(i>1 && nums[i] <= nums[i-2]) nums[i] = nums[i-1]; \n }\n }\n return count <= 1;\n }\n}\n```\n**JavaScript**\n```\nvar canBeIncreasing = function(nums) {\n let count = 0\n for(let i=1; i<nums.length; i++){\n if(nums[i] <= nums[i-1]){\n count++;\n if(i>1 && nums[i] <= nums[i-2]) nums[i] = nums[i-1]\n }\n }\n return count <= 1\n};\n```\n**Python**\n```\nclass Solution(object):\n def canBeIncreasing(self, nums):\n count = 0\n for i in range(1, len(nums)):\n if nums[i] <= nums[i-1]:\n count += 1\n if i>1 and nums[i] <= nums[i-2]:\n nums[i] = nums[i-1]\n return count <= 1\n```
96,908
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
2,460
18
\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n stack = []\n for i in range(1, len(nums)): \n if nums[i-1] >= nums[i]: stack.append(i)\n \n if not stack: return True \n if len(stack) > 1: return False\n i = stack[0]\n return (i == 1 or nums[i-2] < nums[i]) or (i+1 == len(nums) or nums[i-1] < nums[i+1])\n```\n\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n prev, seen = -inf, False\n for i, x in enumerate(nums): \n if prev < x: prev = x\n else: \n if seen: return False \n seen = True \n if i == 1 or nums[i-2] < x: prev = x\n return True \n```
96,911
Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true. The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Array
Easy
For each index i in nums remove this index. If the array becomes sorted return true, otherwise revert to the original array and try different index.
1,271
11
```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n for i in range(len(nums)):\n temp = nums[:i] + nums[i+1:]\n if sorted(temp) == temp:\n if len(set(temp)) == len(temp):\n return True\n return False
96,921
Remove All Occurrences of a Substring
remove-all-occurrences-of-a-substring
Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string.
String
Medium
Note that a new occurrence of pattern can appear if you remove an old one, For example, s = "ababcc" and pattern = "abc". You can maintain a stack of characters and if the last character of the pattern size in the stack match the pattern remove them
999
5
# Intuition\nThe problem asks us to repeatedly remove all occurrences of a given substring, \'part\', from a given string, \'s\', until no more occurrences are left. To solve this problem, we can use a simple iterative approach. We keep searching for the leftmost occurrence of \'part\' in \'s\' and remove it until no more occurrences are found. Finally, we return the modified string \'s\' as the result.\n\n\n# Approach\nWe can use a while loop to repeatedly search for \'part\' in \'s\' and remove it until there are no more occurrences left. To do this, we initialize a boolean variable, \'test\', to True. This variable will help us keep track of whether any occurrence of \'part\' is found in \'s\' during each iteration of the while loop.\n\nInside the while loop, we use the find() function to find the index of the leftmost occurrence of \'part\' in \'s\'. If the index is not -1, which means \'part\' is found in \'s\', we remove \'part\' from \'s\' by slicing the string from the beginning up to the index, and then concatenating it with the substring starting from index+len(part) to the end. After removing \'part\' from \'s\', we set \'test\' to True to continue searching for more occurrences in the next iteration.\n\nIf the index is -1, which means \'part\' is not found in \'s\', we set \'test\' to False to exit the while loop, as there are no more occurrences left to remove.\n\nFinally, we return the modified string \'s\' as the output.\n# Complexity\n- Time complexity:\nThe time complexity of this approach depends on the number of occurrences of \'part\' in \'s\'. In the worst case, we may have to search for \'part\' and remove it for all its occurrences in \'s\'. Suppose \'s\' has length n and \'part\' has length m. The find() function has a time complexity of O(nm) in the worst case. Therefore, the overall time complexity of the removeOccurrences() function is O(nm) in the worst case.\n\n\n- Space complexity:\nThe space complexity of this approach is O(n), where n is the length of the input string \'s\'. This is because we are modifying the string \'s\' in place without using any additional data structures. Hence, the space complexity is linear with respect to the input size.\n\n\n\n\n\n# Code\n```\nclass Solution:\n def removeOccurrences(self, s: str, part: str) -> str:\n test=True\n while test:\n test=False\n i=s.find(part)\n if i!=-1:\n s=s[:i]+s[i+len(part):]\n test=True\n return s\n \n```
96,924
Remove All Occurrences of a Substring
remove-all-occurrences-of-a-substring
Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string.
String
Medium
Note that a new occurrence of pattern can appear if you remove an old one, For example, s = "ababcc" and pattern = "abc". You can maintain a stack of characters and if the last character of the pattern size in the stack match the pattern remove them
1,371
17
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n*The problem is asking us to remove all occurrences of a substring \'part\' from a string \'s\'. The approach to solve this problem is to repeatedly find the leftmost occurrence of the substring \'part\' in the string \'s\', and remove it. This process is repeated until no more occurrences of \'part\' can be found in the string \'s\'.*\n\n# Approach : ***Brute Force***\n<!-- Describe your approach to solving the problem. -->\nThe simplest approach is to iterate through the input string s and check if the substring part is present. If it is present, remove it from s and repeat the process until all occurrences of part are removed.\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n> This is because for each occurrence of the substring part, the erase() function has to shift all the characters in the string after the part to the left by part.length() positions, which takes O(n) time in the worst case. Since we may have to do this for all occurrences of part in s, the overall time complexity becomes O(n^2).\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n> Since we are modifying the input string s in place and not using any additional data structures.\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n string removeOccurrences(string s, string part) {\n int n = s.length();\n while(n!=0 && s.find(part)<n){\n s.erase(s.find(part),part.length());\n }\n return s;\n }\n};\n```\n```java []\nclass Solution {\n public String removeOccurrences(String s, String part) {\n int n = s.length();\n int index = s.indexOf(part);\n while(index != -1) {\n s = s.substring(0, index) + s.substring(index + part.length());\n n = s.length();\n index = s.indexOf(part);\n }\n return s;\n }\n}\n```\n```python []\nclass Solution(object):\n def removeOccurrences(self, s, part):\n while part in s:\n s = s.replace(part, \'\', 1)\n return s\n```\n```javascript []\nvar removeOccurrences = function(s, part) {\n let idx = s.indexOf(part);\n while (idx !== -1) {\n s = s.substring(0, idx) + s.substring(idx + part.length);\n idx = s.indexOf(part);\n }\n return s;\n};\n```\n\n\n---\n\n# Approach : ***Using Stack***\n<!-- Describe your approach to solving the problem. -->\nIn this approach, we maintain a stack and iterate over the string s. We push each character of s onto the stack. If the top of the stack matches the last character of the substring part, we check if the last len(part) characters on the stack match with the substring part. If they match, we pop them from the stack. We repeat this process until no more occurrences of the substring part are found. The time complexity of this approach is O(n*m), where n is the length of string s and m is the length of substring part.\n\n# Complexity\n- Time complexity: O(n*m)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n> Where n is the length of the string s and m is the length of the string part. \n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n> Since we are using a stack to store the characters of s.\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n string removeOccurrences(string s, string part) {\n stack<char> st;\n for(char c : s) {\n st.push(c);\n if(st.size() >= part.length() && st.top() == part.back()) {\n string temp = "";\n for(int i = 0; i < part.length(); i++) {\n temp += st.top();\n st.pop();\n }\n reverse(temp.begin(), temp.end());\n if(temp != part) {\n for(char c : temp) {\n st.push(c);\n }\n }\n }\n }\n string ans = "";\n while(!st.empty()) {\n ans += st.top();\n st.pop();\n }\n reverse(ans.begin(), ans.end());\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public String removeOccurrences(String s, String part) {\n Stack<Character> stack = new Stack<>();\n for(char c : s.toCharArray()) {\n stack.push(c);\n if(stack.size() >= part.length() && stack.peek() == part.charAt(part.length()-1)) {\n StringBuilder temp = new StringBuilder();\n for(int i = 0; i < part.length(); i++) {\n temp.append(stack.pop());\n }\n temp.reverse();\n if(!temp.toString().equals(part)) {\n for(char c : temp.toString().toCharArray()) {\n stack.push(c);\n }\n }\n }\n }\n StringBuilder ans = new StringBuilder();\n while(!stack.isEmpty()) {\n ans.append(stack.pop());\n }\n return ans.reverse().toString();\n }\n}\n\n```\n```python []\nclass Solution:\n def removeOccurrences(self, s: str, part: str) -> str:\n stack = []\n for c in s:\n stack.append(c)\n if len(stack) >= len(part) and stack[-1] == part[-1]:\n temp = []\n for i in range(len(part)):\n temp.append(stack.pop())\n temp.reverse()\n if \'\'.join(temp) != part:\n for c in temp:\n stack.append(c)\n ans = []\n while stack:\n ans.append(stack.pop())\n return \'\'.join(ans[::-1])\n\n```\n```javascript []\nvar removeOccurrences = function(s, part) {\n let stack = [];\n for(let c of s) {\n stack.push(c);\n if(stack.length >= part.length && stack[stack.length-1] == part[part.length-1]) {\n let temp = [];\n for(let i = 0; i < part.length; i++) {\n temp.push(stack.pop());\n }\n temp.reverse();\n if(temp.join(\'\') != part) {\n for(let c of temp) {\n stack.push(c);\n }\n }\n }\n }\n let ans = [];\n while(stack.length > 0) {\n ans.push(stack.pop());\n }\n ans.reverse();\n return ans.join(\'\');\n};\n```\n\n---\n\n![upvote.jpeg]()\n\n
96,940
Remove All Occurrences of a Substring
remove-all-occurrences-of-a-substring
Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string.
String
Medium
Note that a new occurrence of pattern can appear if you remove an old one, For example, s = "ababcc" and pattern = "abc". You can maintain a stack of characters and if the last character of the pattern size in the stack match the pattern remove them
1,421
5
Solution 1:\n```\ndef removeOccurrences(self, s: str, part: str) -> str:\n while part in s:\n s= s.replace(part,"",1)\n return s\n```\nSolution 2:\n```\ndef removeOccurrences(self, s: str, part: str) -> str:\n while part in s:\n index = s.index(part)\n s = s[:index] + s[index+len(part):]\n return s\n```
96,946
Remove All Occurrences of a Substring
remove-all-occurrences-of-a-substring
Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string.
String
Medium
Note that a new occurrence of pattern can appear if you remove an old one, For example, s = "ababcc" and pattern = "abc". You can maintain a stack of characters and if the last character of the pattern size in the stack match the pattern remove them
1,608
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeOccurrences(self, s: str, part: str) -> str:\n while(part in s):\n s=s.replace(part,"",1)\n return s\n\n\n\n\n```
96,967
Maximum Alternating Subsequence Sum
maximum-alternating-subsequence-sum
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Array,Dynamic Programming
Medium
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
1,528
32
![image]()\n\n```\nclass Solution:\n def maxAlternatingSum(self, nums: List[int]) -> int:\n ans = 0\n direction = \'down\'\n n = len(nums)\n for i in range(n-1):\n if direction == \'down\' and nums[i] >= nums[i+1]:\n ans += nums[i]\n direction = \'up\'\n elif direction == \'up\' and nums[i] <= nums[i+1]:\n ans -= nums[i]\n direction = \'down\'\n if direction == \'up\':\n return ans\n return ans + nums[-1]\n```\n
96,985
Maximum Alternating Subsequence Sum
maximum-alternating-subsequence-sum
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Array,Dynamic Programming
Medium
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
853
9
***Solution 1: Dynamic Programming***\n\n**Intuition**\nWe can use DP (dynamic programming) to loop through nums and find the biggest alternating subsequence num.\n\n**Algorithm**\nWe first initialize a `n` by `2` matrix where `n = len(nums)`. In a supposed index of `dp[i][j]`, `i` stands for the index of `dp` based on the such index of `nums` given from the input, while `j` stands for whether we add or subtract a number for the last value. If `j == 0`, then we add, if `j==1`, then we subtract. This means `dp[i][0]` means that we have a plus for the last value, while `dp[i][1]` means we have a minus for the last value. Before we start the iteration, we need to pre-define `dp[0][0]` as `nums[0]` as the index is both `0`. We also need to pre-define `dp[0][1]` as `0` since we have to start by adding given the question, thus we put 0.\n\nNext, we iterate through `nums` in a range for loop from index `1` to `n`, we start on index `1` instead of `0` because index `0` is already pre-defined. Each iteration, we try either to choose (meaning we choose to go or continue to add/subtract) or not choose (meaning we continue iterating through the array without making an alternating subsequence) for when the last value is plus (`dp[i][0]`) and when the last value is minus. (`dp[i][1]`) We take the max of whether to choose or not choose for both when the last value is plus and when the last value is minus.\n\nAfter we finish iterating, max of `dp[-1]` is the result, meaning we find the maximum number between when the last value is plus and when the last value is minus.\n\n```\nclass Solution:\n def maxAlternatingSum(self, nums: List[int]) -> int:\n n = len(nums) \n dp = [[0,0] for _ in range(n)] # initialize dp\n dp[0][0] = nums[0] # pre-define\n dp[0][1] = 0 # pre-define\n\n for i in range(1, n): # iterate through nums starting from index 1\n dp[i][0] = max(nums[i] + dp[i-1][1], dp[i-1][0]) # find which value is higher between choosing or not choosing when the last value is plus.\n dp[i][1] = max(-nums[i] + dp[i-1][0], dp[i-1][1]) # find which value is higher between choosing or not choosing when the last value is minus.\n \n return max(dp[-1]) # find the maximum of the last array of dp of whether the last value is plus or minus, this will be our answer.\n```\n\n***Solution 2: DFS with Memoization***\n\n**Intuition**\nWe can combine DFS with memoization to find all the paths and narrow it down as we go.\n\n**Algorithm**\nStart a dfs function, it terminates when `i`, the index, reaches the length of nums, or `n` in this case. We also keep track of another variable `p`, which determines whether we add or subtract. Next, similar to solution 1, we either choose (to start or continue the existing alternating subsequence) or not choose (move on to the next element of nums without doing anything). This will give us the answer.\n```\nclass Solution:\n def maxAlternatingSum(self, nums: List[int]) -> int:\n\t\tn = len(nums) \n @cache\n def dfs(i: int, p: bool) -> int:\n if i>=n:\n return 0 \n\t\t\t\n\t\t\t# if choose\n num = nums[i] if p else -nums[i]\n choose = num + dfs(i+1, not p)\n\n # if not choose\n not_choose = dfs(i+1, p)\n return max(choose, not_choose)\n\n return dfs(0, True)\n```\n\n**Please consider upvoting if these solutions helped you. Good luck!**\n
96,991
Maximum Alternating Subsequence Sum
maximum-alternating-subsequence-sum
The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices. Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence). A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.
Array,Dynamic Programming
Medium
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
747
9
## IDEA:\n\uD83D\uDC49 Maximize the max_diff.\n\uD83D\uDC49 Minimize the min_diff.\nGiven an alternating sequence (a0, a1... ak), the change in value after appending an element x depends only on whether we have an even or odd number of elements so far:\n\nIf we have even # of elements, we add x; otherwise, we subtract x. So, tracking the best subsequences of odd and even sizes gives an extremely simple update formula.\n\n\'\'\'\n\n\tclass Solution:\n def maxAlternatingSum(self, nums: List[int]) -> int:\n \n ma=0\n mi=0\n for num in nums:\n ma=max(ma,num-mi)\n mi=min(mi,num-ma)\n \n return ma
97,011
Design Movie Rental System
design-movie-rental-system
You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies. Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei. The system should support the following functions: Implement the MovieRentingSystem class: Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.
Array,Hash Table,Design,Heap (Priority Queue),Ordered Set
Hard
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
944
9
\n```\nclass MovieRentingSystem:\n\n def __init__(self, n: int, entries: List[List[int]]):\n self.avail = {}\n self.price = {}\n self.movies = defaultdict(list)\n for s, m, p in entries: \n heappush(self.movies[m], (p, s))\n self.avail[s, m] = True # unrented \n self.price[s, m] = p\n self.rented = []\n \n\n def search(self, movie: int) -> List[int]:\n if movie not in self.movies: return []\n ans, temp = [], []\n while len(ans) < 5 and self.movies[movie]: \n p, s = heappop(self.movies[movie])\n temp.append((p, s))\n if self.avail[s, movie]: ans.append((p, s))\n for p, s in temp: heappush(self.movies[movie], (p, s))\n return [x for _, x in ans]\n \n\n def rent(self, shop: int, movie: int) -> None:\n self.avail[shop, movie] = False\n p = self.price[shop, movie]\n heappush(self.rented, (p, shop, movie))\n \n\n def drop(self, shop: int, movie: int) -> None:\n self.avail[shop, movie] = True \n \n\n def report(self) -> List[List[int]]:\n ans = []\n while len(ans) < 5 and self.rented: \n p, s, m = heappop(self.rented)\n if not self.avail[s, m] and (not ans or ans[-1] != (p, s, m)): \n ans.append((p, s, m))\n for p, s, m in ans: heappush(self.rented, (p, s, m))\n return [[s, m] for _, s, m in ans]\n\n\n# Your MovieRentingSystem object will be instantiated and called as such:\n# obj = MovieRentingSystem(n, entries)\n# param_1 = obj.search(movie)\n# obj.rent(shop,movie)\n# obj.drop(shop,movie)\n# param_4 = obj.report()\n```\n\nAdding `SortedList` implementation \n```\nfrom sortedcontainers import SortedList \n\nclass MovieRentingSystem:\n\n def __init__(self, n: int, entries: List[List[int]]):\n self.avail = {}\n self.price = {}\n for shop, movie, price in entries: \n self.price[shop, movie] = price \n self.avail.setdefault(movie, SortedList()).add((price, shop))\n self.rented = SortedList()\n\n \n def search(self, movie: int) -> List[int]:\n return [x for _, x in self.avail.get(movie, [])[:5]]\n \n\n def rent(self, shop: int, movie: int) -> None:\n price = self.price[shop, movie]\n self.avail[movie].remove((price, shop))\n self.rented.add((price, shop, movie))\n\n def drop(self, shop: int, movie: int) -> None:\n price = self.price[shop, movie]\n self.avail[movie].add((price, shop))\n self.rented.remove((price, shop, movie))\n\n def report(self) -> List[List[int]]:\n return [[x, y] for _, x, y in self.rented[:5]]\n```
97,031
Calculate Special Bonus
calculate-special-bonus
Table: Employees Write an SQL query to calculate the bonus of each employee. The bonus of an employee is 100% of their salary if the ID of the employee is an odd number and the employee name does not start with the character 'M'. The bonus of an employee is 0 otherwise. Return the result table ordered by employee_id. The query result format is in the following example.
Database
Easy
null
1,488
19
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef calculate_special_bonus(employees: pd.DataFrame) -> pd.DataFrame:\n return employees.assign(\n bonus=employees.apply(lambda x: x[\'salary\'] if int(x[\'employee_id\']) % 2 != 0 and not x[\'name\'].startswith(\'M\') else 0, axis=1)\n )[[\'employee_id\', \'bonus\']].sort_values(\n by=\'employee_id\',\n )\n```\n```SQL []\nSELECT employee_id,\n IF (employee_id % 2 != 0 AND name NOT LIKE \'M%\', salary, 0) AS bonus\n FROM Employees\n ORDER BY employee_id;\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
97,095
Calculate Special Bonus
calculate-special-bonus
Table: Employees Write an SQL query to calculate the bonus of each employee. The bonus of an employee is 100% of their salary if the ID of the employee is an odd number and the employee name does not start with the character 'M'. The bonus of an employee is 0 otherwise. Return the result table ordered by employee_id. The query result format is in the following example.
Database
Easy
null
155
6
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nimport pandas as pd\n\ndef calculate_special_bonus(employees: pd.DataFrame) -> pd.DataFrame:\n \n employees[\'bonus\'] = employees[(employees[\'employee_id\'] % 2 == 1) & (~employees[\'name\'].str.startswith(\'M\'))][\'salary\']\n \n employees[\'bonus\'] = employees[\'bonus\'].fillna(0)\n \n return employees[[\'employee_id\', \'bonus\']].sort_values(by=\'employee_id\')\n```\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.**
97,108