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
[Python3] Priority Queue + Greedy + Couting - Simple Solution
construct-string-with-repeat-limit
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(NlogN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity ...
1
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] factors
count-array-pairs-divisible-by-k
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/793daa0aab0733bfadd4041fdaa6f8bdd38fe229) for solutions of weekly 281. \n\n```\nclass Solution:\n def coutPairs(self, nums: List[int], k: int) -> int:\n factors = []\n for x in range(1, int(sqrt(k))+1):\n if k % x == 0: ...
6
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _such that:_ * `0 <= i < j <= n - 1` _and_ * `nums[i] * nums[j]` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], k = 2 **Output:** 7 **Explanation:** The 7 pairs of indic...
Once x drops below 0 or goes above 1000, is it possible to continue performing operations on x? How can you use BFS to find the minimum operations?
Just like Two-Sum hashmap
count-array-pairs-divisible-by-k
1
1
**It\'s just like two sum in that we were storing the remaining part if the target sum was 10 and we found 7 we were storing the 10-7 in hashmap so if we found 3 we will return it\'s index from there same we need to find the product which is divisible by k so for example if we need to make a pair which is divisible by ...
11
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _such that:_ * `0 <= i < j <= n - 1` _and_ * `nums[i] * nums[j]` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], k = 2 **Output:** 7 **Explanation:** The 7 pairs of indic...
Once x drops below 0 or goes above 1000, is it possible to continue performing operations on x? How can you use BFS to find the minimum operations?
Python | O(N * (k^1/3)) | Easy code with explanation (Get all factors)
count-array-pairs-divisible-by-k
0
1
## Explanation:\n1. We can get all factors of `k` first.\n2. For each `num` in `nums`, `k // gcd(num, k)` will be the multiplier that num needs that make the result is divisible by `k`.\n3. We use `counter` to maintain how many numbers is divisible by factors of `k`.\n\n\n## Solutions:\n```\nclass Solution:\n def c...
1
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _such that:_ * `0 <= i < j <= n - 1` _and_ * `nums[i] * nums[j]` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], k = 2 **Output:** 7 **Explanation:** The 7 pairs of indic...
Once x drops below 0 or goes above 1000, is it possible to continue performing operations on x? How can you use BFS to find the minimum operations?
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
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. -->\nThe algorithm counts pairs of numbers in the list where their Greatest Common Divisor (GCD)is divisible by k. The GCD represents the largest common factor between two ...
0
Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _such that:_ * `0 <= i < j <= n - 1` _and_ * `nums[i] * nums[j]` _is divisible by_ `k`. **Example 1:** **Input:** nums = \[1,2,3,4,5\], k = 2 **Output:** 7 **Explanation:** The 7 pairs of indic...
Once x drops below 0 or goes above 1000, is it possible to continue performing operations on x? How can you use BFS to find the minimum operations?
Simple solution in Python3
counting-words-with-a-given-prefix
0
1
# Intuition\nHere we have:\n- `words` and `pref`\n- our goal is to find, **how many** words start from `pref`\n\n# Approach\n1. declare `ans`\n2. for each word check `startswith(pref)`\n\n# Complexity\n- Time complexity: **O(N*K)** since we iterate over `words` by length `K`\n\n- Space complexity: **O(1)**, we don\'t a...
1
You are given an array of strings `words` and a string `pref`. Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** words = \[ "pay ", "**at**tention ", "practice ", "**at**tend "\], `pre...
null
Simplest Python solution. Use startswith
counting-words-with-a-given-prefix
0
1
\n\n# Code\n```\nclass Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n cnt = 0\n for s in words:\n if s.startswith(pref):\n cnt += 1\n return cnt\n```
3
You are given an array of strings `words` and a string `pref`. Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** words = \[ "pay ", "**at**tention ", "practice ", "**at**tend "\], `pre...
null
Python one line simple solution
counting-words-with-a-given-prefix
0
1
**Python**\n\n```\ndef prefixCount(self, words: List[str], pref: str) -> int:\n\treturn sum([word.startswith(pref) for word in words])\n```\n\n**Like it ? please upvote !**
15
You are given an array of strings `words` and a string `pref`. Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** words = \[ "pay ", "**at**tention ", "practice ", "**at**tend "\], `pre...
null
Python easy Solution | using Counter
minimum-number-of-steps-to-make-two-strings-anagram-ii
0
1
\n# Code\n```\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n cnt1=Counter(s)\n cnt2=Counter(t)\n sm=0\n cnt=cnt1-cnt2+(cnt2-cnt1)\n for i in cnt.values():\n sm+=i\n return sm\n```
3
You are given two strings `s` and `t`. In one step, you can append **any character** to either `s` or `t`. Return _the minimum number of steps to make_ `s` _and_ `t` _**anagrams** of each other._ An **anagram** of a string is a string that contains the same characters with a different (or the same) ordering. **Examp...
While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant? Can you store the count of characters to avoid generating substrings altogether?
[Python3, Java, C++] Counter O(len(s) + (len(t))
minimum-number-of-steps-to-make-two-strings-anagram-ii
1
1
* Count the number of characters in each string \n* Compare the counts for each character\n* If the counts of the characters don\'t match, add the difference of the counts to answer\n<iframe src="https://leetcode.com/playground/TrFoEYxb/shared" frameBorder="0" width="600" height="200"></iframe>\n\nTime complexity: `O(l...
43
You are given two strings `s` and `t`. In one step, you can append **any character** to either `s` or `t`. Return _the minimum number of steps to make_ `s` _and_ `t` _**anagrams** of each other._ An **anagram** of a string is a string that contains the same characters with a different (or the same) ordering. **Examp...
While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant? Can you store the count of characters to avoid generating substrings altogether?
[Python3] freq table
minimum-number-of-steps-to-make-two-strings-anagram-ii
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/6f8a2c98f0feab59d2e0ec35f928e3ee1d3e4456) for solutions of weekly 282. \n\n```\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n fs, ft = Counter(s), Counter(t)\n return sum((fs-ft).values()) + sum((ft-fs).values())\n...
6
You are given two strings `s` and `t`. In one step, you can append **any character** to either `s` or `t`. Return _the minimum number of steps to make_ `s` _and_ `t` _**anagrams** of each other._ An **anagram** of a string is a string that contains the same characters with a different (or the same) ordering. **Examp...
While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant? Can you store the count of characters to avoid generating substrings altogether?
Counter
minimum-number-of-steps-to-make-two-strings-anagram-ii
0
1
For some reason, I misread the description, and tried to solve another problem.\n\n**Python 3**\n```python\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n cs, ct = Counter(s), Counter(t)\n return sum(cnt for ch, cnt in ((cs - ct) + (ct - cs)).items())\n```\n**C++**\n```cpp\nint minSteps...
6
You are given two strings `s` and `t`. In one step, you can append **any character** to either `s` or `t`. Return _the minimum number of steps to make_ `s` _and_ `t` _**anagrams** of each other._ An **anagram** of a string is a string that contains the same characters with a different (or the same) ordering. **Examp...
While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant? Can you store the count of characters to avoid generating substrings altogether?
Self Understandable Python (2 methods) :
minimum-number-of-steps-to-make-two-strings-anagram-ii
0
1
**Method 1:**\n```\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n a=Counter(s)\n b=Counter(t)\n c=(a-b)+(b-a)\n \n count=0\n for i in c:\n count+=c[i]\n return count\n```\n**Method 2:**\n```\nclass Solution:\n def minSteps(self, s: str, ...
3
You are given two strings `s` and `t`. In one step, you can append **any character** to either `s` or `t`. Return _the minimum number of steps to make_ `s` _and_ `t` _**anagrams** of each other._ An **anagram** of a string is a string that contains the same characters with a different (or the same) ordering. **Examp...
While generating substrings starting at any index, do you need to continue generating larger substrings if you encounter a consonant? Can you store the count of characters to avoid generating substrings altogether?
Solution with clear explanation and example with a plot.
minimum-time-to-complete-trips
0
1
# Intuition\n--> Since number of trips possible for a given number of days with respect to time array is monotonic, we can use Binary search on the ouput limit.\n\n--> Output is monotonic because when output increases trips you can make is non decresing with respect to time array.\n\n--> Example to understand it is mon...
3
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
[Python] One-liner, two-liner
minimum-time-to-complete-trips
0
1
# Approach\nBinary search (or rather, bisect) the minimum time required to fulfill all trips.\n\n# Code\n\n### Two liner\n```\nclass Solution:\n def minimumTime(self, time: List[int], totalTrips: int) -> int:\n check = lambda t: sum(t // bus for bus in time) >= totalTrips\n return bisect_left(range(tim...
2
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
📌📌Python3 || ⚡1737 ms, faster than 97.75% of Python3
minimum-time-to-complete-trips
0
1
![image](https://assets.leetcode.com/users/images/dd9c3714-4bca-483d-8fc6-8411cb7a43e4_1678200467.7560015.png)\n```\ndef minimumTime(self, time: List[int], totalTrips: int) -> int:\n def check(t):\n res = 0\n for e in time:\n res += t//e\n return res >= totalTrips\...
2
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
Python Solution || Faster than 96% of other solutions
minimum-time-to-complete-trips
0
1
Please Upvote if you like it.\n```\nclass Solution:\n def minimumTime(self, time: List[int], totalTrips: int) -> int:\n a, b = 1, totalTrips * min(time)\n\n def f(x):\n return sum(x // t for t in time) >= totalTrips\n \n while a < b:\n m = (a + b) // 2\n if no...
2
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
beats 100% space complexity.
minimum-time-to-complete-trips
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nas the question requires as to find the minimum time required to finish the total trip. first i needed to find the range in which the solution can lay and traverse through that inorder to reach an optimal solution. \n\n# Approach\n<!-- De...
2
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
✅ All Binary Search Problems 🔥🔥
minimum-time-to-complete-trips
1
1
**Good Binary Search Problems**\n* [1552. Magnetic Force Between Two Balls](https://leetcode.com/problems/magnetic-force-between-two-balls/)\n* [1870. Minimum Speed to Arrive on Time](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/)\n* [875. Koko Eating Bananas](https://leetcode.com/problems/koko-eating-...
308
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
Clean Code Python
minimum-time-to-complete-trips
0
1
**Please upvote if u liked the solution**\n```\nclass Solution:\n def minimumTime(self, time: List[int], totalTrips: int) -> int:\n return bisect_left(range(time[0] * totalTrips + 1), True, key=lambda t: sum(t // bus for bus in time) >= totalTrips)\n```
1
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
python3 || simple binary search
minimum-time-to-complete-trips
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe can reduce half the search space for time, in eac iteration of binary search.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nbinay search\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g...
1
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
O(n log(k)) solution | 1378 ms in Python3 | Beats 100%
minimum-time-to-complete-trips
0
1
Here is a solution which is more efficient that the solutions using only the minimum of `time` for computing the upper bound.\n\nEDIT: I added an improvement whose worst-case complexity only depends on $$n$$: no matter `totalTrips` and the values in `time`, it runs in at most $$O(n \\log(n))$$, and it can be faster dep...
1
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
Python solution
minimum-time-to-complete-trips
0
1
# Code\n```\nclass Solution:\n def minimumTime(self, time: List[int], totalTrips: int) -> int:\n left = 1\n right = max(time) * totalTrips\n\n while right > left:\n mid = (left + right)//2\n sums = sum([mid//t for t in time])\n if sums >= totalTrips:\n ...
1
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
Python short and clean. Binary Search.
minimum-time-to-complete-trips
0
1
# Approach\nNotice that the time needed can never be greater than `min(time) * total_trips`.\nLeveraging this, binary search for `min_time` in the range `[0, min(time) * total_trips]`\n\n# Complexity\n- Time complexity: $$O(n * log(n * k))$$\n\n- Space complexity: $$O(1)$$\n\nwhere,\n`n is length of time`,\n`k is total...
1
You are given an array `time` where `time[i]` denotes the time taken by the `ith` bus to complete **one trip**. Each bus can make multiple trips **successively**; that is, the next trip can start **immediately after** completing the current trip. Also, each bus operates **independently**; that is, the trips of one bus...
Since generating substrings is not an option, can we count the number of substrings a vowel appears in? How much does each vowel contribute to the total sum?
[Python] DP with pre-treatment to reduce time complexity
minimum-time-to-finish-the-race
0
1
Let t[n] denotes the minimum time to run n laps, the DP equation is thus:\nt[n] = min {r = 1 ~ min(maxt,n)} t[r] + changeTime + t[n-r]\n\nNow we add some pre-treatment:\n1) The default value of t[n] for any n can be set as changeTime * (n-1) + min(f) * n, i.e., change tire after every lap. \n2) We don\'t need to consid...
4
You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
Hindsight is the Answer | Commented and Explained
minimum-time-to-finish-the-race
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRather than try to figure it out before or as you run the race, figure it out afterwards. The key is that we are trying to discern the best possible lap for the best possible set of tires from the sets of all tires that can be changed to ...
0
You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
Beat 100% submissions
minimum-time-to-finish-the-race
0
1
# Intuition\nProprocessing for reduce the computation, and then do a simple DP. \n\n# Code\n```\nclass Solution:\n def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n def filter_tires():\n min_r, out = float(\'inf\'), []\n for f, r in sorted(tires...
0
You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
beats 97% , simple DP
minimum-time-to-finish-the-race
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** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
DP ?>? easy shit no fancy shit fk that
minimum-time-to-finish-the-race
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumFinishTime(self, tires: List[List[int]], ct: int, nl: int) -> int:\n cn=[]\n dis=[float("inf")]*(nl+1)\n for x,y in tires:\n cnt=-1\n res=0\n while x*(pow(y,cnt+...
0
You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
Python (Simple DP)
minimum-time-to-finish-the-race
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** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
Easy Python solution for beginners with comments
minimum-time-to-finish-the-race
0
1
# Intuition\n\nSimilar idea to other solutions but I think this version is easier to understand for beginners. \n\nFirst, we use Dynamic Programming. Below is the recurrent equation.\n\n- `dp[i]` is optimal solution of `numLaps=i+1`\n- `dp[0] = best time to complete 1 lap without changing tires`\n- `dp[i] = min(b0, b1,...
0
You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
Python Comments easy DP to improved DP
minimum-time-to-finish-the-race
0
1
Solution: find all possible combinations, use DP\n- state: dp[i] the number of seconds after finish lap i, after changing tire, it is a new start.\n- policy: dp[i, new_tire] = min(dp[i - j, old_tire] + cost of time from change tire at i-j lap to i lap)\n- actions: 1. change to tire j after lap i - 1, 0<= j < n; 2. cont...
0
You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
DP : transit function
minimum-time-to-finish-the-race
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n transit function:\n f(i) = min(f(k) + changeTime + f(i - k)) when k = [1,i)) \n reduce the range of k for the symmetric of k and i-k\n f(i) = min(f(i), sum(f * power(r, j) for j in (0, i - 1)) when k == 0...
0
You are given a **0-indexed** 2D integer array `tires` where `tires[i] = [fi, ri]` indicates that the `ith` tire can finish its `xth` successive lap in `fi * ri(x-1)` seconds. * For example, if `fi = 3` and `ri = 2`, then the tire would finish its `1st` lap in `3` seconds, its `2nd` lap in `3 * 2 = 6` seconds, its `...
There exists a monotonic nature such that when x is smaller than some number, there will be no way to distribute, and when x is not smaller than that number, there will always be a way to distribute. If you are given a number k, where the number of products given to any store does not exceed k, could you determine if a...
Python dictionary
most-frequent-number-following-key-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 a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`. For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `key` in `nums`. In other words, count the number of indices `i` such that: * ...
Could you try every word? Could you use a hash map to achieve a good complexity?
Python3 O(N) solution with dictionary and heap (90.83% Runtime)
most-frequent-number-following-key-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/4ee43f3a-27ac-4a1b-b2fb-206a4480b64d_1698043766.336558.png)\nStore and retrieve value counts with dictionary. Then utilize heap with the counts as a priority for the value.\n\n# Approa...
1
You are given a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`. For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `key` in `nums`. In other words, count the number of indices `i` such that: * ...
Could you try every word? Could you use a hash map to achieve a good complexity?
[Java/Python 3] Simple code.
most-frequent-number-following-key-in-an-array
1
1
**Java**\n```java\n public int mostFrequent(int[] nums, int key) {\n Map<Integer, Integer> freq = new HashMap<>();\n int mostFreq = -1;\n for (int i = 0, n = nums.length, max = 0; i + 1 < n; ++i) {\n if (nums[i] == key) {\n int candidate = nums[i + 1];\n ...
26
You are given a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`. For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `key` in `nums`. In other words, count the number of indices `i` such that: * ...
Could you try every word? Could you use a hash map to achieve a good complexity?
Python 2 Lines Functional Style
most-frequent-number-following-key-in-an-array
0
1
# Intuition\nGet a list of all the values that come right after the keys\nThen return the most frequent one\n\n# Code\n```\nclass Solution:\n def mostFrequent(self, nums: List[int], key: int) -> int:\n l = [t for k,t in zip(nums, nums[1:]) if k == key]\n return max(set(l), key = l.count)\n```
2
You are given a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`. For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `key` in `nums`. In other words, count the number of indices `i` such that: * ...
Could you try every word? Could you use a hash map to achieve a good complexity?
Python - Multiple Solutions + One-Liners | Clean and Simple
most-frequent-number-following-key-in-an-array
0
1
**Solution - Count by hand**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n counts = {}\n \n for i in range(1,len(nums)):\n if nums[i-1]==key:\n if nums[i] not in counts: counts[nums[i]] = 1\n else: counts[nums[i]] += 1\n \n r...
8
You are given a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`. For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `key` in `nums`. In other words, count the number of indices `i` such that: * ...
Could you try every word? Could you use a hash map to achieve a good complexity?
Python3 Readable
most-frequent-number-following-key-in-an-array
0
1
\n\n# Code\n```\nclass Solution:\n def mostFrequent(self, nums: List[int], key: int) -> int:\n targets = []\n\n for i in range(len(nums) - 1):\n if nums[i] == key:\n targets.append(nums[i + 1])\n \n count = collections.Counter(targets)\n\n return sorted(co...
0
You are given a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`. For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `key` in `nums`. In other words, count the number of indices `i` such that: * ...
Could you try every word? Could you use a hash map to achieve a good complexity?
ChatGTP 3.5 solution
most-frequent-number-following-key-in-an-array
0
1
# Intuition\nChatGTP 3.5 solution\n\n# Approach\n\nUsing a dictionary target_counts to keep track of the counts of targets that follow the key. The loop iterates through the elements of nums, and whenever it encounters an element equal to the key, it looks at the next element (target) and updates its count in the targe...
0
You are given a **0-indexed** integer array `nums`. You are also given an integer `key`, which is present in `nums`. For every unique integer `target` in `nums`, **count** the number of times `target` immediately follows an occurrence of `key` in `nums`. In other words, count the number of indices `i` such that: * ...
Could you try every word? Could you use a hash map to achieve a good complexity?
Python Simple Solution using sort()
sort-the-jumbled-numbers
0
1
\n```\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n def c(n):\n v=""\n for p in str(n):\n v+=str(mapping[int(p)])\n return int(v)\n k=[]\n for p in range(len(nums)):\n k.append([c(nums[p]),...
1
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
Python Simple Solution using sort()
sort-the-jumbled-numbers
0
1
\n```\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n def c(n):\n v=""\n for p in str(n):\n v+=str(mapping[int(p)])\n return int(v)\n k=[]\n for p in range(len(nums)):\n k.append([c(nums[p]),...
1
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
[Java/Python 3] Convert and sort indices accordingly.
sort-the-jumbled-numbers
1
1
**Q & A**\n*Q*: How is `Arrays.sort(indices, Comparator.comparing(i -> convert(nums[i], mapping)));` sorting the elements of `indices` array?\n\n*A*: Sort the `i`\'s in `indices` according to the corresponding value of `convert(nums[i], mapping)`. E.g.,\n\nInput: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]\n\n...
24
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
[Java/Python 3] Convert and sort indices accordingly.
sort-the-jumbled-numbers
1
1
**Q & A**\n*Q*: How is `Arrays.sort(indices, Comparator.comparing(i -> convert(nums[i], mapping)));` sorting the elements of `indices` array?\n\n*A*: Sort the `i`\'s in `indices` according to the corresponding value of `convert(nums[i], mapping)`. E.g.,\n\nInput: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]\n\n...
24
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Sorted Lambda
sort-the-jumbled-numbers
0
1
\nWe will use Python to leverage `@cache`.\n> Note: the solution is accepted without cahce (since constraints are relaxed).\n\nWatch for `0` edge case and convert it to a number using `mapping`.\n\n**Python**\n```python\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n ...
8
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
Sorted Lambda
sort-the-jumbled-numbers
0
1
\nWe will use Python to leverage `@cache`.\n> Note: the solution is accepted without cahce (since constraints are relaxed).\n\nWatch for `0` edge case and convert it to a number using `mapping`.\n\n**Python**\n```python\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n ...
8
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
python 1-line
sort-the-jumbled-numbers
0
1
```\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n \n return sorted(nums, key = lambda x: int("".join([str(mapping[int(digit)]) for digit in str(x)])))\n```
2
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
python 1-line
sort-the-jumbled-numbers
0
1
```\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n \n return sorted(nums, key = lambda x: int("".join([str(mapping[int(digit)]) for digit in str(x)])))\n```
2
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
[Python] - 10 Liner Solution ✔
sort-the-jumbled-numbers
0
1
\tclass Solution:\n\t\tdef sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n\t\t\tres = []\n\t\t\tfor num in nums:\n\t\t\t\tans = ""\n\t\t\t\tfor char in str(num):\n\t\t\t\t\tans += str(mapping[int(char)])\n\t\t\t\tres.append(int(ans))\n\t\t\tfinal = list(zip(nums, res))\n\t\t\tfinal = sorted(final...
2
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
[Python] - 10 Liner Solution ✔
sort-the-jumbled-numbers
0
1
\tclass Solution:\n\t\tdef sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n\t\t\tres = []\n\t\t\tfor num in nums:\n\t\t\t\tans = ""\n\t\t\t\tfor char in str(num):\n\t\t\t\t\tans += str(mapping[int(char)])\n\t\t\t\tres.append(int(ans))\n\t\t\tfinal = list(zip(nums, res))\n\t\t\tfinal = sorted(final...
2
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Easy Solution! || PYTHON || BEATS 98.8%|| SORTING
sort-the-jumbled-numbers
0
1
```\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n mapp = {ind:val for ind,val in enumerate(mapping)}\n # print(mapp)\n ans = []\n for num in nums:\n pre , alph = 1 , 0\n if num == 0:alph = mapp[num]\n org= nu...
0
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
Easy Solution! || PYTHON || BEATS 98.8%|| SORTING
sort-the-jumbled-numbers
0
1
```\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n mapp = {ind:val for ind,val in enumerate(mapping)}\n # print(mapp)\n ans = []\n for num in nums:\n pre , alph = 1 , 0\n if num == 0:alph = mapp[num]\n org= nu...
0
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Python | Custom Sorting | Japanese
sort-the-jumbled-numbers
0
1
# Complexity\n## Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(NlogN + NlogD)$$, $N = nums$\u306E\u8981\u7D20\u6570 $$D = nums$$\u306B\u542B\u307E\u308C\u308B\u8981\u7D20\u306E\u6700\u5927\u5024\n\n\u524D\u534A\u306F\u30BD\u30FC\u30C8\u306E\u6642\u9593\u8A08\u7B97\u91CF\u306A\u306E\u3067\...
0
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
Python | Custom Sorting | Japanese
sort-the-jumbled-numbers
0
1
# Complexity\n## Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(NlogN + NlogD)$$, $N = nums$\u306E\u8981\u7D20\u6570 $$D = nums$$\u306B\u542B\u307E\u308C\u308B\u8981\u7D20\u306E\u6700\u5927\u5024\n\n\u524D\u534A\u306F\u30BD\u30FC\u30C8\u306E\u6642\u9593\u8A08\u7B97\u91CF\u306A\u306E\u3067\...
0
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
Python Solution to the problem
sort-the-jumbled-numbers
0
1
# Intuition\nThe intuition behind the solution is to create a dictionary (new) to store the mapped values of each number in nums. Then, sort the dictionary keys to get the mapped values in non-decreasing order. Finally, concatenate the lists associated with each key to get the sorted array.\n\n# Approach\nInitialize an...
0
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
Python Solution to the problem
sort-the-jumbled-numbers
0
1
# Intuition\nThe intuition behind the solution is to create a dictionary (new) to store the mapped values of each number in nums. Then, sort the dictionary keys to get the mapped values in non-decreasing order. Finally, concatenate the lists associated with each key to get the sorted array.\n\n# Approach\nInitialize an...
0
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
[Python3] Simple Sort Solution
sort-the-jumbled-numbers
0
1
# Code\n```\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n hm = dict()\n newNums = []\n for i, e in enumerate(nums):\n newE = ""\n sNum = str(e)\n for ch in sNum:\n newE += str(mapping[int(ch)])\n ...
0
You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system. The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer wi...
When is it impossible to collect the rainwater from all the houses? When one or more houses do not have an empty space adjacent to it. Assuming the rainwater from all previous houses is collected. If there is a house at index i and you are able to place a bucket at index i - 1 or i + 1, where should you put it? It is a...
[Python3] Simple Sort Solution
sort-the-jumbled-numbers
0
1
# Code\n```\nclass Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n hm = dict()\n newNums = []\n for i, e in enumerate(nums):\n newE = ""\n sNum = str(e)\n for ch in sNum:\n newE += str(mapping[int(ch)])\n ...
0
Given the array `restaurants` where `restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]`. You have to filter the restaurants using three filters. The `veganFriendly` filter will be either _true_ (meaning you should only include restaurants with `veganFriendlyi` set to true) or _false_ (meaning you can ...
Map the original numbers to new numbers by the mapping rule and sort the new numbers. To maintain the same relative order for equal mapped values, use the index in the original input array as a tiebreaker.
[Java/Python 3] 2 codes:Topological sort & DFS, w/ brief explanation and comments.
all-ancestors-of-a-node-in-a-directed-acyclic-graph
1
1
**Topological Sort**\n\n1. Build graph from parent to kids, and compute in-degree for each node;\n2. Use topological to get direct parent and all ancestors of the direct parent of each node;\n\n```java\n public List<List<Integer>> getAncestors(int n, int[][] edges) {\n \n // Build graph, and compute in...
50
You are given a positive integer `n` representing the number of nodes of a **Directed Acyclic Graph** (DAG). The nodes are numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges`, where `edges[i] = [fromi, toi]` denotes that there is a **unidirectional** edge from `fromi` to `toi` i...
Irrespective of what path the robot takes, it will have to traverse all the rows between startRow and homeRow and all the columns between startCol and homeCol. Hence, making any other move other than traversing the required rows and columns will potentially incur more cost which can be avoided.
[Java/Python 3] 2 codes:Topological sort & DFS, w/ brief explanation and comments.
all-ancestors-of-a-node-in-a-directed-acyclic-graph
1
1
**Topological Sort**\n\n1. Build graph from parent to kids, and compute in-degree for each node;\n2. Use topological to get direct parent and all ancestors of the direct parent of each node;\n\n```java\n public List<List<Integer>> getAncestors(int n, int[][] edges) {\n \n // Build graph, and compute in...
50
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _i...
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
Python3 | Solved using Topo Sort(Kahn Algo) with Queue(BFS)
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0
1
```\nclass Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n #Use Kahn\'s algorithm of toposort using a queue and bfs!\n graph = [[] for _ in range(n)]\n indegrees = [0] * n\n \n #Time: O(n^2)\n #Space: O(n^2 + n + n) -> O(n^2)\n ...
4
You are given a positive integer `n` representing the number of nodes of a **Directed Acyclic Graph** (DAG). The nodes are numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges`, where `edges[i] = [fromi, toi]` denotes that there is a **unidirectional** edge from `fromi` to `toi` i...
Irrespective of what path the robot takes, it will have to traverse all the rows between startRow and homeRow and all the columns between startCol and homeCol. Hence, making any other move other than traversing the required rows and columns will potentially incur more cost which can be avoided.
Python3 | Solved using Topo Sort(Kahn Algo) with Queue(BFS)
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0
1
```\nclass Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n #Use Kahn\'s algorithm of toposort using a queue and bfs!\n graph = [[] for _ in range(n)]\n indegrees = [0] * n\n \n #Time: O(n^2)\n #Space: O(n^2 + n + n) -> O(n^2)\n ...
4
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _i...
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
dfs from child to parent
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0
1
# approach:\njust take transpose of the graph and call dfs for each node.\nAs graph edges are reversed and we are calling dfs, its like calling dfs from leaf to parent, and just keep appending the vertices which are not in ans[node]..... \n\n\n# Code\n```\nclass Solution:\n def getAncestors(self, n: int, edges: List...
4
You are given a positive integer `n` representing the number of nodes of a **Directed Acyclic Graph** (DAG). The nodes are numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges`, where `edges[i] = [fromi, toi]` denotes that there is a **unidirectional** edge from `fromi` to `toi` i...
Irrespective of what path the robot takes, it will have to traverse all the rows between startRow and homeRow and all the columns between startCol and homeCol. Hence, making any other move other than traversing the required rows and columns will potentially incur more cost which can be avoided.
dfs from child to parent
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0
1
# approach:\njust take transpose of the graph and call dfs for each node.\nAs graph edges are reversed and we are calling dfs, its like calling dfs from leaf to parent, and just keep appending the vertices which are not in ans[node]..... \n\n\n# Code\n```\nclass Solution:\n def getAncestors(self, n: int, edges: List...
4
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _i...
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
Python Elegant & Short | Reverse edges
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0
1
```\nfrom collections import defaultdict\nfrom typing import Iterable, List\n\n\nclass Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> Iterable[List[int]]:\n def dfs(u: int) -> set:\n if not ancestors[u]:\n for v in graph[u]:\n if v not in anc...
2
You are given a positive integer `n` representing the number of nodes of a **Directed Acyclic Graph** (DAG). The nodes are numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges`, where `edges[i] = [fromi, toi]` denotes that there is a **unidirectional** edge from `fromi` to `toi` i...
Irrespective of what path the robot takes, it will have to traverse all the rows between startRow and homeRow and all the columns between startCol and homeCol. Hence, making any other move other than traversing the required rows and columns will potentially incur more cost which can be avoided.
Python Elegant & Short | Reverse edges
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0
1
```\nfrom collections import defaultdict\nfrom typing import Iterable, List\n\n\nclass Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> Iterable[List[int]]:\n def dfs(u: int) -> set:\n if not ancestors[u]:\n for v in graph[u]:\n if v not in anc...
2
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _i...
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
🐍 python, simple BFS solution with explanation; O(V+E)
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0
1
# Intuition\nThis is a topoligical sort problem. Here we use the famous Kahn\'s algo. \n\n# Approach\n1) Like most of the graphs problem first we create and adjacency map and in_degree dictionary.\n2) Then we create a queue and add the nodes with no parent (in_degree[node]==0 or node not in_degree), we add that to the ...
1
You are given a positive integer `n` representing the number of nodes of a **Directed Acyclic Graph** (DAG). The nodes are numbered from `0` to `n - 1` (**inclusive**). You are also given a 2D integer array `edges`, where `edges[i] = [fromi, toi]` denotes that there is a **unidirectional** edge from `fromi` to `toi` i...
Irrespective of what path the robot takes, it will have to traverse all the rows between startRow and homeRow and all the columns between startCol and homeCol. Hence, making any other move other than traversing the required rows and columns will potentially incur more cost which can be avoided.
🐍 python, simple BFS solution with explanation; O(V+E)
all-ancestors-of-a-node-in-a-directed-acyclic-graph
0
1
# Intuition\nThis is a topoligical sort problem. Here we use the famous Kahn\'s algo. \n\n# Approach\n1) Like most of the graphs problem first we create and adjacency map and in_degree dictionary.\n2) Then we create a queue and add the nodes with no parent (in_degree[node]==0 or node not in_degree), we add that to the ...
1
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _i...
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
Python + 2 pointers + Explanation.
minimum-number-of-moves-to-make-palindrome
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n # At each point, we look at the first and the last elements\n # if they are the same, then we skip them, else we find\n # another element in the string ...
1
You are given a string `s` consisting only of lowercase English letters. In one **move**, you can select any two **adjacent** characters of `s` and swap them. Return _the **minimum number of moves** needed to make_ `s` _a palindrome_. **Note** that the input will be generated such that `s` can always be converted to...
Think about how dynamic programming can help solve the problem. For any fixed cell (r, c), can you calculate the maximum height of the pyramid for which it is the apex? Let us denote this value as dp[r][c]. How will the values at dp[r+1][c-1] and dp[r+1][c+1] help in determining the value at dp[r][c]? For the cell (r, ...
Python + 2 pointers + Explanation.
minimum-number-of-moves-to-make-palindrome
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n # At each point, we look at the first and the last elements\n # if they are the same, then we skip them, else we find\n # another element in the string ...
1
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
[python3] easy to understand 2 pointer solution with comments
minimum-number-of-moves-to-make-palindrome
0
1
```\n\'\'\'\nidea is to fix one side (left or right) and make other side equal to it\nfor e.g. \naabb , I will make right side equal to left.\n1. index[0] = a != index[3] = b \n2. now look for a from right to left \n3. once found swap with adjacent element till it reaches index[3].\n4. abba. is palindrome. took 2 swaps...
1
You are given a string `s` consisting only of lowercase English letters. In one **move**, you can select any two **adjacent** characters of `s` and swap them. Return _the **minimum number of moves** needed to make_ `s` _a palindrome_. **Note** that the input will be generated such that `s` can always be converted to...
Think about how dynamic programming can help solve the problem. For any fixed cell (r, c), can you calculate the maximum height of the pyramid for which it is the apex? Let us denote this value as dp[r][c]. How will the values at dp[r+1][c-1] and dp[r+1][c+1] help in determining the value at dp[r][c]? For the cell (r, ...
[python3] easy to understand 2 pointer solution with comments
minimum-number-of-moves-to-make-palindrome
0
1
```\n\'\'\'\nidea is to fix one side (left or right) and make other side equal to it\nfor e.g. \naabb , I will make right side equal to left.\n1. index[0] = a != index[3] = b \n2. now look for a from right to left \n3. once found swap with adjacent element till it reaches index[3].\n4. abba. is palindrome. took 2 swaps...
1
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Straightforward Brute-Force in Python, Beating 100%
minimum-number-of-moves-to-make-palindrome
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nIn each turn, it is necessary to match the first character `s[0]` and the last charactor `s[-1]` of the string `s`. Do nothing if the first and the last ones already match (i.e., `s[0] == s[-1]`). Otherwise, my greedy approach determines to replace th...
1
You are given a string `s` consisting only of lowercase English letters. In one **move**, you can select any two **adjacent** characters of `s` and swap them. Return _the **minimum number of moves** needed to make_ `s` _a palindrome_. **Note** that the input will be generated such that `s` can always be converted to...
Think about how dynamic programming can help solve the problem. For any fixed cell (r, c), can you calculate the maximum height of the pyramid for which it is the apex? Let us denote this value as dp[r][c]. How will the values at dp[r+1][c-1] and dp[r+1][c+1] help in determining the value at dp[r][c]? For the cell (r, ...
Straightforward Brute-Force in Python, Beating 100%
minimum-number-of-moves-to-make-palindrome
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nIn each turn, it is necessary to match the first character `s[0]` and the last charactor `s[-1]` of the string `s`. Do nothing if the first and the last ones already match (i.e., `s[0] == s[-1]`). Otherwise, my greedy approach determines to replace th...
1
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Python Greedy 2 pointer
minimum-number-of-moves-to-make-palindrome
0
1
\tclass Solution:\n\t\tdef minMovesToMakePalindrome(self, s: str) -> int:\n\t\t\ts = list(s) #makes it easy for assignment op\n\n\t\t\tres = 0\n\t\t\tleft, right = 0, len(s) - 1\n\n\t\t\twhile left < right:\n\t\t\t\tl, r = left, right\n\n\t\t\t\t#find matching char\n\t\t\t\twhile s[l] != s[r]:\n\t\t\t\t\tr -= 1\n\n\t\t...
2
You are given a string `s` consisting only of lowercase English letters. In one **move**, you can select any two **adjacent** characters of `s` and swap them. Return _the **minimum number of moves** needed to make_ `s` _a palindrome_. **Note** that the input will be generated such that `s` can always be converted to...
Think about how dynamic programming can help solve the problem. For any fixed cell (r, c), can you calculate the maximum height of the pyramid for which it is the apex? Let us denote this value as dp[r][c]. How will the values at dp[r+1][c-1] and dp[r+1][c+1] help in determining the value at dp[r][c]? For the cell (r, ...
Python Greedy 2 pointer
minimum-number-of-moves-to-make-palindrome
0
1
\tclass Solution:\n\t\tdef minMovesToMakePalindrome(self, s: str) -> int:\n\t\t\ts = list(s) #makes it easy for assignment op\n\n\t\t\tres = 0\n\t\t\tleft, right = 0, len(s) - 1\n\n\t\t\twhile left < right:\n\t\t\t\tl, r = left, right\n\n\t\t\t\t#find matching char\n\t\t\t\twhile s[l] != s[r]:\n\t\t\t\t\tr -= 1\n\n\t\t...
2
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
The Finest and Simple Solution
cells-in-a-range-on-an-excel-sheet
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
A cell `(r, c)` of an excel sheet is represented as a string `" "` where: * denotes the column number `c` of the cell. It is represented by **alphabetical letters**. * For example, the `1st` column is denoted by `'A'`, the `2nd` by `'B'`, the `3rd` by `'C'`, and so on. * is the row number `r` of the cell. Th...
null
[Java/Python 3] Simple code w/ analysis.
cells-in-a-range-on-an-excel-sheet
1
1
\n\n```java\n public List<String> cellsInRange(String s) {\n char c1 = s.charAt(0), c2 = s.charAt(3);\n char r1 = s.charAt(1), r2 = s.charAt(4);\n List<String> cells = new ArrayList<>();\n for (char c = c1; c <= c2; ++c) {\n for (char r = r1; r <= r2; ++r) {\n ce...
43
A cell `(r, c)` of an excel sheet is represented as a string `" "` where: * denotes the column number `c` of the cell. It is represented by **alphabetical letters**. * For example, the `1st` column is denoted by `'A'`, the `2nd` by `'B'`, the `3rd` by `'C'`, and so on. * is the row number `r` of the cell. Th...
null
🔥[Python 3] Two loops + 1 line bonus, beats 97% 🥷🏼
cells-in-a-range-on-an-excel-sheet
0
1
```python3 []\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n res = []\n for ch in range(ord(s[0]), ord(s[3])+1):\n for i in range(int(s[1]), int(s[4])+1):\n res.append(f\'{chr(ch)}{i}\')\n return res\n```\n```python3 []\nclass Solution:\n def cells...
4
A cell `(r, c)` of an excel sheet is represented as a string `" "` where: * denotes the column number `c` of the cell. It is represented by **alphabetical letters**. * For example, the `1st` column is denoted by `'A'`, the `2nd` by `'B'`, the `3rd` by `'C'`, and so on. * is the row number `r` of the cell. Th...
null
Simple Python3 | NO ord(), NO chr()
cells-in-a-range-on-an-excel-sheet
0
1
```\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n start, end = s.split(\':\')\n start_letter, start_num = start[0], int(start[-1])\n end_letter, end_num = end[0], int(end[1])\n alphabet = list(\'ABCDEFGHIJKLMNOPQRSTUVWXYZ\')\n alphabet_slice = \\\n al...
2
A cell `(r, c)` of an excel sheet is represented as a string `" "` where: * denotes the column number `c` of the cell. It is represented by **alphabetical letters**. * For example, the `1st` column is denoted by `'A'`, the `2nd` by `'B'`, the `3rd` by `'C'`, and so on. * is the row number `r` of the cell. Th...
null
[Python3] 1-line
cells-in-a-range-on-an-excel-sheet
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/bb5647e856ff11b072f9c51a140e0f243c100171) for solutions of weekly 283.\n\n```\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n return [chr(c)+str(r) for c in range(ord(s[0]), ord(s[3])+1) for r in range(int(s[1]), int(s[4...
10
A cell `(r, c)` of an excel sheet is represented as a string `" "` where: * denotes the column number `c` of the cell. It is represented by **alphabetical letters**. * For example, the `1st` column is denoted by `'A'`, the `2nd` by `'B'`, the `3rd` by `'C'`, and so on. * is the row number `r` of the cell. Th...
null
Python Solution using AP Sum Explained
append-k-integers-with-minimal-sum
0
1
**Idea Used:**\nHere we use the idea of adding the sum of values that exist b/w all consecutive values until we expire all k given to us. \n\n**Steps:**\n\n1. Sort the numbers and add 0 to the start and 2000000001 to the end of the list.\n2. Now go through all the n values of nums\n3. For each iteration select ith valu...
8
You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appended to_ `nums`. **Example 1:** **Input:** nums = \[1,4,25,10,25\], k = 2 **Output:*...
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
[Java/Python 3] Two methods w/ brief explanation and analysis.
append-k-integers-with-minimal-sum
1
1
**Method 1:**\nSort and Track low missing bound and compute the arithmetic sequence.\n\n1. Sort the input;\n2. Starting from `1` as the lower bound of the missing range, then based on current `num` and `k`, determine current missing upper bound `hi`; Compute the subtotal in [lo, hi] and add it to `ans`.\n```java\n p...
17
You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appended to_ `nums`. **Example 1:** **Input:** nums = \[1,4,25,10,25\], k = 2 **Output:*...
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
[Python3] swap
append-k-integers-with-minimal-sum
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/bb5647e856ff11b072f9c51a140e0f243c100171) for solutions of weekly 283.\n\n```\nclass Solution:\n def minimalKSum(self, nums: List[int], k: int) -> int:\n ans = k*(k+1)//2\n prev = -inf \n for x in sorted(nums): \n ...
10
You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appended to_ `nums`. **Example 1:** **Input:** nums = \[1,4,25,10,25\], k = 2 **Output:*...
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
Python Explanation || sort and add
append-k-integers-with-minimal-sum
0
1
**Idea:** \n* As we need samllest sum possible we need to choose smallest numbers that we can add.\n* To get smallest numbers we need to sort `nums` first.\n* Then append the numbers which are between suppose `(prev,curr)` or `(nums[i],nums[i+1])`.\n* This way we can get smallest numbers possible.\n* Now we need to tak...
8
You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appended to_ `nums`. **Example 1:** **Input:** nums = \[1,4,25,10,25\], k = 2 **Output:*...
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
Easy & explained python solution || faster than 99%
append-k-integers-with-minimal-sum
0
1
the idea is to find the last (biggest) number we gonna add to the list, by incrementing k by 1 each time we find a smaller number than it in the sorted list.\nafter that, we calculate the sum from 1 to the last added number, and remove the sum of the existing numbers (removable_sum).\nfor example, if k was 50 and the l...
5
You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appended to_ `nums`. **Example 1:** **Input:** nums = \[1,4,25,10,25\], k = 2 **Output:*...
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
Python | math solution with explanation
append-k-integers-with-minimal-sum
0
1
\n# Approach\nThe general idea is like: if element in array is <=k, we need to expand k to k+1 to make get first k element not in the array possible. If the element <=k, we need to sum them together, so the final result is k*(k+1)//2-sum of the appeared element.\n\nDetail is as follows:\nFirst let the element in the ar...
4
You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appended to_ `nums`. **Example 1:** **Input:** nums = \[1,4,25,10,25\], k = 2 **Output:*...
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
Python O(nlogn) solution with n(n+1) / 2 Range Sum
append-k-integers-with-minimal-sum
0
1
My first approach was the naive **O(n + k)** time but due to the large magnitude of k I was experiencing TLE.\n\n**New Approach: O(nlogn)**\n\n1) Sort nums: (The intution is that the "gaps" between adjacent sorted elements is space where we can add our k items"\n2) Define range sum n (n+1) / 2\n3) Iterate through these...
4
You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appended to_ `nums`. **Example 1:** **Input:** nums = \[1,4,25,10,25\], k = 2 **Output:*...
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
python | O(nlogn) solution using sort | 97.65% faster
append-k-integers-with-minimal-sum
0
1
A straightforward solution would be to initialize the sum with zero, search for the smallest integers that are not in `nums`, and add them to the sum. However, this approach would yield a TLE because the range we are searching within could be as big as `1e9`. \n\nTherefore, working within the range of `len(nums)` would...
1
You are given an integer array `nums` and an integer `k`. Append `k` **unique positive** integers that do **not** appear in `nums` to `nums` such that the resulting total sum is **minimum**. Return _the sum of the_ `k` _integers appended to_ `nums`. **Example 1:** **Input:** nums = \[1,4,25,10,25\], k = 2 **Output:*...
Loop through the line of people and decrement the number of tickets for each to buy one at a time as if simulating the line moving forward. Keep track of how many tickets have been sold up until person k has no more tickets to buy. Remember that those who have no more tickets to buy will leave the line.
Simple solution with HashMap in Python3
create-binary-tree-from-descriptions
0
1
# Intuition\nHere we have:\n- list of `descriptions`, that consists with `[parent, child, isLeft]`\n- our goal is to **restore** a **Binary Search tree** from that list\n\nAn algorithm is **simple**: use **HashMap** to associate **node values** with nodes.\n\nThe catchiest thing is to find **a root**.\nBut remember, th...
1
You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore, * If `isLefti == 1`, then `childi` is the left child of `parenti`. * If `isLefti == 0`, then `childi` i...
Consider the list structure ...A → (B → ... → C) → D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B → ... → C reversed (because it was of even length) so that it is ...
[Java/Python 3] 2 codes: HashMap and BFS, w/ brief explanation and analysis.
create-binary-tree-from-descriptions
1
1
**Q & A:**\nQ1: How to get root?\nA1: The node that does NOT have any parent is the root.\nUse `2` sets to store parents and kids respectively; from the `keySet()` of `valToNode`, `parents`, remove all `kids`, there must be one remaining, the root.\n\n**End of Q & A**\n\n**HashMap**\n\n```java\n public TreeNode crea...
20
You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore, * If `isLefti == 1`, then `childi` is the left child of `parenti`. * If `isLefti == 0`, then `childi` i...
Consider the list structure ...A → (B → ... → C) → D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B → ... → C reversed (because it was of even length) so that it is ...
[Python3] simulation
create-binary-tree-from-descriptions
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/bb5647e856ff11b072f9c51a140e0f243c100171) for solutions of weekly 283.\n\n```\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n mp = {}\n seen = set()\n for p, c, left in d...
13
You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore, * If `isLefti == 1`, then `childi` is the left child of `parenti`. * If `isLefti == 0`, then `childi` i...
Consider the list structure ...A → (B → ... → C) → D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B → ... → C reversed (because it was of even length) so that it is ...
Python Solution using HashMap with Steps
create-binary-tree-from-descriptions
0
1
Here we use a HashMap to keep track of node values and their references along with the fact if that node has a parent or not. We develop the Binary Tree as we go along. Finally we check which node has no parent as that node is the root node.\n1. Maintain a hash map with the keys being node values and value being a list...
5
You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore, * If `isLefti == 1`, then `childi` is the left child of `parenti`. * If `isLefti == 0`, then `childi` i...
Consider the list structure ...A → (B → ... → C) → D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B → ... → C reversed (because it was of even length) so that it is ...
Python | Dictonary | Recursion
create-binary-tree-from-descriptions
0
1
create a tree dict to store all the child node\ncreate a dict to find the parent node\n\nuse recursion to form the tree. \n\n\n\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.rig...
4
You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore, * If `isLefti == 1`, then `childi` is the left child of `parenti`. * If `isLefti == 0`, then `childi` i...
Consider the list structure ...A → (B → ... → C) → D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B → ... → C reversed (because it was of even length) so that it is ...
[ Python ] Faster then 100% solution
create-binary-tree-from-descriptions
0
1
```\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n \n tree = dict()\n children = set()\n for parent, child, isLeft in descriptions:\n if parent not in tree : tree[parent] = TreeNode(parent)\n if child not in tree...
8
You are given a 2D integer array `descriptions` where `descriptions[i] = [parenti, childi, isLefti]` indicates that `parenti` is the **parent** of `childi` in a **binary** tree of **unique** values. Furthermore, * If `isLefti == 1`, then `childi` is the left child of `parenti`. * If `isLefti == 0`, then `childi` i...
Consider the list structure ...A → (B → ... → C) → D..., where the nodes between B and C (inclusive) form a group, A is the last node of the previous group, and D is the first node of the next group. How can you utilize this structure? Suppose you have B → ... → C reversed (because it was of even length) so that it is ...
Doubly-Linked List in Python
replace-non-coprime-numbers-in-array
0
1
By using doubly linked list, you can access the deletable pair in O(1) time.\nEvery time you delete some pair, you need to add a new node with the value of lcm. Also, it might be possible that one of the pair is already deleted, so you need to keep track of which nodes are already deleted. (`wasted` stores all the fini...
3
You are given an array of integers `nums`. Perform the following steps: 1. Find **any** two **adjacent** numbers in `nums` that are **non-coprime**. 2. If no such numbers are found, **stop** the process. 3. Otherwise, delete the two numbers and **replace** them with their **LCM (Least Common Multiple)**. 4. **Repe...
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?
Easiest Python Code | 7 Line Code | 99% faster | Stack
replace-non-coprime-numbers-in-array
0
1
# Complexity\n- Time complexity: $$O(nlogn)$$\n\n- Space complexity: $$O(nlogn)$$\n\n# Code\n```\nclass Solution:\n def replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n stack = []\n for i in nums:\n toBeAppended = i\n while stack and gcd(stack[-1], toBeAppended) > 1:\n ...
4
You are given an array of integers `nums`. Perform the following steps: 1. Find **any** two **adjacent** numbers in `nums` that are **non-coprime**. 2. If no such numbers are found, **stop** the process. 3. Otherwise, delete the two numbers and **replace** them with their **LCM (Least Common Multiple)**. 4. **Repe...
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?
[Python 3] Stack solution
replace-non-coprime-numbers-in-array
0
1
```\nclass Solution:\n def replaceNonCoprimes(self, nums: List[int]) -> List[int]: \n\n stack = nums[:1]\n \n for j in range(1, len(nums)):\n cur = nums[j]\n while stack and math.gcd(stack[-1], cur) > 1:\n prev = stack.pop()\n cur = math....
2
You are given an array of integers `nums`. Perform the following steps: 1. Find **any** two **adjacent** numbers in `nums` that are **non-coprime**. 2. If no such numbers are found, **stop** the process. 3. Otherwise, delete the two numbers and **replace** them with their **LCM (Least Common Multiple)**. 4. **Repe...
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?
[Python3] stack
replace-non-coprime-numbers-in-array
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/bb5647e856ff11b072f9c51a140e0f243c100171) for solutions of weekly 283.\n\n```\nclass Solution:\n def replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n stack = []\n for x in nums: \n while stack and gcd(stack[-1],...
2
You are given an array of integers `nums`. Perform the following steps: 1. Find **any** two **adjacent** numbers in `nums` that are **non-coprime**. 2. If no such numbers are found, **stop** the process. 3. Otherwise, delete the two numbers and **replace** them with their **LCM (Least Common Multiple)**. 4. **Repe...
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?
One Trick to make this an LC Easy - Fastest O(n) python + Optimized for O(1) memory
replace-non-coprime-numbers-in-array
0
1
# Intuition\nAny result in the output will have to be a merge of a subarray or elements, what is that output value going to be?\nWell it has to be the LCM of all the numbers in the subarray that got merged.\n\n# Approach\nConceptually we use a stack to output the result greedily backtracking as when neccesary. We can t...
0
You are given an array of integers `nums`. Perform the following steps: 1. Find **any** two **adjacent** numbers in `nums` that are **non-coprime**. 2. If no such numbers are found, **stop** the process. 3. Otherwise, delete the two numbers and **replace** them with their **LCM (Least Common Multiple)**. 4. **Repe...
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?