title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python easy solution with extend
partition-array-according-to-given-pivot
0
1
# Code\n```\nclass Solution:\n def pivotArray(self, nums: List[int], pivot: int) -> List[int]:\n res = [n for n in nums if n < pivot]\n res.extend([pivot] * nums.count(pivot))\n res.extend([n for n in nums if n > pivot])\n return res\n```
0
You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same...
How would you solve the problem for offline queries (all queries given at once)? Think about which data structure can help insert and delete the most optimal way.
Easy to understand Python3 solution
partition-array-according-to-given-pivot
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same...
How would you solve the problem for offline queries (all queries given at once)? Think about which data structure can help insert and delete the most optimal way.
4 pointers
partition-array-according-to-given-pivot
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
4
You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same...
How would you solve the problem for offline queries (all queries given at once)? Think about which data structure can help insert and delete the most optimal way.
In place re-arrange numbers - T:O(N) , S: O(1)- 42/44 passed test cases
partition-array-according-to-given-pivot
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach \nIn Place rearranging numbers \n<!-- Describe your approach to solving the problem. -->\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 yo...
1
You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same...
How would you solve the problem for offline queries (all queries given at once)? Think about which data structure can help insert and delete the most optimal way.
Python 3 || 8 lines || T/M: 97% / 81%
minimum-cost-to-set-cooking-time
0
1
```\nclass Solution:\n def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:\n\n def cost(m: int,s: int)-> int:\n\n if not(0 <= m <= 99 and 0 <= s <= 99): return inf\n\n display = str(startAt)+str(100*m+s)\n\n moves = sum(display[i]!...
3
A generic microwave supports cooking times for: * at least `1` second. * at most `99` minutes and `99` seconds. To set the cooking time, you push **at most four digits**. The microwave normalizes what you push as four digits by **prepending zeroes**. It interprets the **first** two digits as the minutes and the *...
The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For ...
[Python3, Java, C++] Combinations of Minutes and Seconds O(1)
minimum-cost-to-set-cooking-time
1
1
**Explanation**: \n* The maximum possible minutes are: `targetSeconds` / 60\n* Check for all possible minutes from 0 to `maxmins` and the corresponding seconds\n* `cost` function returns the cost for given minutes and seconds\n* `moveCost` is added to current cost if the finger position is not at the correct number\n* ...
108
A generic microwave supports cooking times for: * at least `1` second. * at most `99` minutes and `99` seconds. To set the cooking time, you push **at most four digits**. The microwave normalizes what you push as four digits by **prepending zeroes**. It interprets the **first** two digits as the minutes and the *...
The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For ...
Simple Python Solution
minimum-cost-to-set-cooking-time
0
1
```\nclass Solution:\n def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:\n def count_cost(minutes, seconds): # Calculates cost for certain configuration of minutes and seconds\n time = f\'{minutes // 10}{minutes % 10}{seconds // 10}{seconds % 10}\' # m...
10
A generic microwave supports cooking times for: * at least `1` second. * at most `99` minutes and `99` seconds. To set the cooking time, you push **at most four digits**. The microwave normalizes what you push as four digits by **prepending zeroes**. It interprets the **first** two digits as the minutes and the *...
The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For ...
Python3 | Beats 100% time
minimum-cost-to-set-cooking-time
0
1
```\nclass Solution:\n def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:\n poss = [(targetSeconds // 60, targetSeconds % 60)] # store possibilities as (minutes, seconds)\n \n if poss[0][0] > 99: # for when targetSeconds >= 6000\n poss =...
2
A generic microwave supports cooking times for: * at least `1` second. * at most `99` minutes and `99` seconds. To set the cooking time, you push **at most four digits**. The microwave normalizes what you push as four digits by **prepending zeroes**. It interprets the **first** two digits as the minutes and the *...
The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For ...
Constant time and space (atmost 100 iterations)
minimum-cost-to-set-cooking-time
0
1
\n# Code\n```\nclass Solution:\n def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:\n min_cost = float(\'inf\')\n \n def calculateCost(time_str, startAt, moveCost, pushCost):\n cost = 0\n for digit in time_str:\n ...
0
A generic microwave supports cooking times for: * at least `1` second. * at most `99` minutes and `99` seconds. To set the cooking time, you push **at most four digits**. The microwave normalizes what you push as four digits by **prepending zeroes**. It interprets the **first** two digits as the minutes and the *...
The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For ...
Python (Simple Maths)
minimum-cost-to-set-cooking-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
A generic microwave supports cooking times for: * at least `1` second. * at most `99` minutes and `99` seconds. To set the cooking time, you push **at most four digits**. The microwave normalizes what you push as four digits by **prepending zeroes**. It interprets the **first** two digits as the minutes and the *...
The target sum for the two partitions is sum(nums) / 2. Could you reduce the time complexity if you arbitrarily divide nums into two halves (two arrays)? Meet-in-the-Middle? For both halves, pre-calculate a 2D array where the kth index will store all possible sum values if only k elements from this half are added. For ...
Python solution | O(nlogn) | explained with diagram | heap and dp solution
minimum-difference-in-sums-after-removal-of-elements
0
1
This solution is a combination of dp and heaps.\nTime: `O(nlogn)`\n\n# Explanation:\n\nWe can select in first part:\n* first `n` elements or\n* min `n` elements from first `n+1` elements\n* min `n` elements from first `n-2` elements\n* ...\n* min `n` elements from first `2n` elements\n\n\nIn other words,\nwe need to fi...
2
You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements. You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** parts: * The first `n` elements belonging to the first part and their su...
Try 'mapping' the strings to check if they are unique or not.
Python: Heap + DP -- code is easy to read with comments
minimum-difference-in-sums-after-removal-of-elements
0
1
# Approach\nSimilar to many other answers. I\'m sharing my solution because I think my code is a bit clearer than other solutions I was seeing. I hope it\'s helpful!\n\nBy default we remove the middle n elements. The difference is `sum(nums[:n]) - sum([nums[2*n:]])`. However, we could choose to move one of the removes ...
0
You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements. You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** parts: * The first `n` elements belonging to the first part and their su...
Try 'mapping' the strings to check if they are unique or not.
[Python3|C++] Priority Queue
minimum-difference-in-sums-after-removal-of-elements
0
1
# Intuition\n`min(min_left[i] - max_right[i] | i = n, n+1, ... 2*n - 1, 2*n)`\n\n# Approach\nPlease refer to [this great post](https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/solutions/1747003/python-o-nlogn-priority-queue-with-detailed-explanation/)\n\n# Complexity\n- Time complexity...
0
You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements. You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** parts: * The first `n` elements belonging to the first part and their su...
Try 'mapping' the strings to check if they are unique or not.
Two-direction scan with heap in Python, faster than 95%
minimum-difference-in-sums-after-removal-of-elements
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is to find a pivot in between `n` and `2n` (inclusive) so that the sum of the mininum `n` elements in `nums[0:pivot]` - the sum of the maximum `n` elements in `nums[pivot:3n]` is minimized. \n\n# Approach\n<!-- Describe your...
0
You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements. You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** parts: * The first `n` elements belonging to the first part and their su...
Try 'mapping' the strings to check if they are unique or not.
Python (Simple Heap)
minimum-difference-in-sums-after-removal-of-elements
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements. You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** parts: * The first `n` elements belonging to the first part and their su...
Try 'mapping' the strings to check if they are unique or not.
[Python] O(n log n) Easy to Understand Explanation with pictures
minimum-difference-in-sums-after-removal-of-elements
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe first thing we should always do when solving a problem is to carefully read the given examples. In this case, it is important to note that the goal is to find the minimum difference, not the minimum absolute difference. Once this de...
0
You are given a **0-indexed** integer array `nums` consisting of `3 * n` elements. You are allowed to remove any **subsequence** of elements of size **exactly** `n` from `nums`. The remaining `2 * n` elements will be divided into two **equal** parts: * The first `n` elements belonging to the first part and their su...
Try 'mapping' the strings to check if they are unique or not.
Reconstruction
sort-even-and-odd-indices-independently
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given a **0-indexed** integer array `nums`. Rearrange the values of `nums` according to the following rules: 1. Sort the values at **odd indices** of `nums` in **non-increasing** order. * For example, if `nums = [4,**1**,2,**3**]` before this step, it becomes `[4,**3**,2,**1**]` after. The values at odd...
How can sorting the events on the basis of their start times help? How about end times? How can we quickly get the maximum score of an interval not intersecting with the interval we chose?
You can specify steps when slicing a list :)
sort-even-and-odd-indices-independently
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given a **0-indexed** integer array `nums`. Rearrange the values of `nums` according to the following rules: 1. Sort the values at **odd indices** of `nums` in **non-increasing** order. * For example, if `nums = [4,**1**,2,**3**]` before this step, it becomes `[4,**3**,2,**1**]` after. The values at odd...
How can sorting the events on the basis of their start times help? How about end times? How can we quickly get the maximum score of an interval not intersecting with the interval we chose?
Best Easy Solution
sort-even-and-odd-indices-independently
0
1
# Intuition\nIteration\n\n# Approach\nBruteforce\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def sortEvenOdd(self, nums: List[int]) -> List[int]:\n lst=[]\n dst=[]\n bst=[]\n mst=[]\n cst=[0]*len(nums)\n for i in r...
1
You are given a **0-indexed** integer array `nums`. Rearrange the values of `nums` according to the following rules: 1. Sort the values at **odd indices** of `nums` in **non-increasing** order. * For example, if `nums = [4,**1**,2,**3**]` before this step, it becomes `[4,**3**,2,**1**]` after. The values at odd...
How can sorting the events on the basis of their start times help? How about end times? How can we quickly get the maximum score of an interval not intersecting with the interval we chose?
PYTHON BEATS 100% OF RUNTIME✅
smallest-value-of-the-rearranged-number
0
1
# Approach\n1- Check if num is **negative** or not\n\n2- **Store** all **digits** in num in an array **except** the **zeros**\n\n3- If num is **negative** -> you need to order the array in **descending** order and add all **zeros** to the **left**\nif num is **positive** -> you need to order the array in **ascending** ...
1
You are given an integer `num.` **Rearrange** the digits of `num` such that its value is **minimized** and it does not contain **any** leading zeros. Return _the rearranged number with minimal value_. Note that the sign of the number does not change after rearranging the digits. **Example 1:** **Input:** num = 310 ...
Can you find the indices of the most left and right candles for a given substring, perhaps by using binary search (or better) over an array of indices of all the bars? Once the indices of the most left and right bars are determined, how can you efficiently count the number of plates within the range? Prefix sums?
Intuitive Python solution, not using str
smallest-value-of-the-rearranged-number
0
1
# Intuition\nThis problem is similar to sorting an array but in here you need to sort digits in ascending order if the number is positive and descending order if negative. (Technically, it\'s non descending for positive and non acending for negative since we can have duplicate digit)\n\nWe would like to operate as numb...
0
You are given an integer `num.` **Rearrange** the digits of `num` such that its value is **minimized** and it does not contain **any** leading zeros. Return _the rearranged number with minimal value_. Note that the sign of the number does not change after rearranging the digits. **Example 1:** **Input:** num = 310 ...
Can you find the indices of the most left and right candles for a given substring, perhaps by using binary search (or better) over an array of indices of all the bars? Once the indices of the most left and right bars are determined, how can you efficiently count the number of plates within the range? Prefix sums?
Python solution || Easy to understand || string || bitset
design-bitset
0
1
```\nclass Bitset:\n\n def __init__(self, size: int):\n\t\t# stores original bits True -> 1, False -> 0\n self.bit = [False for i in range(size)]\n\t\t# inverse list of self.bit\n self.bitinv = [True for i in range(size)]\n\t\t# counter of True\n self.ones = 0\n\t\t# counter of False (both are f...
1
A **Bitset** is a data structure that compactly stores bits. Implement the `Bitset` class: * `Bitset(int size)` Initializes the Bitset with `size` bits, all of which are `0`. * `void fix(int idx)` Updates the value of the bit at the index `idx` to `1`. If the value was already `1`, no change occurs. * `void unf...
N is small, we can generate all possible move combinations. For each possible move combination, determine which ones are valid.
[Python3, Java, C++] All Operations O(1) | Flipped String/Flip Flag
design-bitset
1
1
\n* Flipping can be done using a flipped string that contains the flipped version of the current bitset. C++ and Java solutions have been done using this method. All operations are O(1) in C++ at the cost of an extra string of length `size`\n* Python solution has been done using a flip flag. Flip flag stores whether th...
92
A **Bitset** is a data structure that compactly stores bits. Implement the `Bitset` class: * `Bitset(int size)` Initializes the Bitset with `size` bits, all of which are `0`. * `void fix(int idx)` Updates the value of the bit at the index `idx` to `1`. If the value was already `1`, no change occurs. * `void unf...
N is small, we can generate all possible move combinations. For each possible move combination, determine which ones are valid.
[Java/Python 3] Boolean array, time O(1) except init() and toString()
design-bitset
1
1
Use 2 boolean arrays to record current state and the corresponding flipped one.\n\n```java\n private boolean[] bits;\n private boolean[] flipped;\n private int sz, cnt;\n \n public BooleanArray2(int size) {\n sz = size;\n bits = new boolean[size];\n flipped = new boolean[size];\n ...
15
A **Bitset** is a data structure that compactly stores bits. Implement the `Bitset` class: * `Bitset(int size)` Initializes the Bitset with `size` bits, all of which are `0`. * `void fix(int idx)` Updates the value of the bit at the index `idx` to `1`. If the value was already `1`, no change occurs. * `void unf...
N is small, we can generate all possible move combinations. For each possible move combination, determine which ones are valid.
✔️ PYTHON || EXPLAINED || ;]
design-bitset
0
1
**UPVOTE IF HELPFuuL**\n\n* Make an array for storing bits. *Initializing all the values to 0*\n* Keep a variable ```on``` to keep the count of number of ones.\n* Create another ```bool``` variable ```flipped = False``` to store condition of array. **[ If array is fliiped, variable is changed to ```True```, if flipped ...
9
A **Bitset** is a data structure that compactly stores bits. Implement the `Bitset` class: * `Bitset(int size)` Initializes the Bitset with `size` bits, all of which are `0`. * `void fix(int idx)` Updates the value of the bit at the index `idx` to `1`. If the value was already `1`, no change occurs. * `void unf...
N is small, we can generate all possible move combinations. For each possible move combination, determine which ones are valid.
Python | O(1) operations using one list only| 97.43% faster
design-bitset
0
1
```python\nclass Bitset:\n def __init__(self, size: int):\n self.bitset = [0] * size\n self.size = size\n self.ones = 0\n self.flipped = False\n \n\t\t\n def fix(self, idx: int) -> None:\n if self.flipped and self.bitset[idx]:\n self.bitset[idx] = 0\n ...
1
A **Bitset** is a data structure that compactly stores bits. Implement the `Bitset` class: * `Bitset(int size)` Initializes the Bitset with `size` bits, all of which are `0`. * `void fix(int idx)` Updates the value of the bit at the index `idx` to `1`. If the value was already `1`, no change occurs. * `void unf...
N is small, we can generate all possible move combinations. For each possible move combination, determine which ones are valid.
[Python 3] Two Lists, Keep track of ones and zeroes
design-bitset
0
1
**Approach:** Keep two lists, one with the regular bits and other with flipped.\n\nAlso, keep track of the number of ones and zeroes in the regular.\nThen it is straightforward solution.\nWhen using flip, interchange the two lists and the number of ones and zeroes.\n\n**DO UPVOTE IF YOU FOUND IT HELPFUL.**\n\n```\nclas...
2
A **Bitset** is a data structure that compactly stores bits. Implement the `Bitset` class: * `Bitset(int size)` Initializes the Bitset with `size` bits, all of which are `0`. * `void fix(int idx)` Updates the value of the bit at the index `idx` to `1`. If the value was already `1`, no change occurs. * `void unf...
N is small, we can generate all possible move combinations. For each possible move combination, determine which ones are valid.
Two passes, min of removing everything in left plus removing all to the right
minimum-time-to-remove-all-cars-containing-illegal-goods
0
1
# Code\n```\nclass Solution:\n def minimumTime(self, s):\n left, res, n = 0, len(s), len(s)\n lefts = []\n for i,c in enumerate(s):\n left = min(left + (c == \'1\') * 2, i + 1)\n lefts.append(left)\n right = 0\n rights = []\n for i,c in enumerate(s[::-1...
0
You are given a **0-indexed** binary string `s` which represents a sequence of train cars. `s[i] = '0'` denotes that the `ith` car does **not** contain illegal goods and `s[i] = '1'` denotes that the `ith` car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing ille...
null
O(N) T and O(1) S | Commented and Explained
minimum-time-to-remove-all-cars-containing-illegal-goods
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe number of prefix to remove and number of suffix to remove suffice for this problem as we are only asked to minimize time. I had started out incorrectly trying to minimize time and maximize overall length delivered, realizing that that...
0
You are given a **0-indexed** binary string `s` which represents a sequence of train cars. `s[i] = '0'` denotes that the `ith` car does **not** contain illegal goods and `s[i] = '1'` denotes that the `ith` car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing ille...
null
Python Solution Using Kadane's algorithm O(N) and O(1)
minimum-time-to-remove-all-cars-containing-illegal-goods
0
1
\n# Code\n```\nclass Solution:\n def minimumTime(self, s: str) -> int:\n \'\'\'\n the technique that we use is find middle string which contain 0 and 1 which done by cost 2 so we have to minimize that so we find maximum sum so minimum number of ones that done by cost 2 and overall cost is minimized\n ...
0
You are given a **0-indexed** binary string `s` which represents a sequence of train cars. `s[i] = '0'` denotes that the `ith` car does **not** contain illegal goods and `s[i] = '1'` denotes that the `ith` car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing ille...
null
100% memory and 60% in speed
minimum-time-to-remove-all-cars-containing-illegal-goods
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a **0-indexed** binary string `s` which represents a sequence of train cars. `s[i] = '0'` denotes that the `ith` car does **not** contain illegal goods and `s[i] = '1'` denotes that the `ith` car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing ille...
null
Python (Simple Maths)
minimum-time-to-remove-all-cars-containing-illegal-goods
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a **0-indexed** binary string `s` which represents a sequence of train cars. `s[i] = '0'` denotes that the `ith` car does **not** contain illegal goods and `s[i] = '1'` denotes that the `ith` car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing ille...
null
DP ez
minimum-time-to-remove-all-cars-containing-illegal-goods
0
1
\n# Approach\nsimple dp states\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumTime(self, s: str) -> int:...
0
You are given a **0-indexed** binary string `s` which represents a sequence of train cars. `s[i] = '0'` denotes that the `ith` car does **not** contain illegal goods and `s[i] = '1'` denotes that the `ith` car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing ille...
null
Python | Min sum of contiguous subsequence
minimum-time-to-remove-all-cars-containing-illegal-goods
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe trick is to convert this problem to:\n Remove the minimum sum of contiguous subsequence.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, ...
0
You are given a **0-indexed** binary string `s` which represents a sequence of train cars. `s[i] = '0'` denotes that the `ith` car does **not** contain illegal goods and `s[i] = '1'` denotes that the `ith` car does contain illegal goods. As the train conductor, you would like to get rid of all the cars containing ille...
null
Simple solution in Python3
count-operations-to-obtain-zero
0
1
# Intuition\nHere we have:\n- two integers `num1` and `num2` respectively\n- our goal is to find how many **decrementations** we should apply to make either `num1` or `num2` equal to `0`\n\nFollowing to the description we need to subtract `num1` from `num2`, if `num1 >= num2` and vice-versa.\nLet\'s simulate a process....
1
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Simple While Loop Solution || Python
count-operations-to-obtain-zero
0
1
# Code\n```\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n cnt=0\n while(num1>0 and num2>0):\n if num1>=num2:\n num1-=num2\n else:\n num2-=num1\n cnt+=1\n return cnt\n```\n\n***Please Upvote***
1
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Beats 57.77% || Count operations to obtain zero
count-operations-to-obtain-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Python Eazy to understand beat 94% and simple🚀
count-operations-to-obtain-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Python Easy Solution
count-operations-to-obtain-zero
0
1
\n\n# Code\n```\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n ans = 0\n\n while num1 > 0 and num2 > 0:\n if num1>=num2:\n num1 -= num2\n else:\n num2 -= num1\n\n ans += 1\n\n return ans\n```
1
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Python | Easy Solution✅
count-operations-to-obtain-zero
0
1
# Code\u2705\n```\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n count = 0\n while num1 != 0 and num2 != 0:\n if num1 >= num2:\n num1 -= num2\n else:\n num2 -= num1\n count +=1\n return count\n```
7
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Easy Python solution
count-operations-to-obtain-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Python intuitive simple solution
count-operations-to-obtain-zero
0
1
**Python :**\n\n```\ndef countOperations(self, num1: int, num2: int) -> int:\n\toperations = 0\n\n\twhile num1 and num2:\n\t\tif num2 > num1:\n\t\t\tnum2 -= num1\n\t\t\toperations += 1\n\n\t\tif num1 > num2:\n\t\t\tnum1 -= num2\n\t\t\toperations += 1\n\n\t\tif num1 == num2:\n\t\t\treturn operations + 1\n\n\treturn oper...
6
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
[Python3] simulation
count-operations-to-obtain-zero
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/2506277d2af78559a0e58d2130fdbe87beab42b5) for solutions of weekly 280. \n\n```\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n ans = 0 \n while num1 and num2: \n ans += num1//num2\n ...
6
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Count GCD steps (w/o recursion and if-else)
count-operations-to-obtain-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCount GCD steps.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIf there\'s `num1 < num2` here, no steps are added and `nums` are swapped.\n# Complexity\n- Time complexity: $$O(GCD)$$\n<!-- Add your time complexity ...
1
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Python3 | 2 approaches Normal and Optimized in time
count-operations-to-obtain-zero
0
1
**Normal Solution**\n```\nclass Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n ct=0\n while num2 and num1:\n if num1>=num2:\n num1=num1-num2\n else:\n num2=num2-num1\n ct+=1\n return ct\n```\n\n**More Optimized...
4
You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initia...
How do you determine if a transaction will fail? Simply apply the operations if the transaction is valid.
Python 3 hashmap solution O(N), no sort needed
minimum-operations-to-make-the-array-alternating
0
1
Key implementation step:\n* Create two hashmaps to count the frequencies of num with odd and even indices, respectively;\n* Search for the `num` in each hashmap with the maximum and second maximum frequencies:\n\t* If the two `num`\'s with the maximum frequencies are not equal, then return `len(nums) - (maxFreqOdd + ma...
12
You are given a **0-indexed** array `nums` consisting of `n` positive integers. The array `nums` is called **alternating** if: * `nums[i - 2] == nums[i]`, where `2 <= i <= n - 1`. * `nums[i - 1] != nums[i]`, where `1 <= i <= n - 1`. In one **operation**, you can choose an index `i` and **change** `nums[i]` into ...
Can we enumerate all possible subsets? The maximum bitwise-OR is the bitwise-OR of the whole array.
[Python3] 4-line
minimum-operations-to-make-the-array-alternating
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/2506277d2af78559a0e58d2130fdbe87beab42b5) for solutions of weekly 280. \n\nUpdated implementation using `most_common()`\n```\nclass Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n pad = lambda x: x + [(None, 0)]*(2-len(...
22
You are given a **0-indexed** array `nums` consisting of `n` positive integers. The array `nums` is called **alternating** if: * `nums[i - 2] == nums[i]`, where `2 <= i <= n - 1`. * `nums[i - 1] != nums[i]`, where `1 <= i <= n - 1`. In one **operation**, you can choose an index `i` and **change** `nums[i]` into ...
Can we enumerate all possible subsets? The maximum bitwise-OR is the bitwise-OR of the whole array.
[Python3] Counter
minimum-operations-to-make-the-array-alternating
0
1
# Approach\nUse Python\'s `Counter` to get the most frequent elements in the even- and odd-indexed elements of `nums`. If the most frequent elements are different, we can just return the number of elements in `nums` that are _not_ their corresponding most frequent element.\n\nIf the most frequent elements _are_ the sam...
0
You are given a **0-indexed** array `nums` consisting of `n` positive integers. The array `nums` is called **alternating** if: * `nums[i - 2] == nums[i]`, where `2 <= i <= n - 1`. * `nums[i - 1] != nums[i]`, where `1 <= i <= n - 1`. In one **operation**, you can choose an index `i` and **change** `nums[i]` into ...
Can we enumerate all possible subsets? The maximum bitwise-OR is the bitwise-OR of the whole array.
Easy 3 line python
minimum-operations-to-make-the-array-alternating
0
1
# Intuition\nWe find 2 most common values in the odd and even lists. We append a dummy (0,0) to each in case those lists contain 1 unique number. We then find the maximum number of characters we can leave repeating and subtract it from len of nums to return all other characters which will need to be swapped. \n\n# Appr...
0
You are given a **0-indexed** array `nums` consisting of `n` positive integers. The array `nums` is called **alternating** if: * `nums[i - 2] == nums[i]`, where `2 <= i <= n - 1`. * `nums[i - 1] != nums[i]`, where `1 <= i <= n - 1`. In one **operation**, you can choose an index `i` and **change** `nums[i]` into ...
Can we enumerate all possible subsets? The maximum bitwise-OR is the bitwise-OR of the whole array.
[Java/Python 3] Sort, then 1 pass find max rectangle, w/ graph explanation and analysis.
removing-minimum-number-of-magic-beans
1
1
**Intuition**\nThe problem asks us to get the minimum beans by removing part or all from any individual bean bag(s), in order to make remaining bean bags homogeneous in terms of the number of beans. \n\nTherefore, we can sort input first, then remove smallest bags by whole and largest bags by part, in order to get the ...
67
You are given an array of **positive** integers `beans`, where each integer represents the number of magic beans found in a particular magic bag. **Remove** any number of beans (**possibly none**) from each bag such that the number of beans in each remaining **non-empty** bag (still containing **at least one** bean) i...
How much is change actually necessary while calculating the required path? How many extra edges do we need to add to the shortest path?
✅ Python | Clear and Concise + Explanation
removing-minimum-number-of-magic-beans
0
1
If you want to make all the numbers the same inside an array (only decreasing is allowed)\nyou need to make `sum(arr) - len(arr) * min(arr)` operations overall as you need to decrease all elements by `arr[i] - min(arr)` where `0<=i<len(arr)`\n\nAs described in problem statement we can decrease number of beans in the ba...
21
You are given an array of **positive** integers `beans`, where each integer represents the number of magic beans found in a particular magic bag. **Remove** any number of beans (**possibly none**) from each bag such that the number of beans in each remaining **non-empty** bag (still containing **at least one** bean) i...
How much is change actually necessary while calculating the required path? How many extra edges do we need to add to the shortest path?
[Python3] 2-line
removing-minimum-number-of-magic-beans
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/2506277d2af78559a0e58d2130fdbe87beab42b5) for solutions of weekly 280. \n\n```\nclass Solution:\n def minimumRemoval(self, beans: List[int]) -> int:\n beans.sort()\n return sum(beans) - max((len(beans)-i)*x for i, x in enumerate(be...
4
You are given an array of **positive** integers `beans`, where each integer represents the number of magic beans found in a particular magic bag. **Remove** any number of beans (**possibly none**) from each bag such that the number of beans in each remaining **non-empty** bag (still containing **at least one** bean) i...
How much is change actually necessary while calculating the required path? How many extra edges do we need to add to the shortest path?
[Python3] Greedy + Sort - Simple Solution
removing-minimum-number-of-magic-beans
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInspired from this [solution](https://leetcode.com/problems/removing-minimum-number-of-magic-beans/solutions/1766795/java-python-3-sort-then-1-pass-find-max-rectangle-w-graph-explanation-and-analysis/) \n<!-- Describe your a...
0
You are given an array of **positive** integers `beans`, where each integer represents the number of magic beans found in a particular magic bag. **Remove** any number of beans (**possibly none**) from each bag such that the number of beans in each remaining **non-empty** bag (still containing **at least one** bean) i...
How much is change actually necessary while calculating the required path? How many extra edges do we need to add to the shortest path?
[Python3] Top-down DP without bitmask
maximum-and-sum-of-array
0
1
I think bitmask is unintuitive while the slots selection state can be stored as a string instead. Although the performance will be less than using bitmask but time complexity will be the same.\n\n# Code\n```\nclass Solution:\n def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n memo = {}\n ...
3
You are given an integer array `nums` of length `n` and an integer `numSlots` such that `2 * numSlots >= n`. There are `numSlots` slots numbered from `1` to `numSlots`. You have to place all `n` integers into the slots such that each slot contains at **most** two numbers. The **AND sum** of a given placement is the su...
null
[Python3] dp (top-down)
maximum-and-sum-of-array
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/2506277d2af78559a0e58d2130fdbe87beab42b5) for solutions of weekly 280. \n\n```\nclass Solution:\n def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n \n @cache\n def fn(k, m): \n """Return max AND su...
16
You are given an integer array `nums` of length `n` and an integer `numSlots` such that `2 * numSlots >= n`. There are `numSlots` slots numbered from `1` to `numSlots`. You have to place all `n` integers into the slots such that each slot contains at **most** two numbers. The **AND sum** of a given placement is the su...
null
Python | DFS with memo
maximum-and-sum-of-array
0
1
# Intuition\n\nDFS with memo.\n\n# Complexity\n- Time complexity: $$O(2^{2*numSlots})*numSlots$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(2^{numSlots})$$\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom functools import cache\n\nclass Solution:\n ...
0
You are given an integer array `nums` of length `n` and an integer `numSlots` such that `2 * numSlots >= n`. There are `numSlots` slots numbered from `1` to `numSlots`. You have to place all `n` integers into the slots such that each slot contains at **most** two numbers. The **AND sum** of a given placement is the su...
null
Python, maximal matching, 44ms, beats 100%
maximum-and-sum-of-array
0
1
# Intuition\n\nIt is maximal matching problem on a bipartite graph.\n\nOn one side are the given numbers on the other side are the slots from 1 to `numSlots`, twice each. It is a complete bipartite graph, where an edge `(a, b)` has weight `(a & b)` and we need to find a maximal matching. Or a minimal one if the edge we...
0
You are given an integer array `nums` of length `n` and an integer `numSlots` such that `2 * numSlots >= n`. There are `numSlots` slots numbered from `1` to `numSlots`. You have to place all `n` integers into the slots such that each slot contains at **most** two numbers. The **AND sum** of a given placement is the su...
null
simple.py
count-equal-and-divisible-pairs-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
Beats 65.34% | Count equal and divisible pairs
count-equal-and-divisible-pairs-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
Simplest solution beat 80%
count-equal-and-divisible-pairs-in-an-array
0
1
\n# Code\n```\nclass Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n count = 0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if nums[i] == nums[j] and (i * j) % k == 0:\n count += 1\n \n ret...
1
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
[Java/Python 3] Traverse indices with same values.
count-equal-and-divisible-pairs-in-an-array
1
1
```java\n public int countPairs(int[] nums, int k) {\n Map<Integer, List<Integer>> indices = new HashMap<>();\n for (int i = 0; i < nums.length; ++i) {\n indices.computeIfAbsent(nums[i], l -> new ArrayList<>()).add(i);\n } \n int cnt = 0;\n for (List<Integer> ind : indic...
21
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
[PYTHON 3] EASY | 2 FOR LOOPS | LOW MEMORY
count-equal-and-divisible-pairs-in-an-array
0
1
Runtime: **109 ms, faster than 81.87%** of Python3 online submissions for Count Equal and Divisible Pairs in an Array.\nMemory Usage: **13.8 MB, less than 98.09%** of Python3 online submissions for Count Equal and Divisible Pairs in an Array.\n```\nclass Solution:\n def countPairs(self, nums: List[int], k: int) -> i...
2
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
Pyhton3 solution using dictionary beats 99.7%
count-equal-and-divisible-pairs-in-an-array
0
1
# stats\n![Screenshot 2023-08-08 at 10.04.55 PM.png](https://assets.leetcode.com/users/images/50204932-e423-445f-a363-604c06a10146_1691512534.2270777.png)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe have a dictionary to ...
3
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
Python3 Solution fastest
count-equal-and-divisible-pairs-in-an-array
0
1
```\nclass Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n n=len(nums)\n c=0\n for i in range(0,n):\n for j in range(i+1,n):\n if nums[i]==nums[j] and ((i*j)%k==0):\n c+=1\n return c \n```
5
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
Easy to understand || O(n2) || Simple python
count-equal-and-divisible-pairs-in-an-array
0
1
```\ndef countPairs(self, nums: List[int], k: int) -> int:\n count = 0\n \n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if nums[i]==nums[j] and (i*j)%k==0:\n count+=1\n return count\n```
2
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
Python 3 (80ms) | Easy Brute Force N^2 Approach
count-equal-and-divisible-pairs-in-an-array
0
1
```\nclass Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n n=len(nums)\n c=0\n for i in range(0,n):\n for j in range(i+1,n):\n if nums[i]==nums[j] and ((i*j)%k==0):\n c+=1\n return c\n```
3
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
Count Equal and Divisible Pairs in an Array
count-equal-and-divisible-pairs-in-an-array
0
1
python 3 :\n```\nclass Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n count= 0\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if (nums[i]==nums[j]) and (i*j)%k==0:\n count+=1\n return count\n```
1
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[3,1,2,2,2,1,3\], k = 2 **Output:** 4 **Explanation:** There are 4 ...
What is the earliest time a course can be taken? How would you solve the problem if all courses take equal time? How would you generalize this approach?
[Java/Python 3] Divisible by 3.
find-three-consecutive-integers-that-sum-to-a-given-number
1
1
```java\n public long[] sumOfThree(long num) {\n if (num % 3 != 0) {\n return new long[0];\n }\n num /= 3;\n return new long[]{num - 1, num, num + 1};\n }\n```\n```python\n def sumOfThree(self, num: int) -> List[int]:\n if num % 3 == 0:\n num //= 3\n ...
16
Given an integer `num`, return _three consecutive integers (as a sorted array)_ _that **sum** to_ `num`. If `num` cannot be expressed as the sum of three consecutive integers, return _an **empty** array._ **Example 1:** **Input:** num = 33 **Output:** \[10,11,12\] **Explanation:** 33 can be expressed as 10 + 11 + 12 ...
What data structure can we use to count the frequency of each character? Are there edge cases where a character is present in one string but not the other?
[Python3] 1-line
find-three-consecutive-integers-that-sum-to-a-given-number
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/97dff55b43563450a33c98f2a216954117100dfe) for solutions of weekly 72. \n\n```\nclass Solution:\n def sumOfThree(self, num: int) -> List[int]:\n return [] if num % 3 else [num//3-1, num//3, num//3+1]\n```
5
Given an integer `num`, return _three consecutive integers (as a sorted array)_ _that **sum** to_ `num`. If `num` cannot be expressed as the sum of three consecutive integers, return _an **empty** array._ **Example 1:** **Input:** num = 33 **Output:** \[10,11,12\] **Explanation:** 33 can be expressed as 10 + 11 + 12 ...
What data structure can we use to count the frequency of each character? Are there edge cases where a character is present in one string but not the other?
Simple Maths || Python || Divisibility by 3
find-three-consecutive-integers-that-sum-to-a-given-number
0
1
```\nif num%3!=0:\n\treturn []\nelse:\n b=num//3\n return [b-1,b,b+1]\n```
1
Given an integer `num`, return _three consecutive integers (as a sorted array)_ _that **sum** to_ `num`. If `num` cannot be expressed as the sum of three consecutive integers, return _an **empty** array._ **Example 1:** **Input:** num = 33 **Output:** \[10,11,12\] **Explanation:** 33 can be expressed as 10 + 11 + 12 ...
What data structure can we use to count the frequency of each character? Are there edge cases where a character is present in one string but not the other?
Python 4 line solution.
find-three-consecutive-integers-that-sum-to-a-given-number
0
1
```\nclass Solution(object):\n def sumOfThree(self, num):\n """\n :type num: int\n :rtype: List[int]\n """\n if num%3==0:\n l=num//3\n return [l-1,l,l+1]\n return []\n \n \n```
1
Given an integer `num`, return _three consecutive integers (as a sorted array)_ _that **sum** to_ `num`. If `num` cannot be expressed as the sum of three consecutive integers, return _an **empty** array._ **Example 1:** **Input:** num = 33 **Output:** \[10,11,12\] **Explanation:** 33 can be expressed as 10 + 11 + 12 ...
What data structure can we use to count the frequency of each character? Are there edge cases where a character is present in one string but not the other?
[Java/Python 3] Greedy w/ brief explanation and analysis.
maximum-split-of-positive-even-integers
1
1
**Note:** For the rigorous proof of greedy algorithm correctness you can refer to \n\nsimilar problem: [881. Boats to Save People](https://leetcode.com/problems/boats-to-save-people/discuss/156855/javapython-3-onlogn-code-sorting-greedy-with-greedy-algorithm-proof) \n\nto prove it similarly.\n\n----\n\n1. Starting from...
121
You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. * For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 +...
The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at? After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at. Can you...
Greedy Approach (easy)
maximum-split-of-positive-even-integers
0
1
# Intuition\nConsider the example with the number 14. The strategy involves initiating the addition process with the smallest even number, as starting with smaller numbers tends to yield longer sequences. Continue adding even numbers until the sum surpasses or equals the target.\n\nCase 1: If the sum of even numbers ma...
2
You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. * For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 +...
The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at? After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at. Can you...
Simple Python Solution with Explanation || O(sqrt(n)) Time Complexity || O(1) Space Complexity
maximum-split-of-positive-even-integers
0
1
```\n\'\'\'VOTE UP, if you like and understand the solution\'\'\'\n\'\'\'You are free to correct my time complexity if you feel it is incorrect.\'\'\' \n```\n```\n**If finalSum is odd then their is no possible way**\n1. If finalSum is even then take s=0 and pointer i=2.\n2. add i in sum till s < finalSum and add i in...
58
You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. * For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 +...
The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at? After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at. Can you...
Python Solution by Splitting and Merging
maximum-split-of-positive-even-integers
0
1
Basically divide the numbers into sum of 2\'s and then join the 2\'s to make different even sized numbers by first taking one 2, then two 2\'s, then three 2\'s and so on. If we do not have the required number of 2\'s left, then just add the remaining 2\'s into the last integer in the array. We add them to the last elem...
10
You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. * For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 +...
The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at? After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at. Can you...
[Python3] Easy Math with Arithmetic Sequence
maximum-split-of-positive-even-integers
0
1
To obtain the maximum split, it makes sense to adopt the greedy algorithm: **always pick the current least possible even integer first such that we finally obtain a longest split**. If the remaining target sum becomes smaller than the current least possible even integer, we simply go one step back, and add to the end o...
2
You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. * For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 +...
The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at? After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at. Can you...
Python - O(finalSum^0.5) Easy Solution
maximum-split-of-positive-even-integers
0
1
If finalSum is divisible by 2, we can divide it by 2 and try to find list of unique positive integers that sum to finalSum. We can multiply everything by 2 at the end to return result. Take the smallest consecutive sequence i.e. 1,2,3,...,n -> this will have a sum of n*(n+1)/2. If this sum == finalSum, we are done. Thi...
7
You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. * For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 +...
The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at? After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at. Can you...
65% TC and 83% SC easy python solution
maximum-split-of-positive-even-integers
0
1
```\ndef maximumEvenSplit(self, finalSum: int) -> List[int]:\n\tif(finalSum % 2):\n\t\treturn []\n\tans = 0\n\ti = 2\n\ts = c = 0\n\tans = []\n\twhile(s != finalSum and i <= finalSum):\n\t\tif(i < (finalSum-s)//2 or i == finalSum-s):\n\t\t\tc += 1\n\t\t\tans.append(i)\n\t\t\ts += i\n\t\ti += 2\n\treturn ans\n```
2
You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers. * For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 +...
The robot only moves along the perimeter of the grid. Can you think if modulus can help you quickly compute which cell it stops at? After the robot moves one time, whenever the robot stops at some cell, it will always face a specific direction. i.e., The direction it faces is determined by the cell it stops at. Can you...
Python 3 SortedList solution, O(NlogN)
count-good-triplets-in-an-array
0
1
According to the question, first we obtain an index array `indices`, where `indices[i]` is the index of `nums1[i]` in `num2`, this can be done using a hashmap in `O(N)` time. For example, given `nums1 = [2,0,1,3], nums2 = [0,1,2,3]`, then `indices = [2,0,1,3]`; given `nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]`, then `in...
15
You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2`. In other words, if we consider `pos1v` as the i...
Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?
[Python3] sortedlist & fenwick tree
count-good-triplets-in-an-array
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/97dff55b43563450a33c98f2a216954117100dfe) for solutions of weekly 72. \n\n\n```\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n mp = {x : i for i, x in enu...
4
You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2`. In other words, if we consider `pos1v` as the i...
Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?
[Python] Simple O(NlogN) solution using bisect
count-good-triplets-in-an-array
0
1
```\nclass Solution:\n def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n res = 0\n m2 = [0] * n\n q = []\n \n\t\t# Build index map of nums2\n for i in range(n):\n m2[nums2[i]] = i\n \n for p1 in range(n):\n ...
2
You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2`. In other words, if we consider `pos1v` as the i...
Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?
Current Fastest Version Rewritten In Sensible Formatting | Commented and Explanation Attempted
count-good-triplets-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition here is not my own; my solution was way less elegant and involved binary search processing. This version is much cleaner and seems to use bitshifts and masking to accomplish a similar goal. Only intution is sparsely explained. T...
0
You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2`. In other words, if we consider `pos1v` as the i...
Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?
[Python] Straightforward binary search
count-good-triplets-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor triplet requirement, consider the middle one in the triplet, count how many "smaller" options in front and how many "bigger" options behind\n\n\n# Code\n```\nfrom bisect import bisect\n\nclass Solution:\n def goodTriplets(self, num...
0
You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2`. In other words, if we consider `pos1v` as the i...
Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?
Python (BIT)
count-good-triplets-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given two **0-indexed** arrays `nums1` and `nums2` of length `n`, both of which are **permutations** of `[0, 1, ..., n - 1]`. A **good triplet** is a set of `3` **distinct** values which are present in **increasing order** by position both in `nums1` and `nums2`. In other words, if we consider `pos1v` as the i...
Can we process the queries in a smart order to avoid repeatedly checking the same items? How can we use the answer to a query for other queries?
simple.py
count-integers-with-even-digit-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
Best solution for beginners in leetcode
count-integers-with-even-digit-sum
0
1
\n\n# Code\n```\nclass Solution:\n def countEven(self, num: int) -> int:\n count=0\n for i in range(1,num+1):\n digit=str(i)\n dsum=0\n for j in range(len(digit)):\n dsum+=int(digit[j])\n if dsum%2==0:\n count+=1\n\n retur...
1
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
Easy Python Solution - countEven || Beats 97%
count-integers-with-even-digit-sum
0
1
\n\n# Code\n```\nclass Solution:\n def countEven(self, num: int) -> int:\n c=0\n for i in range(2,num+1):\n sum,j = 0,i\n while j != 0:\n d = j % 10\n sum = sum + d\n j = j // 10\n if sum % 2 == 0:\n c += 1\n ...
1
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
O(1) solution with 3 lines beats 95%
count-integers-with-even-digit-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)...
1
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
[Python3, Java, C++] 1 liners O(length(num))
count-integers-with-even-digit-sum
1
1
**Brute force**:\nIterate through all the numbers from 1 to num inclusive and check if the sum of the digits of each number in that range is divisible by 2. \n<iframe src="https://leetcode.com/playground/jnt4pAME/shared" frameBorder="0" width="670" height="280"></iframe>\n\n\n**Observation**:\n```\nIntegers: ...
28
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
<Python3> O(1) - Discrete Formula - 100% faster - 1 LINE
count-integers-with-even-digit-sum
0
1
### We sum the digits of num.\n\n##### if the sum is **even** -> return num // 2\n##### if the sum is **odd** -> return (num - 1) // 2\n\n```\nclass Solution:\n def countEven(self, num: int) -> int:\n return num // 2 if sum([int(k) for k in str(num)]) % 2 == 0 else (num - 1) // 2\n```\n\t\t\n\t\t\n##### Sinc...
9
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
Easy python solution.
count-integers-with-even-digit-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe start a loop from range 1 till the num given to us,then we take digits one by one and check whether the sum of its digits are adding up to an even number.If yes we ...
1
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
Count Integer with even digit sum
count-integers-with-even-digit-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
Python | Easy Solution✅
count-integers-with-even-digit-sum
0
1
# Code\u2705\n```\nclass Solution:\n def countEven(self, num: int) -> int:\n count = 0\n for i in range(2,num+1):\n if sum(list(map(int, str(i).strip()))) % 2 == 0:\n count +=1\n return count\n```
6
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
Python 3 (30ms) | Simple Maths Formula | Even Odd Solution
count-integers-with-even-digit-sum
0
1
```\nclass Solution:\n def countEven(self, num: int) -> int:\n if num%2!=0:\n return (num//2)\n s=0\n t=num\n while t:\n s=s+(t%10)\n t=t//10\n if s%2==0:\n return num//2\n else:\n return (num//2)-1\n```
3
Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. The **digit sum** of a positive integer is the sum of all its digits. **Example 1:** **Input:** num = 4 **Output:** 2 **Explanation:** The only integers less than or equal to 4 wh...
Is it possible to assign the first k smallest tasks to the workers? How can you efficiently try every k?
Easy python solution
merge-nodes-in-between-zeros
0
1
```\ndef mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\tcurr = head\n\twhile(curr):\n\t\tif(curr.val == 0):\n\t\t\ts = 0\n\t\t\ttar = curr\n\t\t\tcurr = curr.next\n\t\t\twhile(curr.val != 0):\n\t\t\t\ts += curr.val\n\t\t\t\tcurr = curr.next\n\t\t\ttar.val = s\n\t\t\tif(curr.next):\n\t\t\t\ttar.nex...
2
You are given the `head` of a linked list, which contains a series of integers **separated** by `0`'s. The **beginning** and **end** of the linked list will have `Node.val == 0`. For **every** two consecutive `0`'s, **merge** all the nodes lying in between them into a single node whose value is the **sum** of all the ...
Starting with i=0, check the condition for each index. The first one you find to be true is the smallest index.
[ Python ] ✅✅ Simple Python Solution | Nested Loop 🥳✌👍
merge-nodes-in-between-zeros
0
1
# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 6310 ms, faster than 29.52% of Python3 online submissions for Merge Nodes in Between Zeros.\n# Memory Usage: 104.3 MB, less than 16.40% of Python3 online submissions for Merge Nodes in Between Zeros.\n\n\tclass S...
4
You are given the `head` of a linked list, which contains a series of integers **separated** by `0`'s. The **beginning** and **end** of the linked list will have `Node.val == 0`. For **every** two consecutive `0`'s, **merge** all the nodes lying in between them into a single node whose value is the **sum** of all the ...
Starting with i=0, check the condition for each index. The first one you find to be true is the smallest index.
[Java/Python 3] One pass two pointers, copy sum to 0 nodes.
merge-nodes-in-between-zeros
1
1
Use zero nodes to store the sum of merged nodes, remove the last zero node, which is unused.\n\n1. Use `prev` to connect and move among all zero nodes;\n2. Use `head` to traverse nodes between zero nodes, and add their values to the previous zero node;\n3. Always use `prev` point to the node right before current zero n...
21
You are given the `head` of a linked list, which contains a series of integers **separated** by `0`'s. The **beginning** and **end** of the linked list will have `Node.val == 0`. For **every** two consecutive `0`'s, **merge** all the nodes lying in between them into a single node whose value is the **sum** of all the ...
Starting with i=0, check the condition for each index. The first one you find to be true is the smallest index.
Python 3 Linked list - O(n) time and space - if you want to avoid the O(logN) heap push/pop
construct-string-with-repeat-limit
0
1
# Approach\nThis approach is similar to that of a priority queue / heap.\n\nHowever, using a linked list avoid the O(logN) time operations of heappush() and heappop().\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n"""\nImplementation of a Node in a linked list.\n"""\nclass Node:...
2
You are given a string `s` and an integer `repeatLimit`. Construct a new string `repeatLimitedString` using the characters of `s` such that no letter appears **more than** `repeatLimit` times **in a row**. You do **not** have to use all characters from `s`. Return _the **lexicographically largest**_ `repeatLimitedStri...
The maximum distance must be the distance between the first and last critical point. For each adjacent critical point, calculate the difference and check if it is the minimum distance.
[Python3] priority queue
construct-string-with-repeat-limit
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/793daa0aab0733bfadd4041fdaa6f8bdd38fe229) for solutions of weekly 281. \n\n```\nclass Solution:\n def repeatLimitedString(self, s: str, repeatLimit: int) -> str:\n pq = [(-ord(k), v) for k, v in Counter(s).items()] \n heapify(pq)\n...
29
You are given a string `s` and an integer `repeatLimit`. Construct a new string `repeatLimitedString` using the characters of `s` such that no letter appears **more than** `repeatLimit` times **in a row**. You do **not** have to use all characters from `s`. Return _the **lexicographically largest**_ `repeatLimitedStri...
The maximum distance must be the distance between the first and last critical point. For each adjacent critical point, calculate the difference and check if it is the minimum distance.
Greedy Python Solution | 100% Runtime
construct-string-with-repeat-limit
0
1
Upvote if you find this article helpful\u2B06\uFE0F.\n### STEPS:\n1. Basically we make a sorted table with freq of each character.\n2. Then we take the most lexicographically superior character (Call it A).\n3. If its freq is in limits, directly add it.\n4. If its freq is more than the limit. Add repeatLimit number of ...
4
You are given a string `s` and an integer `repeatLimit`. Construct a new string `repeatLimitedString` using the characters of `s` such that no letter appears **more than** `repeatLimit` times **in a row**. You do **not** have to use all characters from `s`. Return _the **lexicographically largest**_ `repeatLimitedStri...
The maximum distance must be the distance between the first and last critical point. For each adjacent critical point, calculate the difference and check if it is the minimum distance.